XNU as a loadable kernel module inside Linux (macOS personality for arm64 Linux)
C
Application launch, wakeup latency and frame rate on a DGX Spark (#26)
秋 奈月7ed7153bd34b
diff --git a/gpu/venus/patches/0007-venus-one-queue-per-family-on-macos.patch b/gpu/venus/patches/0007-venus-one-queue-per-family-on-macos.patchnew file mode 100644index 0000000..10b07df--- /dev/null+++ b/gpu/venus/patches/0007-venus-one-queue-per-family-on-macos.patch@@ -0,0 +1,35 @@+Upstream: Mesa 26.3.1 (https://archive.mesa3d.org/mesa-26.3.1.tar.xz)+Upstream-License: MIT+Patch-License: MIT (provided under the same license as upstream)+Subject: venus: one queue of each family on macOS++Each queue a device is created with is one the host's driver makes. NVIDIA's (GB10, 580) takes about 150 ms to create+a queue and 40 ms to destroy one: a device with the 16 queues of its first family takes 2.6 s to create, one with a+single queue 0.33 s. The Metal layer asks for every queue a family offers, in every process that makes a Metal device,+so each application spent its first seconds there with its main thread waiting. One queue of a family is offered;+VN_QUEUES_PER_FAMILY=n offers up to n.++--- a/src/virtio/vulkan/vn_physical_device.c++++ b/src/virtio/vulkan/vn_physical_device.c+@@ -1005,6 +1005,21 @@+ }+ }+++#if DETECT_OS_APPLE++ /* A queue asked for is a queue the host driver makes, and some take long over each: NVIDIA's 150 ms to create and++ * 40 ms to destroy (a device with the 16 queues of its first family: 2.6 s). An application that takes every queue++ * on offer pays that at each start, so one queue of a family is offered (VN_QUEUES_PER_FAMILY=n for more).++ */++ {++ const char *limit_str = os_get_option("VN_QUEUES_PER_FAMILY");++ const uint32_t limit = limit_str && atoi(limit_str) > 0 ? (uint32_t)atoi(limit_str) : 1;++ for (uint32_t i = 0; i < count; i++) {++ if (qfp[i].queueFamilyProperties.queueCount > limit)++ qfp[i].queueFamilyProperties.queueCount = limit;++ }++ }++#endif+++ if (VN_DEBUG(NO_SPARSE))+ physical_dev->sparse_binding_disabled = true;+diff --git a/gpu/venus/patches/0008-venus-no-host-image-copy-on-macos.patch b/gpu/venus/patches/0008-venus-no-host-image-copy-on-macos.patchnew file mode 100644index 0000000..c5c3e05--- /dev/null+++ b/gpu/venus/patches/0008-venus-no-host-image-copy-on-macos.patch@@ -0,0 +1,30 @@+Upstream: Mesa 26.3.1 (https://archive.mesa3d.org/mesa-26.3.1.tar.xz)+Upstream-License: MIT+Patch-License: MIT (provided under the same license as upstream)+Subject: venus: no host image copy on macOS++A host image copy (VK_EXT_host_image_copy) is the host driver's to carry out. NVIDIA's (GB10, 580) maps the whole+memory object the image is in for each one, 64 MB in 13 ms, and unmaps it again. The Metal layer reads every frame+WindowServer draws back into its IOSurface that way, twice or more a frame: the renderer's thread spent two thirds of+a CPU in mmap with the GPU 2% busy, and the desktop showed 9 to 23 frames a second. Without the feature the Metal+layer reads back through a buffer: about 50 frames a second, the renderer's thread at 11%. VN_HOST_IMAGE_COPY=1+offers the feature again.++--- a/src/virtio/vulkan/vn_physical_device.c++++ b/src/virtio/vulkan/vn_physical_device.c+@@ -484,6 +484,15 @@+ feats->extendedDynamicState3RepresentativeFragmentTestEnable = false;+ feats->extendedDynamicState3ShadingRateImageEnable = false;+ }++++#if DETECT_OS_APPLE++ /* A host image copy is the host driver's to carry out, and NVIDIA's maps the whole memory object the image is in++ * for each one (64 MB, 13 ms) and unmaps it again: the Metal layer reads every frame WindowServer draws back that++ * way. Without the feature it reads back through a buffer (VN_HOST_IMAGE_COPY=1 offers it again).++ */++ if (!debug_get_bool_option("VN_HOST_IMAGE_COPY", false))++ feats->hostImageCopy = false;++#endif+ }++ static voiddiff --git a/gpu/xnu-cpu-metal/src/xnu-cpu-metal-bundle/XnuCpuMetalPlugin.mm b/gpu/xnu-cpu-metal/src/xnu-cpu-metal-bundle/XnuCpuMetalPlugin.mmindex f9c3001..460968f 100644--- a/gpu/xnu-cpu-metal/src/xnu-cpu-metal-bundle/XnuCpuMetalPlugin.mm+++ b/gpu/xnu-cpu-metal/src/xnu-cpu-metal-bundle/XnuCpuMetalPlugin.mm@@ -1,4 +1,5 @@// SPDX-License-Identifier: GPL-2.0-or-later+#include <os/lock.h>#include <objc/message.h>// XnuCpuMetal.bundle — Pure-CPU Metal plugin for xnulinux (macOS 27).// Principal class: XnuCpuMetalDevice (subclass of IOGPUMetalDevice).@@ -2390,8 +2391,30 @@ static NSUInteger xcmDev_rwTexTier(id, SEL) { return MTLReadWriteTextureTier2; }static BOOL xcmDev_yes(id, SEL) { return YES; }static BOOL xcmDev_supportsSampleCount(id, SEL, NSUInteger c) { return c == 1; }static BOOL xcmDev_supportsFeatureSet(id, SEL, NSUInteger) { return YES; }+// A device's families do not change, and the bridge audits its whole format table to answer for one. Metal asks+// several times for every MTLPixelFormatGetInfoForDevice, which CoreAnimation calls for each surface it makes: half of+// WindowServer's time in a display update went there. Each answer is kept (per device, a handful of families).+static bool xcmBridgeSupportsFamily(int64_t family) {+ static os_unfair_lock lock = OS_UNFAIR_LOCK_INIT;+ static const void *dev;+ static struct { int64_t family; bool yes; } known[32];+ static unsigned n;+ const void *d = gXm2vDevice;+ if (!d) return false;+ os_unfair_lock_lock(&lock);+ if (dev != d) { dev = d; n = 0; }+ for (unsigned i = 0; i < n; i++) {+ if (known[i].family == family) { bool yes = known[i].yes; os_unfair_lock_unlock(&lock); return yes; }+ }+ os_unfair_lock_unlock(&lock);+ bool yes = xm2v_device_supports_family(gXm2vDevice, family);+ os_unfair_lock_lock(&lock);+ if (dev == d && n < sizeof(known) / sizeof(known[0])) { known[n].family = family; known[n].yes = yes; n++; }+ os_unfair_lock_unlock(&lock);+ return yes;+}static BOOL xcmDev_supportsFamily(id, SEL, MTLGPUFamily family) {- if (gXm2vDevice && xm2v_device_supports_family(gXm2vDevice, (int64_t)family)) return YES;+ if (xcmBridgeSupportsFamily((int64_t)family)) return YES;// Report Apple1/Apple2, Mac1/Mac2, Common1..3 so QuartzCore enables framebuffer fetch (programmable blending)// and standard macOS/Apple GPU paths that lavapipe + metal2vulkan support.switch ((int64_t)family) {diff --git a/kexts/XnuSysCfg/XnuSysCfg.cpp b/kexts/XnuSysCfg/XnuSysCfg.cppnew file mode 100644index 0000000..f3ee7c3--- /dev/null+++ b/kexts/XnuSysCfg/XnuSysCfg.cpp@@ -0,0 +1,34 @@+// SPDX-License-Identifier: APSL-2.0+// XnuSysCfg: the service MobileGestalt reads the machine's system configuration (syscfg) from, with nothing in it.+//+// libMobileGestalt, in every process that asks it for a syscfg key (AppKit does while NSApplication starts, for the+// system appearance), looks for the syscfg in /chosen (syscfg-v2-data), then for the IOService+// AppleDiagnosticDataAccessReadOnly, and when there is none waits five seconds for one to appear ("giving up waiting for+// match - runloop result is 3") before answering that the key is not there. The hosted system has neither, so every+// application spent its first five seconds in that wait. This is that service's name with no syscfg behind it and no+// user client: the lookup finds it at once, fails to read from it, and MobileGestalt gives the same answer without waiting.+#include <IOKit/IOLib.h>+#include <IOKit/IOService.h>++class AppleDiagnosticDataAccessReadOnly : public IOService {+ OSDeclareDefaultStructors(AppleDiagnosticDataAccessReadOnly)++public:+ bool start(IOService *provider) override+ {+ if (!IOService::start(provider))+ return false;+ setName("AppleDiagnosticData");+ registerService();+ return true;+ }+};++OSDefineMetaClassAndStructors(AppleDiagnosticDataAccessReadOnly, IOService)++// Module start/stop for the collection's kext entry; the driver starts through IOKit matching.+#include <mach/kmod.h>+extern "C" {+kern_return_t native_kext_start(kmod_info_t *, void *) { return KERN_SUCCESS; }+kern_return_t native_kext_stop(kmod_info_t *, void *) { return KERN_SUCCESS; }+}diff --git a/kexts/XnuSysCfg/XnuSysCfg.json b/kexts/XnuSysCfg/XnuSysCfg.jsonnew file mode 100644index 0000000..83aa5f9--- /dev/null+++ b/kexts/XnuSysCfg/XnuSysCfg.json@@ -0,0 +1,22 @@+{+ "name": "XnuSysCfg",+ "bundle": "org.xnulinux.driver.XnuSysCfg",+ "version": "1.0.0",+ "objects": "out/x12377/native-kexts/XnuSysCfg/objects.json",+ "start": "_native_kext_start",+ "stop": "_native_kext_stop",+ "libraries": {+ "com.apple.kpi.iokit": "18.0.0",+ "com.apple.kpi.libkern": "18.0.0",+ "com.apple.kpi.mach": "18.0.0"+ },+ "personalities": {+ "XnuSysCfg": {+ "CFBundleIdentifier": "org.xnulinux.driver.XnuSysCfg",+ "IOClass": "AppleDiagnosticDataAccessReadOnly",+ "IOProviderClass": "IOResources",+ "IOResourceMatch": "IOKit",+ "IOMatchCategory": "XnuSysCfg"+ }+ }+}diff --git a/scripts/xnulinux-boot.sh b/scripts/xnulinux-boot.shindex 7f0cd5c..ee3835b 100755--- a/scripts/xnulinux-boot.sh+++ b/scripts/xnulinux-boot.sh@@ -28,6 +28,7 @@ if [ "${1:-}" = stop ]; then # end the running hosted system (its disk synced fifor _ in $(seq 1 600); do pgrep -f "insmod xnu-ko/xnu.ko" >/dev/null || break; sleep 0.2; doneif [ -d /sys/module/xnu ]; then sudo rmmod xnu; fisudo systemctl stop xnudrmd 2>/dev/null || true+ for f in /sys/devices/system/cpu/cpu*/cpuidle/state[1-9]*/disable; do [ -e "$f" ] && echo 0 | sudo tee "$f" >/dev/null 2>&1 || true; done # XNU's CPUs are Linux's againecho "hosted system stopped"exitfi@@ -88,6 +89,12 @@ print(format(m, 'x'))")for f in /proc/irq/*/smp_affinity; do echo "$MASK" | sudo tee "$f" >/dev/null 2>&1 || true; doneHOSTCPUS=$(python3 -c "print(','.join(str(c) for c in range($NCPU) if 0x$MASK >> c & 1))")fi+# XNU's CPUs stay out of Linux's deep idle states: a hosted CPU with nothing to run sleeps in Linux, and waking it from+# one (a thread made runnable on another CPU: every Mach message) took 0.6 ms on average on a DGX Spark, 10 us without.+XLIST=$(python3 -c "print(' '.join(str(c) for c in ([int(c) for c in '$(cat /sys/module/fki/parameters/cpu_list 2>/dev/null | tr -d '\n')'.split(',') if c][:$CPUS] or list(range($CPUS)))))")+for c in $XLIST; do+ for f in /sys/devices/system/cpu/cpu$c/cpuidle/state[1-9]*/disable; do [ -e "$f" ] && echo 1 | sudo tee "$f" >/dev/null 2>&1 || true; done+done# Start xnudrmd BEFORE insmod xnu.ko and wait until it has opened /dev/xnu-hostcall and is serving:# fast-booting guests (e.g. 16K pages) can open XnuDrm within ~4-5 s of insmod; restarting xnudrmd after# insmod kills live DRM/Venus clients out from under WindowServer. Never restart xnudrmd while XNU runs.diff --git a/tools/dgx-spark/README.md b/tools/dgx-spark/README.mdindex d22e8a4..c9ee17b 100644--- a/tools/dgx-spark/README.md+++ b/tools/dgx-spark/README.md@@ -14,6 +14,9 @@ and CPU numbers are that machine's.- NetworkManager takes `xnu0` and removes its address unless told not to:`unmanaged-devices=interface-name:xnu0` in `/etc/NetworkManager/conf.d/`.- The counter runs at 1 GHz: xnu.ko has XNU scale it to 24 MHz, which Apple's user space assumes.+- `xnulinux-boot.sh` keeps XNU's CPUs out of Linux's deep idle state (`LPI-1`, 133 us nominal): a hosted CPU with+ nothing to run sleeps in Linux, and a thread woken on one took 0.6 ms on average (144 ms at worst) to run, 19 us+ without it.## GPU@@ -26,6 +29,22 @@ The backend's shared memory is Linux's 4 KB pages, not contiguous, and XnuDrm capages (`map handle ...: 0xe00002bd`; every client then falls back to the software renderer): `xnulinux-boot.sh` startsXNU with `vm16k=0` when xnudrmd serves this backend.+NVIDIA's driver (580) on this machine, measured natively:++- One process gets about 512 open device files and a context with a device holds 10 to 75, so the render server runs+ a process for each context (`-Drender-server-worker=process`). With every context in one process `vkCreateDevice`+ failed from about the twentieth client on and the Metal layer took the next device, the host's llvmpipe.+ Memory, with 24 contexts (a desktop after login): 4.7 GB in all as PSS, about 190 MB a process (2.7 GB anonymous,+ 2.0 GB mapped files). The RSS figures add up to 9.4 GB (about 350 MB a process, 610 MB for WindowServer's) because+ each counts the driver's libraries again. One process with about 20 contexts as threads was 3.5 to 4.9 GB. The+ contexts hold 4.6 GB of GPU memory besides, either way.+- `vkCreateDevice` takes 0.33 s with one queue and 0.15 s more for each further one (16 queues: 2.6 s; destroying+ them 0.6 s). The Venus driver offers one queue of a family (`gpu/venus/patches/0007`): a Metal device is made in+ every application, with its main thread waiting.+- A host image copy (`VK_EXT_host_image_copy`) maps the whole memory object the image is in, 64 MB in 13 ms, and+ unmaps it again. The Metal layer read every frame WindowServer drew back that way: 9 to 23 frames a second with the+ GPU 2% busy. The Venus driver does not offer the feature (`gpu/venus/patches/0008`): about 50.+## In a KVM guest`guest/`: an arm64 Ubuntu guest under KVM, QEMU run from a container (`Dockerfile`, `run-vm.sh`, `vm.sh`); KVM on thediff --git a/tools/dgx-spark/gpu/build-virglrenderer.sh b/tools/dgx-spark/gpu/build-virglrenderer.shindex 5d891e2..a1fbe3b 100755--- a/tools/dgx-spark/gpu/build-virglrenderer.sh+++ b/tools/dgx-spark/gpu/build-virglrenderer.sh@@ -10,7 +10,11 @@ sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq build-essential meson[ -f virglrenderer-$V.tar.gz ] || curl -sSLo virglrenderer-$V.tar.gz \https://gitlab.freedesktop.org/virgl/virglrenderer/-/archive/$V/virglrenderer-$V.tar.gzrm -rf src && mkdir src && tar -C src --strip-components=1 -xf virglrenderer-$V.tar.gz-meson setup src/build src --prefix=/usr/local --buildtype=release -Dvenus=true -Drender-server-worker=thread >/dev/null+# A process for each context (the default), not a thread: NVIDIA's driver gives one process about 512 open device files,+# a context with a device holds 10 to 75 of them, and past that vkCreateDevice fails (VK_ERROR_INITIALIZATION_FAILED):+# with every context in one process the twentieth-odd client of a macOS desktop got the software renderer instead.+# One context's crash also no longer takes the others' with it.+meson setup src/build src --prefix=/usr/local --buildtype=release -Dvenus=true -Drender-server-worker=process >/dev/nullninja -C src/build > ninja.log 2>&1 || { grep -E "error|FAILED" ninja.log | head -30; exit 1; }sudo ninja -C src/build install >/dev/nullsudo ldconfig