XNU as a loadable kernel module inside Linux (macOS personality for arm64 Linux)
C
tools/dgx-spark: what was set on the machine, without the session log and the scripts tied to one disk
Heyang Zhou049b76d2b533
diff --git a/LICENSE b/LICENSEindex de08783..afec7f0 100644--- a/LICENSE+++ b/LICENSE@@ -1,7 +1,7 @@xnulinux is made of parts under different licenses, kept apart along the line between the Linux kernel and XNU.Each source file names its license in an SPDX-License-Identifier line; the full texts are in LICENSES/:- GPL-2.0-only fki-ko/, linux/, scripts/, tools/, tests/, docs/, gpu/xnu-drm/xnudrmd.c, gpu/venus/+ GPL-2.0-only fki-ko/, linux/, scripts/, tools/, tests/, docs/, gpu/xnu-drm/ (xnudrmd, test/), gpu/venus/GPL-2.0-or-later gpu/xnu-cpu-metal/APSL-2.0 xnu-ko/, xnu-patches/, kexts/BSD-2-Clause-Patent kexts/XnuDisplay/, kexts/XnuEthernet/, kexts/XnuInput/ (from macOS-DroidVM),diff --git a/NOTES.md b/NOTES.mddeleted file mode 100644index ae64da9..0000000--- a/NOTES.md+++ /dev/null@@ -1,307 +0,0 @@-# NOTES--## 2026-11-23: trying to run xnulinux on `ssh dgx` (bare-metal DGX Spark)--### Host facts (probed over ssh)-- NVIDIA GB10 (10x Cortex-X925 + 10x Cortex-A725), aarch64, bare metal, Ubuntu 24.04.5, kernel `7.0.0-1025-nvidia`.-- 4K pages, 48-bit VA, `paca pacg` present, `/dev/kvm`, `/dev/dri/renderD128` (NVIDIA).-- Kernel config: `ARM64_PTR_AUTH_KERNEL=y`, `SHADOW_CALL_STACK=y`, `RANDOMIZE_BASE=y`, `KALLSYMS_ALL=y`, `KPROBES=y`,- `CMA=y` but `CmaTotal: 0`, `SECURITY_LOCKDOWN_LSM=y`.-- **Secure Boot enabled, lockdown = integrity** (`/sys/kernel/security/lockdown`: `none [integrity] confidentiality`).-- 121 GiB RAM, ~7 GiB available: two long-running GPU services (an LLM server container, 61 GB of GPU memory, and a- TTS server, 43 GB) hold the rest.-- `sudo` needs a password (no passwordless sudo over ssh).--### What was done-- `rsync` of the repo (without `.git`, `docs/images`) to `dgx:~/xnulinux`.-- `fki.ko` and `xnu.ko` **build cleanly** against `7.0.0-1025-nvidia` headers with gcc 13.3 (one- "non-compatible type" warning at `xnu-ko/xnu_main.c:308`). Unsigned; not loaded.--### Blockers before anything can be loaded (all need the user)-1. sudo password: insmod, apt (llvm-21/clang-21/lld-21, meson, unifdef, tcsh, pax, libbsd-dev, libmd-dev, 7zip are missing- for `scripts/vm-xnu-build.sh`), `/lib/firmware/xnu`.-2. Secure Boot + lockdown=integrity: unsigned modules are refused, and lockdown blocks kprobes, which `fki_mod.c` needs- (`kallsyms_lookup_name` lookup, `__do_kernel_fault` hook). MOK signing alone is not enough; Secure Boot has to be off- (firmware setup) or lockdown lifted.-3. DRAM for XNU: no CMA area, so it needs the carve-out (`mem=` + `nokaslr` on the kernel command line, reboot), with- `carve_base` chosen from this machine's memory map (`/proc/iomem` is zeroed without root). The reboot stops the two- GPU services; 8 GB less for Linux.-4. Never tested on bare metal / this kernel: only on krunkit/tart VMs on Apple Silicon. A fault in `xnu.ko` here takes the- whole machine down (the services with it).--### Ingredients already on dgx-- the macOS 27.2 (26B123) restore IPSW (kernelcache for the kernel collection's Apple kexts).-- installed macOS 27.2 VM disks from the user's own macOS-on-KVM stack- (`mk-macvm-disk.sh` expects to run on a Mac with the disk attached; would need the disk copied to the Mac or the- script's steps redone on Linux).--### Decision (user, 2026-11-23): run it in a KVM guest on dgx, not on the bare metal--Memory survey (`dgx:~/xnulinux/mem.txt`): 117.7 GiB used of 121.7, 6.9 GiB available, swap 1.2 of 16 GiB.-- Process RSS sums to only ~11 GiB; the rest is GPU memory, which on GB10 is system RAM (unified):- - the LLM server (a docker container, restart `unless-stopped`): 60.9 GiB GPU + ~7 GiB RSS.- - the TTS server (a plain process started from an ssh session, no supervisor): 42.9 GiB GPU + 2.6 GiB RSS.-- Everything else is small. Page cache 5 GiB. No VM running.-- A 16 GiB guest does not fit until one of the two is stopped.--KVM tooling: no `qemu-system-aarch64`, `qemu-img`, AAVMF or libvirt installed (and no sudo). The user is in `kvm` and-`docker`, so QEMU can run from a container with `--device /dev/kvm`. `/boot/vmlinuz-*` is root-only.--SSH: one-shot `ssh dgx` calls were unreliable from the Mac; a persistent tmux session `dgx` was used instead.--### KVM guest on dgx (2026-11-23, after the user said to stop both services)-- Both GPU services stopped (the container with `docker stop`; the other's start command saved for the user). 117 GiB available after.-- Channel: new `ssh dgx` connections can hang; everything goes through the Mac's tmux session `dgx`- (helper used this session: paste a script through a heredoc, run it, read the output file).-- `dgx:~/xnuvm/`: `Dockerfile` (image `xnuvm-qemu`: ubuntu 24.04 + qemu-system-arm, AAVMF, cloud-image-utils),- `run-vm.sh` (container `xnuvm`, `--device /dev/kvm`, pinned to the X925 cores 5-9,15-19, `-cpu host`, 10 vCPUs, 24 GiB,- raw 300G `disk.img`, user net with ssh on 127.0.0.1:2222, serial in `console.log`), `vm.sh` (run a command in the guest- as `admin`, key `vmkey`), `stage2.sh`.-- cloud-init gotcha: user `admin` fails to create because the image already has a group `admin`; fixed with- `primary_group: admin`.-- **Works:** guest boots; **KVM on GB10 exposes PAC** (`paca pacg` in the guest), 4K pages, RAM- `0x40000000-0x640000000` (24 GiB: carve-out per `vm-install-fki-service.sh`'s 24 GB note: `LINUX_MEM=15G- CARVE_BASE=0x400000000`). HWE kernel candidate `7.0.0-38.38~24.04.4` (same series the README shows).-- In progress: `stage2.sh` installs `linux-generic-hwe-24.04`, reboots, rsyncs the repo to guest `~/w/poc`, starts- `scripts/vm-xnu-build.sh` (log: guest `~/w/xnu-build.log`).--### Result so far (2026-11-23): the XNU kernel boots inside xnu.ko in the KVM guest on GB10-- Guest on `7.0.0-43-generic` (HWE). `scripts/vm-xnu-build.sh` failed on a fresh checkout: it patched cctools' foreign- headers before the toolchain step had fetched them (`set -e` stopped it). The toolchain itself builds on arm64 as it- is; the kernel's host tools (`installhdrs`: "architecture not supported" in `foreign/mach/machine/boolean.h`) need the- patch. **Fixed in the repo (uncommitted):** `patch_cctools` runs after `setup-env.py toolchain`. With it the k27 kernel- built in ~3 min on 10 X925 cores.-- `kc27.bin`: `unzip -j <IPSW> kernelcache.release.vma2`, then blacktop `ipsw`- (v3.1.749 **linux_arm64**; DroidVM's lock names the x86_64 one) `img4 im4p extract -o kc27.bin` → guest- `~/w/dvm/out/kc/kc27.bin` (what DroidVM's `product.py inputs` does, without its 10s of GB of other members). Kept in- `dgx:~/xnuvm/kc/`.-- `scripts/vm-xnu-rebuild.sh` (needs `sudo mkdir -p /lib/firmware/xnu` first): patches applied, all 8 kexts built,- collection linked (`kc-k27.bin` 0x55a8000 bytes), AMFI platform patched 27 -> 26 (default `AMFI_PLATFORM=26`; a 27.2- disk may want 27), `/lib/firmware/xnu/{kc.bin,kernel.macho}` installed.-- Carve-out: `LINUX_MEM=15G CARVE_BASE=0x400000000 bash scripts/vm-install-fki-service.sh`, reboot: `mem=15G nokaslr`,- kernel image at `0x633a00000` (above the carve-out), `fki: 8156 MiB at 0x400000000`, `xnu0` present.-- Smoke test with an empty 1 GiB disk and fake UUIDs, no trust cache, `cpus=1`, by hand (the insmod line of- `xnulinux-boot.sh` without `trustcache=`): `Darwin Kernel Version 25.5.0 ... DEVELOPMENT_ARM64_BCM2837`, APFS kext- loaded, XnuDisk/XnuDisplay (1280x800)/XnuEthernet started, then `Waiting on ... IOMedia UUID` (no root: expected) and- idle. `xnulinux-boot.sh stop` ended it cleanly. No fault, no panic.--### Metal plugin on GitHub CI (2026-11-23, user asked for it)-- Branch `ci/metal-plugin` (pushed; main untouched): `.github/workflows/metal-plugin.yml`, macOS runner, artifact- `XnuCpuMetal.bundle` (tar.gz), lavapipe only (no Venus). Run: https://github.com/AFK-surf/xnulinux/actions/runs/45150248426-- The build scripts assume things the README does not list; the workflow recreates them: `build/pyvenv` (mako, pyyaml,- packaging), `build/vk-deps/vulkan-headers/1.4.363.0` (Vulkan-Headers `vulkan-sdk-1.4.363.0`),- `build/vk-deps/vulkan-loader/1.4.363.0/lib/libvulkan.1.4.363.dylib` (copied from `build-vkloader-arm64e.sh`'s arm64- output), Homebrew `llvm@22` (symlinked to `llvm` when there is no such formula), glslang, bison, flex, zstd, Rust- 1.100.0 and nightly with rust-src. `build-vkloader-arm64e.sh` must run before `build-m2v.sh`.-- First run: host, tools, sources, loader, lavapipe arm64 and the arm64 bridge passed; the arm64e LLVM build (cached- afterwards) was still running when last checked. arm64e lavapipe, arm64e bridge and the bundle step: not yet reached.--### A new system disk on dgx (2026-11-23)-- `dgx:~/xnuvm/mac-restore.sh`: the user's `vmapple-cli create` + `restore` from- the macOS 27.2 (26B123) restore IPSW → `~/xnuvm/mac/xnu272/{disk.img,aux.img,vm.json}`, macOS 27.2 (26B123),- 26 GiB allocated. First attempt hit the known "timed out waiting for the restore OS" USB flake; the second finished.-- Layout (own GPT/APSB scan): p2 main container: `Macintosh HD` (System), `Preboot`, `Data` (fs flags `0x100`, not the- UNENCRYPTED bit), `Recovery`, `Update`; volume group `478C06EB-C8E8-4234-B386-23433F2A8433`.-- Making it a hosted disk (what `mk-macvm-disk.sh` does) from a helper macOS guest on dgx: **does not work so far.**- - `~/xnuvm/mac/hboot.sh`: copy of a pristine install of the same build as `helper`, booted single-user (`--boot-args="-s ..."`; the- `=` is needed) with the new disk as an extra `virtio-blk-pci` through `VMAPPLE_QEMU_ARGS`; `sershell.py` types- commands on `helper/serial.sock`. The helper sees the target container (`apfs.util -p` names its volumes; disk- numbers change between boots) and has the cryptexes grafted at `/System/Cryptexes/{OS,App}`. No python3 in the guest.- - `apfs_boot_util 1` (the helper's own Data, as `vmapple-cli account` does) with the second disk attached: kernel- panic `"unencrypted data volume is not allowed" @apfs_vfsops.c:2399`. Which Data volume it was about: not determined.- - Without it there is no writable directory; mounting the target's volumes on existing directories (`/Volumes`,- `/System/Volumes/{VM,Update}`), read-write or read-only, and `mount_tmpfs`: `Operation not permitted`. SIP is- enabled in the guest (`csrutil status`).- - So from a SIP-on RELEASE guest neither Preboot/Cryptexes nor the sealed System volume of another disk can be- written. Open: SIP off in the user's vmapple stack (LocalPolicy / OpenAVB), or the Mac host with sudo and the image- served from dgx (SMB), or the target's own single-user boot for the Data-only parts.--### SIP off in the vmapple guests, and a hosted disk made entirely on dgx (2026-11-23, user: "go disable SIP")-- **SIP off:** XNU takes its CSR configuration from `/chosen/asmb` `lp-sip0` (8 bytes) in the device tree; iBoot writes it- only when the LocalPolicy says so (the node has `lp-nsih lp-spih lp-stng lp-lpnh lp-rpnh lp-hrlp`, no `lp-sip*`).- The user's QEMU already edits the tree at the kernel handoff (`target/arm/kvm.c: vmapple_handoff_apply`), so a- **separate patched copy** (`dgx:~/xnuvm/qemu-sip/`, source copied from that stack's QEMU tree,- patch script `qpatch.py` + `fix.py`, `build.sh`; the user's trees and build are untouched) adds the property when- `QEMU_VMAPPLE_LP_SIP0=<flags>` is set. The tree's `tree_len` (0x8c000) is its allocation; the tree ends at 0x8a150,- so the 44-byte entry is inserted in place. Used with `0x86f`. `csrutil status` still prints "enabled", but the- restrictions are gone: other disks' volumes mount read-write, datavault directories list.-- **Hosted trial boots** (`/etc/xnulinux.conf` in the guest: `DISK=/dev/disk/by-id/virtio-macimg GPU=off CPUS=4`;- `dgx:~/xnuvm/mac.img` is a copy of the restored disk attached to the Linux guest as a second virtio disk;- `/var/tmp/mac.conf`: `ROOT_UUID=C0513755-8E91-4456-8BD8-71475A0F7370` (apfs.util -k of "Macintosh HD"),- `BOOT_UUID=478C06EB-C8E8-4234-B386-23433F2A8433`; collection rebuilt with `AMFI_PLATFORM=27`; trust cache from the- IPSW: BuildManifest `StaticTrustCache` of `vma2macosap` → `ipsw img4 im4p extract`, 1 file, `dgx:~/xnuvm/trial/tc.py`):- 1. unmodified disk: root mounts, launchd: `Library not loaded: /usr/lib/libSystem.B.dylib` (no cryptex) → panic. Expected.- 2. after the cryptex step: launchd runs, `apfs_boot_util` (mount-phase-2) aborts: `failed to unwrap volume key`- for the Data volume. **A vmapple restore encrypts Data with that VM's keys** (fs flags 0x100, incompat 0x41);- only the installed system itself opens it (its own single-user boot does).- 3. after the Data volume was made again: **macOS 27.2 (26B123) userspace runs on the hosted kernel**: Data mounts,- root shell `xnulinux#` on the console, `sw_vers`/`uname` answer, 4 CPUs, 8 GB, 168 processes.-- **XnuDisk** (`kexts/XnuDisk/XnuDisk.cpp`, uncommitted): detects a 4096-byte-LBA GPT ("EFI PART" at byte 4096 and not- at 512). This disk turned out to have a GPT readable at 512 as well (the kext logged 512-byte blocks and Linux listed- the partitions), so the detection was not exercised.-- **Disk preparation without a Mac** (replaces `mk-macvm-disk.sh` here; all in `dgx:~/xnuvm/mac/`):- - `hboot.sh`: helper macOS guest (copy of a pristine install of the same build) single-user, SIP off, `mac.img` and `payload.img`- as extra `virtio-blk-pci` disks; `sershell.py SOCK FILE [--wait-boot]` types a command file on the serial shell- (`@SECONDS ` prefix = timeout). Target volumes found by name with `apfs.util -p` (disk numbers change every boot).- No python, `man`, `strings`, `diskutil` (diskarbitrationd exits 70) in single-user; mount points must be existing- directories (`/Volumes`, `/System/Volumes/{VM,Update}`). Do not run `apfs_boot_util` in the helper with the- target attached (kernel panic "unencrypted data volume is not allowed", seen once, before any of this).- - Cryptexes: the helper is the same build, so its own grafted `/System/Cryptexes/{OS,App}` are the source: `ditto`- to the target Preboot's `Cryptexes/{OS,App}` (2.6 GB + 40 MB) and the script's `cp -Rpn` merge into the target- System volume.- - Data: `tboot.sh` boots the restored install itself (`xnu272`, never booted before) single-user with SIP off,- `apfs_boot_util 1; 2`, then `tar -cf - <top-level names> | dd of=/dev/rdiskN ibs=65536 obs=1048576 conv=osync`- onto the raw payload disk (37289 members, 2.4 GB, no errors). Gotchas: `tar .` fails ("Couldn't visit- directory"), with SIP on TCC and other datavaults are unreadable, `dd bs=1m conv=sync` pads every short pipe read.- In the helper: `newfs_apfs -A -v Data <container>` (unencrypted; no role or group option that I know), untar,- then the overlay.- - Overlay (`dgx:~/xnuvm/overlay.py`, run as root in the `xnuvm-qemu` container): `tools/hosted/gui-user.py` and the- inline Python of `mk-macvm-disk.sh` against a staging tree seeded with the archive's `admin`/`staff` group- plists, plus the CI bundle in `Library/GPUBundles`; files only (existing directories keep their modes), written- at 4 GiB into `payload.img`, untarred over the new volume, then `chown -R 501:20 Users/xnu`. The System volume's- `User Template` is an empty directory from there, so the home has only what gui-user.py writes.- - `dgx:~/xnuvm/apsb.py IMAGE NEW_UUID --apply`: sets the new volume's role (0x40) and volume group in every APSB- copy (Fletcher-64 recomputed, 11 blocks) and clears both on the old Data volume (1 block), which stays in the- container, unused. New Data volume UUID `8588A37C-4CC5-4993-B3EA-D55D38325A47`.-- **WindowServer** aborts in `__WSSystemCanCompositeWithMetal_block_invoke` every 30 s: the plugin loads but- `dlopen(libvulkan_lvp.dylib)`: `symbol not found in flat namespace '_spvBinaryToText'`. The CI runner's Homebrew- glslang brought SPIRV-Tools; Mesa found it, linked Homebrew's dylib into the arm64 slice and left the arm64e slice- with undefined `spv*` symbols (the runner's render test passed because the dylib was there). Fixed in the workflow- (`brew unlink spirv-tools` + a self-containment check on the bundle); run 45165136403 in progress when written.-- **Desktop reached (2026-11-23):** CI run 45165136403 passed; its bundle (no `spv*` undefined symbols, no Homebrew- dependency) installed from the hosted console (`curl http://192.168.77.1:8099/b.tgz | tar` into `/Library/GPUBundles`;- the hosted system reaches the Linux guest and the internet, `https://www.apple.com` 200). After a clean restart:- automatic login, WindowServer on lavapipe, Finder menu bar, wallpaper, widgets, a notification, 1280x800- (screenshot: `../xnulinux-dgx-desktop.png` on the Mac, outside the repo). The Dock was not on screen ~2 min after- boot; not checked further. `dgx:~/xnuvm/overlay.py` still packs the first (broken) bundle unless rerun: the fixed- one is `dgx:~/xnuvm/XnuCpuMetal.bundle.tar.gz` now.-- **Intermittent boot failure (1 of 3 boots on the finished disk):** `apfs_boot_util` took the root device for- `/dev/disk3s5` (the old encrypted Data volume, left in the container with no role) instead of `disk3s1`:- "root device /dev/disk3s5 is not in a volume group", "No DATA volume present", Data not mounted, `tzinit` exits 2,- launchd panics. The next boot, nothing changed on disk, was fine. Removing the old volume (or giving the new one- the group's UUID) may avoid it; not tried. That boot also followed an unclean stop of the run before it.-- **VNC:** macOS Screen Sharing in the hosted system works. From the hosted console: `kickstart -activate -configure- -access -on -privs -all -restart -agent`, `launchctl enable/bootstrap system/com.apple.screensharing`, legacy VNC- password (`kickstart -configure -clientopts -setvnclegacy -vnclegacy yes -setvncpw -vncpw <password>`: without it only- Apple's auth types 30/33/35/36 are offered and third-party clients fail with "key length too large"), and two rows in- `/Library/Application Support/com.apple.TCC/TCC.db` (`kTCCServiceScreenCapture`, `kTCCServicePostEvent` for- `com.apple.screensharing.agent`, auth_value 2, auth_reason 4; without them: "Screen Sharing is not permitted").- Path: Mac `ssh -L 5901:127.0.0.1:5901 dgx` → dgx `ssh -L 127.0.0.1:5901:192.168.77.37:5900` into the Linux guest- (a background ssh on dgx; hosted en0 got 192.168.77.37 on every boot so far). The user confirmed the UI shows.-- **Console output channel:** dmesg is unusable while a process floods it; `guest:~/hcmd.sh [TIMEOUT] < commands`- serves the commands over `http://192.168.77.1:8099/cmd.sh`, the hosted console shell runs them and pipes the- output to `nc 192.168.77.1 8100`. A `ps ax` on the console can hang for a long time; avoid it in scripts.-- **No Dock, blank icons (open, 2026-11-23):** Dock runs; the user's `iconservicesagent` (gui/501) dies ~3 s after- each start (SIGSEGV, 19+ runs), so Dock and System Settings get no icons (`NSCocoaErrorDomain 4097`).- - Stack: IconServices → IconRendering → RenderBox (`RB::TextureCache::prepare_from_iosurface`, `render_image`) →- XnuCpuMetal → lavapipe; the crash is in a JIT-compiled fragment shader called from `lp_rast_triangle_32_5`:- `ldr x8,[x8,x0,lsl #3]; add x0,x22,#0xc0; ldr x8,[x8]` ← faults; `blr x8` follows. The table entry read was 0x22- in one crash and 0 in another: llvmpipe's per-texture sample-function row for the sampler index is not there.- - Deterministic, not a race: same instruction with `LP_NUM_THREADS=0` (then on the queue thread, via- `llvmpipe_flush`). Not the sandbox (no denials; neither binary has JIT entitlements). The arm64e JIT patch is- applied in the CI build. CPUS=1 was not a usable test (no login session after 5.5 min).- - Separate, intermittent: one agent instance looped on "Data/Stack execution not permitted ... protections were- read-write" at one address (1.1 M kernel log lines in 18 s) instead of dying. Not explained.- - Guess, unverified: RenderBox's shaders use constexpr samplers; metal2vulkan lowers those to Vulkan immutable- samplers, and the texture or sampler never gets its row in llvmpipe's matrix on this path (e.g. a texture view- not registered as sampled). WindowServer composites fine with the same bundle. The README's screenshots show a- Dock with icons, so the author's build or system differs somewhere; unknown where.- - Next: a lavapipe debug build (asserts, symbols) in CI and/or logging in the plugin around- `xcmDev_newTextureIOSurface`; ask upstream whether this is known.-- **Workaround for the icon agent (2026-11-23, works):** `launchctl disable gui/501/com.apple.iconservices.iconservicesagent`- (+ `bootout`; persists) from a root shell in the hosted system. Clients then fail at once instead of queueing behind- a service that crashes and respawns: the Dock comes up (about half of its icons drawn, the rest blank), Terminal- opens a window with a shell. Before it, Terminal's main thread sat in `+[ISIconManager sharedInstance]` →- `xpc_connection_send_message_with_reply_sync` while loading its nib. Undo: `launchctl enable ...`. The crash itself- is still open (above).-- **SSH into the hosted system:** enabled (`launchctl enable system/com.openssh.sshd` + bootstrap `ssh.plist`), the- Linux guest's key (`~/hkey`, same as `dgx:~/xnuvm/vmkey`) in root's and xnu's `authorized_keys`:- `ssh -i ~/hkey [email protected]` from the guest. Use this, not the console, for anything that can block.- TCC rows added for `com.apple.Terminal` (full disk access, accessibility, developer tool).-- Also seen, not looked into: `cryptexd` crashes every 10 s; `com.apple.DriverKit-IOUserDockChannelSerial` crashed;- `AppleVPKeyStore ... unexpected session uid: -1` for bluetoothd/ReportCrash.--### Still missing for a boot (as of the first KVM session; superseded by the section above)-- `out/kc/kc27.bin` (macOS 27.2 kernelcache for the collection's Apple kexts): dgx has- the macOS 27.2 (26B123) restore IPSW; how DroidVM turns it into kc27.bin: to read in the dvm tree.-- The system disk (`mk-macvm-disk.sh`): written for a Mac with tart, passwordless sudo and the built Metal bundle.- The Mac at hand had none of that prepared and little free disk. dgx has installed macOS 27.2 disks from the user's own macOS-on-KVM stack- (its disks and its QEMU), but Linux has no- read-write APFS. Options: (a) serve the image from dgx to the Mac (SMB from a container) and run the script's steps- there with sudo; (b) do the steps inside a macOS guest on dgx with the disk attached as a second drive.-- `XnuCpuMetal.bundle` (WindowServer needs a Metal device): Mac build with LLVM arm64e + Mesa: too large for the Mac at hand.- Without it the target is launchd + the console root shell, not the desktop.--### Open questions-- (resolved: both stopped) Which service to stop to free 16+ GiB for the guest (user's call).-- Does KVM on GB10 expose PAC (`paca`/`pacg`) to guests? To check with the first guest boot.-- Does the user accept a reboot of dgx with Secure Boot off and `mem=`/`nokaslr`, with the running services stopped?-- Alternative with no risk to the host: run it inside a KVM guest on dgx (arm64 Ubuntu VM, 16 GB, as on the Mac). KVM on- GB10 exposes PAC to guests? Not checked. Needs ~16 GB free RAM, which the host does not have while both services run.-- `SHADOW_CALL_STACK=y` (x18 is Linux's shadow stack pointer) vs XNU code running on Linux kthreads: not checked whether- the Ubuntu generic kernels the project was tested on also have it.--## 2026-11-23 (late): moving to the dgx bare metal (user decision)-- User turned Secure Boot off in the firmware (Security → Secure Boot); after the reboot: `SecureBoot disabled`,- lockdown `[none]`. The reboot ended the KVM guest and the hosted system; the two GPU services stay stopped.-- Prepared without root, in `dgx:~/xnuhost/`: `poc/` (the guest's `~/w/poc`, with `fki.ko`/`xnu.ko` built for- `7.0.0-1025-nvidia`), `fw/{kc.bin,kernel.macho,trustcache-mac.bin}` (the guest's `/lib/firmware/xnu`), `mac.conf`.- The finished disk is `dgx:~/xnuvm/mac.img`. The guest was powered off and its container removed- (`~/xnuvm/run-vm.sh` starts it again; it attaches the same `mac.img`: never run both on it).-- Plan (needs sudo, not yet given): read `/proc/iomem`, pick `mem=`/`carve_base` for an 8156 MiB carve-out, add- `kvm-arm.mode=nvhe mem=... nokaslr log_buf_len=128M` in `/etc/default/grub.d/99-xnulinux.cfg`, `update-grub`,- reboot, check dmesg says nVHE, install firmware to `/lib/firmware/xnu`, `insmod fki.ko carve_base=... carve_mb=8156`,- then `xnulinux-boot.sh` with `GPU=off`, few CPUs.-- Unverified risks: XNU machine layer at EL2 if nVHE cannot be forced on GB10; `SHADOW_CALL_STACK=y` (x18) in the- NVIDIA kernel; a fault in kernel mode takes dgx down.-- **Bare metal works (2026-11-23 late):** sudo given by the user (temporary `/etc/sudoers.d/99-xnulinux-tmp`, to remove).- - `/etc/default/grub.d/99-xnulinux.cfg`: `kvm-arm.mode=nvhe mem=112G nokaslr log_buf_len=128M`. After reboot:- "Hyp nVHE mode initialized successfully", System RAM ends at `0x1c97c1f000`, kernel image at `0x206ce00000`- (nokaslr puts it near the top), carve-out `carve_base=0x1E00000000 carve_mb=8156` accepted by fki.- - Run 1 (`CPUS=2`, XNU on Linux CPUs 0,1): reached the console shell and login, then "XNU CPU 0 made no host call- for 2 s (interrupts masked)", XNU panic `wait_while_equals32 ... timeout @locks.c:959` at 341 s. Cause: the NVMe- has 15 I/O queues for 20 CPUs; `nvme0q8` serves CPUs 0-1 with its (managed, not movable) interrupt on CPU 0, so- CPU 1's disk completions arrive on CPU 0: the deadlock `xnulinux-boot.sh`'s comment describes. Also in that run:- xnu.ko's monitor thread, dumping the silent CPU, read an unmapped XNU address and Linux oopsed in `show_pte`- (the carve-out is not in Linux's linear map); xnu.ko could not be unloaded afterwards (reboot).- - Fix (uncommitted): `fki.ko cpu_list=` (foreign CPU n = Linux CPU cpu_list[n]; `fki_bind_cpu`, `fki_thread_start`,- `fki_kick_cpu`, `fki_cpu_mpidr`, `fki_num_cpus`), and `xnulinux-boot.sh` takes its interrupt mask from it.- dgx: `cpu_list=5,6,7,8,9` (X925 cores, each with its own NVMe queue; the fifth is the monitor's), `CPUS=4`.- - Run 2: desktop (Terminal restored from the earlier session, Dock, Finder), no panic or oops in the first- ~6 minutes. Boot is slower than in the KVM guest (Data volume mounted 100 s after the kernel banner; ~12 s in- the guest; not investigated). "XNU CPU 1 made no host call for 2 s ... last call 810 (inside it)" five times- during boot. The hosted `uptime` showed load averages in the hundreds (not investigated).- - Network: NetworkManager on dgx took `xnu0` and removed 192.168.77.1; fixed with `nmcli dev set xnu0 managed no`- and `/etc/NetworkManager/conf.d/99-xnulinux.conf` (unmanaged-devices=interface-name:xnu0), address re-added,- `ipconfig set en0 DHCP` on the hosted console. Then lease 192.168.77.37, ssh from dgx, internet from the hosted- system, Screen Sharing listening.- - Not persistent: fki.ko is loaded by hand after each dgx boot- (`sudo insmod ~/xnuhost/poc/fki-ko/fki.ko carve_base=0x1E00000000 carve_mb=8156 cpu_list=5,6,7,8,9`), then- `cd ~/xnuhost/poc && bash scripts/xnulinux-boot.sh` (config `/etc/xnulinux.conf`, `/var/tmp/mac.conf`).--## GPU on the dgx bare metal: feasibility probe (2026-11-23 late; nothing connected yet)-- State: `GPU=off`, WindowServer has only `libvulkan_lvp.dylib`; the CI bundle carries no Venus driver.-- `gpu/xnu-drm/xnudrmd.c` forwards virtio-gpu DRM ioctls (`VIRTGPU_CONTEXT_INIT/EXECBUFFER/GET_CAPS/GETPARAM/MAP/- RESOURCE_CREATE_BLOB/RESOURCE_INFO/WAIT`, `GEM_CLOSE`) to a virtio-gpu render node. dgx's `/dev/dri/renderD128` is- the NVIDIA proprietary driver (580.178.04): no virtio-gpu, so the bridge as written has nothing to talk to.-- Way through: xnudrmd as the virtio-gpu backend itself (libvirglrenderer with Venus on NVIDIA's Vulkan).-- Probed on Linux only, in `dgx:~/xnuhost/gputest/` (vtest socket, no macOS involved):- - NVIDIA GB10 Vulkan 1.4.312 lists `VK_EXT_external_memory_dma_buf`, `VK_KHR_external_memory_fd`,- `VK_EXT_image_drm_format_modifier`, `VK_EXT_external_memory_host`, fence/semaphore fd (grep over all devices,- llvmpipe included: per-device not separated).- - Ubuntu's virglrenderer 1.0.0: device enumerates, `vkCreateDevice` -3. virglrenderer 1.2.0 built from source- (`-Dvenus=true -Drender-server-worker=thread`) + the project's Mesa 26.3.1 Venus (`gpu/venus/patches`):- `vulkaninfo`: "Virtio-GPU Venus (NVIDIA GB10)", Mesa 26.3.1. (Ubuntu's Mesa 25.2 Venus against 1.2.0: -9.- `VKR_DEBUG=validate` without the validation layer installed also gives -9.)- - `gpu/venus/test/compute.c` hangs in `vkMapMemory` (`vtest_bo_create_from_device_memory` waiting on the socket);- server: `virgl_renderer_resource_export_blob ... failed (-22)`. On NVIDIA the host-visible device memory exports- as an OPAQUE fd, which vtest refuses (it takes dma-buf or shm only). virglrenderer hands out- `virgl_resource_vulkan_info` (device/driver UUID, size, memory type) for exactly this case: the embedder imports- the opaque fd into a Vulkan device of its own and maps it (what crosvm does).- - `fki_hostcall.c`'s XLATE already translates `VM_IO|VM_PFNMAP` mappings (`follow_pfnmap_start`), so a driver- mapping in the daemon can be handed to the hosted kernel.-- Work left for a real connection: (1) a virglrenderer backend in xnudrmd (contexts, execbuffer, caps, fences,- blobs; opaque-fd blobs imported and mapped through Vulkan); (2) the Darwin Venus dylib (`gpu/venus/build-darwin.sh`)- built in CI and packed into the bundle; (3) WindowServer and apps on it. Untested unknowns: whether an imported- NVIDIA mapping's pages can be mapped by the hosted pmap, performance, the 16 KiB blob alignment patch on a 4 KiB host.-- Installed on dgx for this: `virgl-server` and build dependencies via apt.diff --git a/tools/dgx-spark/README.md b/tools/dgx-spark/README.mdindex 37f0a43..21366d6 100644--- a/tools/dgx-spark/README.md+++ b/tools/dgx-spark/README.md@@ -1,26 +1,36 @@-# xnulinux on an NVIDIA DGX Spark (GB10), without a Mac+# xnulinux on an NVIDIA DGX Spark (GB10)-The scripts as they ran, except that the vmapple stack's locations now come from the environment (not rerun since):-work paths (`~/xnuvm`, `~/xnuhost`) and volume UUIDs are that machine's. Details: `NOTES.md`.+What was set on that machine (Ubuntu 24.04.5, Linux `7.0.0-1025-nvidia`), bare metal and in a KVM guest. The addresses+and CPU numbers are that machine's.-- `guest/`: an arm64 Ubuntu guest under KVM (QEMU from a container); `hcmd.sh` runs commands on the hosted console.-- `disk/`: the system disk, in place of `scripts/mk-macvm-disk.sh`, in this order:- `mac-restore.sh`, `trustcache-from-ipsw.py`, `hboot.sh` + `1-cryptex.cmds`, `tboot.sh` + `2-tar-data.cmds`,- `overlay.py`, `hboot.sh` + `3-new-data.cmds`, `apsb.py IMAGE NEW_UUID --apply`.- A vmapple restore encrypts the Data volume with that VM's keys, so a new unencrypted one is made.-- `qemu/`: `QEMU_VMAPPLE_LP_SIP0=<flags>` turns SIP off in a vmapple guest (a patch on the vmapple QEMU in use).+## Bare metal-Bare metal: Secure Boot off; `kvm-arm.mode=nvhe mem=112G nokaslr`;-`insmod fki.ko carve_base=0x1E00000000 carve_mb=8156 cpu_list=5,6,7,8,9`; NetworkManager off `xnu0`;-`/etc/xnulinux.conf`: `GPU=off CPUS=4`.+- Secure Boot off: with it the kernel is locked down, which refuses unsigned modules and the kprobes fki needs.+- Kernel command line: `kvm-arm.mode=nvhe mem=112G nokaslr log_buf_len=128M`. `nvhe` keeps Linux at EL1; `mem=` leaves+ the RAM above it for the carve-out; with `nokaslr` the kernel image stays out of it.+- `insmod fki.ko carve_base=0x1E00000000 carve_mb=8156 cpu_list=5,6,7,8,9`. The NVMe has 15 I/O queues for 20 CPUs, so+ some CPUs share a queue's interrupt, and two XNU CPUs on such a pair deadlock: `cpu_list` gives XNU CPUs that each+ have a queue of their own (here the X925 cores; the one after the last XNU CPU is the monitor thread'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.-- `gpu/`: `build-virglrenderer.sh` installs virglrenderer 1.2.0 with Venus, which `gpu/xnu-drm/xnudrmd` then serves the- hosted system's Vulkan from (NVIDIA's render node is not virtio-gpu). Written and tested off the machine only- (`make -C gpu/xnu-drm test-virgl`); not yet run on NVIDIA's driver.+## GPU-With `GPU=auto` and the Venus driver in `/Library/GPUBundles/XnuCpuMetal.bundle` Metal and WindowServer run on the GB10-(`Virtio-GPU Venus (NVIDIA GB10)`), the Dock with its icons. The counter here runs at 1 GHz: xnu.ko has XNU scale it to-Apple's 24 MHz (user space assumes it).+The render node is NVIDIA's driver, not virtio-gpu, so `xnudrmd` serves the hosted system's Venus driver from+virglrenderer on the machine's Vulkan driver (`gpu/xnu-drm/xnudrmd_virgl.c`). Ubuntu 24.04's virglrenderer 1.0.0 fails+`vkCreateDevice` there; `gpu/build-virglrenderer.sh` builds and installs 1.2.0 with Venus. With `GPU=auto` and the+Venus driver in `/Library/GPUBundles/XnuCpuMetal.bundle`, Metal and WindowServer run on `Virtio-GPU Venus (NVIDIA GB10)`.-Open: without a GPU `iconservicesagent` crashes in lavapipe; stopping a run takes minutes; one boot in three takes the-leftover encrypted Data volume for the root device.+## In a KVM guest++`guest/`: an arm64 Ubuntu guest under KVM, QEMU run from a container (`Dockerfile`, `run-vm.sh`, `vm.sh`); KVM on the+GB10 gives the guest pointer authentication. `hcmd.sh` runs commands in the hosted system's console shell and returns+their output over the `xnu0` link, for when the kernel log is flooded.++## Open++- Without the GPU bridge `iconservicesagent` crashes in lavapipe (a JIT-compiled fragment shader reads a missing+ sampler entry); the Dock then has no icons.+- A system disk restored by a virtual Mac has its Data volume encrypted with that VM's keys: the hosted system cannot+ open it, and the volume has to be made again unencrypted.diff --git a/tools/dgx-spark/disk/1-cryptex.cmds b/tools/dgx-spark/disk/1-cryptex.cmdsdeleted file mode 100644index 6faab04..0000000--- a/tools/dgx-spark/disk/1-cryptex.cmds+++ /dev/null@@ -1,7 +0,0 @@-# sershell.py helper/serial.sock 1-cryptex.cmds --wait-boot (helper guest: hboot.sh, SIP off, the target disk attached)-B=$(mount | awk '$3=="/"{print $1}' | sed 's|/dev/\(disk[0-9]*\).*|\1|'); A=/System/Library/Filesystems/apfs.fs/Contents/Resources/apfs.util; for d in /dev/disk[0-9]s[0-9]; do case $d in /dev/${B}s*) continue;; esac; n=$($A -p $d 2>/dev/null | head -1); case "$n" in "Macintosh HD") TSYS=$d;; Preboot) TPRE=$d;; esac; done; echo "sys=$TSYS pre=$TPRE"; P=/System/Volumes/VM; Y=/System/Volumes/Update-mount -t apfs -o rw,nobrowse $TPRE $P >/dev/null 2>&1; mount -t apfs -o rw,nobrowse $TSYS $Y >/dev/null 2>&1; mount | grep -c -E "Volumes/(VM|Update)"-@2400 rm -rf $P/Cryptexes/OS $P/Cryptexes/App; mkdir -p $P/Cryptexes/OS $P/Cryptexes/App && ditto /System/Cryptexes/OS/ $P/Cryptexes/OS >/dev/null 2>&1; echo ditto-os=$?; ditto /System/Cryptexes/App/ $P/Cryptexes/App >/dev/null 2>&1; echo ditto-app=$?-@1200 C=/System/Cryptexes/OS; for d in usr/lib usr/libexec usr/bin usr/sbin usr/share System/iOSSupport; do [ -d $C/$d ] && mkdir -p $Y/$d && cp -Rpn $C/$d/. $Y/$d/ 2>/dev/null; done; echo merged-usr-@1200 C=/System/Cryptexes/OS; for e in $C/System/Library/*; do n=$(basename "$e"); [ "$n" = dyld ] && continue; if [ -d "$e" ]; then mkdir -p "$Y/System/Library/$n"; cp -Rpn "$e/." "$Y/System/Library/$n/" 2>/dev/null; else cp -pn "$e" "$Y/System/Library/" 2>/dev/null; fi; done; ls -la $Y/usr/lib/libLaunchServicesSupport.dylib-sync; umount $Y; umount $P; sync; mount | grep -c -E "Volumes/(VM|Update)"; echo CRYPTEX_DONEdiff --git a/tools/dgx-spark/disk/2-tar-data.cmds b/tools/dgx-spark/disk/2-tar-data.cmdsdeleted file mode 100644index cbdbe6c..0000000--- a/tools/dgx-spark/disk/2-tar-data.cmds+++ /dev/null@@ -1,5 +0,0 @@-# sershell.py xnu272/serial.sock 2-tar-data.cmds --wait-boot (the restored install itself: tboot.sh, SIP off, a raw payload disk)-@240 R=/System/Library/Filesystems/apfs.fs/Contents/Resources; $R/apfs_boot_util 1 >/dev/null 2>&1; $R/apfs_boot_util 2 >/dev/null 2>&1; test -d /private/var/db/dslocal/nodes/Default && echo DATA_OK-RAW=; for d in /dev/disk[0-9]; do [ -e ${d}s1 ] || RAW=/dev/r${d#/dev/}; done; echo raw=$RAW-@3000 cd /System/Volumes/Data && tar -cf - .TemporaryItems Applications Library System Users Volumes cores home mnt opt pkg private sw usr 2>/var/root/tar.err | dd of=$RAW ibs=65536 obs=1048576 conv=osync 2>&1 | tail -1; cd /; wc -l /var/root/tar.err; head -8 /var/root/tar.err-sync; echo TAR_DONEdiff --git a/tools/dgx-spark/disk/3-new-data.cmds b/tools/dgx-spark/disk/3-new-data.cmdsdeleted file mode 100644index 4a00384..0000000--- a/tools/dgx-spark/disk/3-new-data.cmds+++ /dev/null@@ -1,9 +0,0 @@-# sershell.py helper/serial.sock 3-new-data.cmds (helper guest again; payload.img: the Data archive at 0, overlay.tar at 4 GiB)-B=$(mount | awk '$3=="/"{print $1}' | sed 's|/dev/\(disk[0-9]*\).*|\1|'); A=/System/Library/Filesystems/apfs.fs/Contents/Resources/apfs.util; for d in /dev/disk[0-9]s[0-9]; do case $d in /dev/${B}s*) continue;; esac; n=$($A -p $d 2>/dev/null | head -1); case "$n" in "Macintosh HD") TSYS=$d;; Preboot) TPRE=$d;; esac; done; CONT=${TSYS%s[0-9]}; echo "sys=$TSYS cont=$CONT"-newfs_apfs -A -v Data $CONT 2>&1 | tail -3; sleep 2; NEW=; for d in ${CONT}s[0-9] ${CONT}s[0-9][0-9]; do [ -e $d ] || continue; n=$($A -p $d 2>/dev/null | head -1); u=$($A -k $d 2>/dev/null | tail -1); echo "$d $n $u"; [ "$n" = Data ] && [ "$u" != 478C06EB-C8E8-4234-B386-23433F2A8433 ] && NEW=$d; done; echo new=$NEW-V=/Volumes; Y=/System/Volumes/Update; mount -t apfs -o rw,nobrowse $NEW $V 2>&1 | tail -1; mount -t apfs -o rdonly,nobrowse $TSYS $Y 2>&1 | tail -1; mount | grep -E " on ($V|$Y) "-RAW=; for d in /dev/disk[0-9]; do [ -e ${d}s1 ] || RAW=/dev/r${d#/dev/}; done; echo raw=$RAW-@2400 dd if=$RAW bs=1048576 2>/dev/null | tar -xpf - -C $V 2>/dev/null; echo untar=$?; ls $V; df -k $V | tail -1-rm -rf $V/private/var/keybags/* 2>/dev/null; mkdir -p $V/Users/xnu; T="$Y/System/Library/User Template"; for s in Non_localized English.lproj; do [ -d "$T/$s" ] && cp -a "$T/$s/." $V/Users/xnu/; done-@1200 dd if=$RAW bs=1048576 skip=4096 2>/dev/null | tar -xpf - -C $V 2>/dev/null; echo overlay=$?; chown -R 501:20 $V/Users/xnu; chmod 755 $V/Users/xnu-sync; umount $Y; umount $V; sync; echo DATA_DONEdiff --git a/tools/dgx-spark/disk/apsb.py b/tools/dgx-spark/disk/apsb.pydeleted file mode 100644index dbe86d8..0000000--- a/tools/dgx-spark/disk/apsb.py+++ /dev/null@@ -1,35 +0,0 @@-#!/usr/bin/env python3-# SPDX-License-Identifier: GPL-2.0-only-"""apsb.py IMAGE [--apply]: the hosted disk's volume group after the Data volume was made again (newfs_apfs -A cannot set these):-the new Data volume gets the Data role and the group of the System volume; the installed (encrypted) one loses both."""-import mmap, struct, sys, uuid-GROUP = uuid.UUID('478C06EB-C8E8-4234-B386-23433F2A8433')-OLD, NEW = GROUP, uuid.UUID(sys.argv[2])-apply = '--apply' in sys.argv-def fletcher64(data):- lo = hi = 0- for (w,) in struct.iter_unpack('<I', data):- lo = (lo + w) % 0xFFFFFFFF; hi = (hi + lo) % 0xFFFFFFFF- c0 = 0xFFFFFFFF - ((lo + hi) % 0xFFFFFFFF); c1 = 0xFFFFFFFF - ((lo + c0) % 0xFFFFFFFF)- return (c1 << 32) | c0-f = open(sys.argv[1], 'r+b' if apply else 'rb'); m = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_WRITE if apply else mmap.ACCESS_READ)-pos, end, n = 524308480, 63350788096, 0-while True:- pos = m.find(b'APSB', pos, end)- if pos < 0: break- b = pos - 32; pos += 4- if b % 4096: continue- blk = bytearray(m[b:b + 4096]); vu = uuid.UUID(bytes=bytes(blk[240:256]))- if vu not in (OLD, NEW): continue- ok = struct.unpack_from('<Q', blk, 0)[0] == fletcher64(bytes(blk[8:]))- xid = struct.unpack_from('<Q', blk, 16)[0]- feat, ro, inc = struct.unpack_from('<QQQ', blk, 40); flags = struct.unpack_from('<Q', blk, 264)[0]- role = struct.unpack_from('<H', blk, 964)[0]; grp = uuid.UUID(bytes=bytes(blk[1008:1024]))- print(f'{"NEW" if vu == NEW else "OLD"} block {b // 4096:#x} xid {xid} cksum {"ok" if ok else "BAD"} features {feat:#x} ro {ro:#x} incompat {inc:#x} flags {flags:#x} role {role:#x} group {grp}')- if not ok or not apply: continue- if vu == NEW:- struct.pack_into('<H', blk, 964, 0x40); blk[1008:1024] = GROUP.bytes- else:- struct.pack_into('<H', blk, 964, 0); blk[1008:1024] = bytes(16)- struct.pack_into('<Q', blk, 0, fletcher64(bytes(blk[8:]))); m[b:b + 4096] = bytes(blk); n += 1-if apply: m.flush(); print(n, 'superblocks rewritten')diff --git a/tools/dgx-spark/disk/hboot.sh b/tools/dgx-spark/disk/hboot.shdeleted file mode 100755index ca3b253..0000000--- a/tools/dgx-spark/disk/hboot.sh+++ /dev/null@@ -1,13 +0,0 @@-#!/usr/bin/env bash-# SPDX-License-Identifier: GPL-2.0-only-# boot the helper macOS VM single-user with the target disk (and optionally a payload disk) attached; serial at helper/serial.sock-# The vmapple stack's pieces come from the environment: VMAPPLE_DEPS (the prefix its libraries were installed to),-# VMAPPLE_QEMU, VMAPPLE_ROM; vmapple-cli is on PATH.-: "${VMAPPLE_DEPS:?} ${VMAPPLE_QEMU:?} ${VMAPPLE_ROM:?}"-export LD_LIBRARY_PATH=$VMAPPLE_DEPS/lib PATH=$VMAPPLE_DEPS/bin:$PATH-export VMAPPLE_ROM VMAPPLE_QEMU=${SIP_QEMU:-$HOME/xnuvm/qemu-sip/build/qemu-system-aarch64} QEMU_VMAPPLE_LP_SIP0=${LP_SIP0:-0x86f}-M=$HOME/xnuvm/mac-X="-drive if=none,format=raw,file.filename=$HOME/xnuvm/mac.img,file.locking=off,id=x1 -device virtio-blk-pci,drive=x1"-[ -f $M/payload.img ] && X="$X -drive if=none,format=raw,file.filename=$M/payload.img,file.locking=off,id=x2 -device virtio-blk-pci,drive=x2"-export VMAPPLE_QEMU_ARGS="$X"-cd $M; exec vmapple-cli boot helper --boot-args="-s -v serial=11 debug=0x14c" --cpus 4 --memory 8diff --git a/tools/dgx-spark/disk/mac-restore.sh b/tools/dgx-spark/disk/mac-restore.shdeleted file mode 100755index 8261825..0000000--- a/tools/dgx-spark/disk/mac-restore.sh+++ /dev/null@@ -1,11 +0,0 @@-#!/usr/bin/env bash-# SPDX-License-Identifier: GPL-2.0-only-# a new macOS install for xnulinux with vmapple-cli: mac-restore.sh RESTORE.ipsw-# The vmapple stack's pieces come from the environment: VMAPPLE_DEPS (the prefix its libraries were installed to),-# VMAPPLE_QEMU, VMAPPLE_ROM; vmapple-cli is on PATH.-: "${VMAPPLE_DEPS:?} ${VMAPPLE_QEMU:?} ${VMAPPLE_ROM:?}"-export LD_LIBRARY_PATH=$VMAPPLE_DEPS/lib PATH=$VMAPPLE_DEPS/bin:$PATH-export VMAPPLE_QEMU VMAPPLE_ROM-mkdir -p ~/xnuvm/mac; cd ~/xnuvm/mac-[ -f xnu272/vm.json ] || vmapple-cli create xnu272-exec vmapple-cli restore xnu272 "${1:?the restore IPSW}"diff --git a/tools/dgx-spark/disk/overlay.py b/tools/dgx-spark/disk/overlay.pydeleted file mode 100644index 99eb7bd..0000000--- a/tools/dgx-spark/disk/overlay.py+++ /dev/null@@ -1,65 +0,0 @@-# SPDX-License-Identifier: GPL-2.0-only-import os, plistlib, subprocess, tarfile, sys-P, ST = '/vm/mac/payload.img', '/stage'-D, T = ST + '/D', ST + '/T/System/Library/User Template'-want = {'private/var/db/dslocal/nodes/Default/groups/admin.plist', 'private/var/db/dslocal/nodes/Default/groups/staff.plist',- 'Library/Preferences/com.apple.loginwindow.plist', 'private/var/db/com.apple.xpc.launchd/disabled.plist',- 'Library/Preferences/com.apple.keyboardtype.plist', 'private/etc/sysctl.conf'}-t = tarfile.open(P, 'r:')-have = []-for m in t:- if m.name in want:- t.extract(m, D); have.append(m.name)- if m.name.startswith(('private/var/keybags', 'Users/')) or m.name in ('private/etc', 'private/var/db/.AppleSetupDone'):- print('in the archive:', m.name, m.type, m.linkname)-print('existing files taken:', have)-for d in ('private/var/db/dslocal/nodes/Default/users', 'private/var/db/dslocal/nodes/Default/groups', 'Library/Preferences', 'Users',- 'Library/GPUBundles', 'Library/LaunchDaemons', 'private/var/db/com.apple.xpc.launchd', 'private/etc'):- os.makedirs(D + '/' + d, exist_ok=True)-os.makedirs(T, exist_ok=True); os.makedirs(ST + '/T/System/Library/CoreServices', exist_ok=True)-plistlib.dump({'ProductVersion': '27.2', 'ProductBuildVersion': '26B123'}, open(ST + '/T/System/Library/CoreServices/SystemVersion.plist', 'wb'))-subprocess.run([sys.executable, '/vm/gui-user.py', D, T], check=True)-subprocess.run(['tar', '-C', D + '/Library/GPUBundles', '-xzf', '/vm/XnuCpuMetal.bundle.tar.gz'], check=True)-subprocess.run(['chown', '-R', '0:0', D + '/Library/GPUBundles'], check=True)-os.environ['D'] = D; os.environ['DISABLE'] = 'com.apple.watchdogd com.apple.iomfb_bics_daemon com.apple.audiomxd com.apple.audio.coreaudiod com.apple.PerfPowerServices com.apple.PerfPowerServicesExtended com.apple.oahd com.apple.oahd-root-helper'-import os, plistlib-D = os.environ["D"]-shell = {"Label": "xnulinux.shell", "ProgramArguments": ["/bin/bash", "-i"], "RunAtLoad": True,- "StandardInPath": "/dev/console", "StandardOutPath": "/dev/console", "StandardErrorPath": "/dev/console",- "EnvironmentVariables": {"HOME": "/var/root", "LOGNAME": "root", "USER": "root", "SHELL": "/bin/bash", "TERM": "dumb",- "PATH": "/bin:/usr/bin:/sbin:/usr/sbin", "PS1": "xnulinux# "}}-p = D + "/Library/LaunchDaemons/xnulinux.shell.plist"-plistlib.dump(shell, open(p, "wb")); os.chown(p, 0, 0); os.chmod(p, 0o644)-# No display or system sleep: a hosted display has no one to wake it, and its sleep locks the screen after ten idle-# minutes (loginwindow's lock-screen request, reason 5), taking the session to the lock screen.-awake = {"Label": "xnulinux.awake", "RunAtLoad": True,- "ProgramArguments": ["/usr/bin/pmset", "-a", "displaysleep", "0", "sleep", "0", "disksleep", "0"]}-p = D + "/Library/LaunchDaemons/xnulinux.awake.plist"-plistlib.dump(awake, open(p, "wb")); os.chown(p, 0, 0); os.chmod(p, 0o644)-# No screen saver either: after its idle time (no keyboard or pointer input: a hosted system with no one at it) it plays-# the aerial wallpaper's video, which without the GPU bridge decodes in software and takes both of a two-CPU system's-# CPUs, then locks the session. The setting is the user's, per host (ByHost, by IOPlatformUUID), so it is made at login.-nosaver = {"Label": "xnulinux.nosaver", "RunAtLoad": True, "LimitLoadToSessionType": "Aqua",- "ProgramArguments": ["/usr/bin/defaults", "-currentHost", "write", "com.apple.screensaver", "idleTime", "-int", "0"]}-os.makedirs(D + "/Library/LaunchAgents", exist_ok=True)-p = D + "/Library/LaunchAgents/xnulinux.nosaver.plist"-plistlib.dump(nosaver, open(p, "wb")); os.chown(p, 0, 0); os.chmod(p, 0o644)-p = D + "/private/var/db/com.apple.xpc.launchd/disabled.plist"-disabled = plistlib.load(open(p, "rb")) if os.path.exists(p) else {}-disabled.update({label: True for label in os.environ["DISABLE"].split()})-plistlib.dump(disabled, open(p, "wb")); os.chown(p, 0, 0); os.chmod(p, 0o644)-# The hosted keyboard's type (ANSI), as Keyboard Setup Assistant records it for a keyboard it cannot identify by itself-# (xnulinux Keyboard, vendor 0x1209, product 0x5801: "<product>-<vendor>-0"); without it the assistant opens at each login.-p = D + "/Library/Preferences/com.apple.keyboardtype.plist"-plistlib.dump({"keyboardtype": {"22529-4617-0": 40}}, open(p, "wb")); os.chown(p, 0, 0); os.chmod(p, 0o644)-# Per-process memory limits (jetsam high-water marks) off: the CPU Metal device does a GPU's work in the process that asks-# for it (WebKit's GPU process, WindowServer), over the limits set for a real GPU's clients. launchd applies sysctl.conf.-p = D + "/private/etc/sysctl.conf"-open(p, "w").write("kern.memorystatus_highwater_enabled=0\n"); os.chown(p, 0, 0); os.chmod(p, 0o644)-print("console shell job, no screen saver, %d daemons disabled, keyboard type, sysctl.conf" % len(disabled))-# files and links only: the directories that exist on the Data volume keep their own owners and modes-names = subprocess.check_output('cd %s && find . ! -type d | sort' % D, shell=True, text=True).split('\n')[:-1]-open(ST + '/list', 'w').write('\n'.join(names) + '\n')-subprocess.run(['tar', '--numeric-owner', '--format=pax', '-C', D, '-cf', '/vm/mac/overlay.tar', '-T', ST + '/list'], check=True)-print(len(names), 'entries in overlay.tar', os.path.getsize('/vm/mac/overlay.tar'))-print([n for n in names if 'GPUBundles' not in n])diff --git a/tools/dgx-spark/disk/sershell.py b/tools/dgx-spark/disk/sershell.pydeleted file mode 100755index 73dea96..0000000--- a/tools/dgx-spark/disk/sershell.py+++ /dev/null@@ -1,47 +0,0 @@-#!/usr/bin/env python3-# SPDX-License-Identifier: GPL-2.0-only-"""sershell.py SOCK CMDFILE [--wait-boot]: type each line of CMDFILE on a macOS guest's serial root shell, print its output and status."""-import socket, sys, time, re-sock_path, cmdfile = sys.argv[1], sys.argv[2]-s = socket.socket(socket.AF_UNIX);-for _ in range(150):- try: s.connect(sock_path); break- except OSError: time.sleep(0.2)-else: sys.exit("no serial socket")-s.settimeout(1)-buf = b''-def read_until(pat, timeout, start=0):- global buf- end = time.time() + timeout- while time.time() < end:- m = re.search(pat, buf[start:])- if m: return m- try:- d = s.recv(65536)- if d: buf += d- except socket.timeout: pass- return None-PROMPT = rb'(root#|sh-[0-9.]+#|# )\s*$'-if '--wait-boot' in sys.argv:- if not read_until(rb'Darwin Kernel Version', 420): sys.exit('no kernel')- if not read_until(PROMPT, 120):- for _ in range(30):- st = len(buf); s.send(b'\n')- if read_until(PROMPT, 10, st): break- else: sys.exit('no prompt')- print('[prompt]', flush=True)-n = 0-for line in open(cmdfile):- line = line.rstrip('\n')- if not line or line.startswith('#'): continue- to = 120- m = re.match(r'^@(\d+) (.*)', line)- if m: to, line = int(m.group(1)), m.group(2)- n += 1; tag = f'__DONE_{n}_{int(time.time())}__'- st = len(buf); s.send((line + f'; echo {tag}$?\n').encode())- m = read_until((tag + r'(\d+)').encode(), to, st)- out = buf[st:].decode('utf-8', 'replace')- out = out.replace(line + f'; echo {tag}$?', '', 1)- out = re.sub(tag + r'\d+', '', out).strip('\r\n')- print(f'$ {line[:150]}\n{out}\n[status {m.group(1).decode() if m else "TIMEOUT"}]', flush=True)- if not m: breakdiff --git a/tools/dgx-spark/disk/tboot.sh b/tools/dgx-spark/disk/tboot.shdeleted file mode 100755index 4d76b38..0000000--- a/tools/dgx-spark/disk/tboot.sh+++ /dev/null@@ -1,11 +0,0 @@-#!/usr/bin/env bash-# SPDX-License-Identifier: GPL-2.0-only-# boot the pristine target single-user (its own keys open its Data volume) with a raw payload disk for a tar of Data-# The vmapple stack's pieces come from the environment: VMAPPLE_DEPS (the prefix its libraries were installed to),-# VMAPPLE_QEMU, VMAPPLE_ROM; vmapple-cli is on PATH.-: "${VMAPPLE_DEPS:?} ${VMAPPLE_QEMU:?} ${VMAPPLE_ROM:?}"-export LD_LIBRARY_PATH=$VMAPPLE_DEPS/lib PATH=$VMAPPLE_DEPS/bin:$PATH-export VMAPPLE_ROM VMAPPLE_QEMU=${SIP_QEMU:-$HOME/xnuvm/qemu-sip/build/qemu-system-aarch64} QEMU_VMAPPLE_LP_SIP0=${LP_SIP0:-0x86f}-M=$HOME/xnuvm/mac-export VMAPPLE_QEMU_ARGS="-drive if=none,format=raw,file.filename=$M/payload.img,file.locking=off,id=x2 -device virtio-blk-pci,drive=x2"-cd $M; exec vmapple-cli boot xnu272 --boot-args="-s -v serial=11 debug=0x14c" --cpus 4 --memory 8diff --git a/tools/dgx-spark/disk/trustcache-from-ipsw.py b/tools/dgx-spark/disk/trustcache-from-ipsw.pydeleted file mode 100644index 9c2c371..0000000--- a/tools/dgx-spark/disk/trustcache-from-ipsw.py+++ /dev/null@@ -1,10 +0,0 @@-# SPDX-License-Identifier: GPL-2.0-only-import plistlib, zipfile, sys, struct, subprocess, os-z = zipfile.ZipFile(sys.argv[1]) # the restore IPSW; blacktop's ipsw is on PATH-bm = plistlib.loads(z.read('BuildManifest.plist'))-ids = [i for i in bm['BuildIdentities'] if i['Info']['DeviceClass'].lower() == 'vma2macosap' and i['Info'].get('RestoreBehavior') == 'Erase' and 'Customer' in i['Info'].get('Variant', '')]-print(len(ids), 'identities'); path = ids[0]['Manifest']['StaticTrustCache']['Info']['Path']; print(path)-open('static.im4p', 'wb').write(z.read(path))-subprocess.run(['ipsw', 'img4', 'im4p', 'extract', '-o', 'trustcache-mac.bin', 'static.im4p'], check=True, capture_output=True)-p = open('trustcache-mac.bin', 'rb').read(); v, c = struct.unpack_from('<I', p, 0)[0], struct.unpack_from('<I', p, 20)[0]-print('trust cache version', v, 'entries', c, 'bytes', len(p), 'expected', 24 + c * (24 if v == 2 else 22))diff --git a/tools/dgx-spark/guest/Dockerfile b/tools/dgx-spark/guest/Dockerfileindex 19c2a74..f24ce31 100644--- a/tools/dgx-spark/guest/Dockerfile+++ b/tools/dgx-spark/guest/Dockerfile@@ -1,2 +1,3 @@+# SPDX-License-Identifier: GPL-2.0-onlyFROM ubuntu:24.04RUN apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends qemu-system-arm qemu-efi-aarch64 qemu-utils cloud-image-utils genisoimage ipxe-qemu >/dev/null && rm -rf /var/lib/apt/lists/*diff --git a/tools/dgx-spark/guest/run-vm.sh b/tools/dgx-spark/guest/run-vm.shindex d427cb6..67f356e 100755--- a/tools/dgx-spark/guest/run-vm.sh+++ b/tools/dgx-spark/guest/run-vm.sh@@ -1,9 +1,10 @@#!/bin/bash# SPDX-License-Identifier: GPL-2.0-only# the xnulinux guest: arm64 Ubuntu under KVM, QEMU from a container (no QEMU on the host). ssh: 127.0.0.1:2222, key ~/xnuvm/vmkey+# CPUSET= pins it (on the GB10: 5-9,15-19, the X925 cores)V=~/xnuvm; MEM=${MEM:-24576}; CPUS=${CPUS:-10}docker rm -f xnuvm >/dev/null 2>&1-docker run -d --name xnuvm --device /dev/kvm --group-add $(stat -c %g /dev/kvm) --network host --cpuset-cpus 5-9,15-19 -v $V:/vm xnuvm-qemu \+docker run -d --name xnuvm --device /dev/kvm --group-add $(stat -c %g /dev/kvm) --network host ${CPUSET:+--cpuset-cpus "$CPUSET"} -v $V:/vm xnuvm-qemu \qemu-system-aarch64 -machine virt,gic-version=host -accel kvm -cpu host -smp $CPUS -m $MEM \-drive if=pflash,format=raw,readonly=on,file=/usr/share/AAVMF/AAVMF_CODE.fd -drive if=pflash,format=raw,file=/vm/vars.fd \-drive if=none,id=d0,file=/vm/disk.img,format=raw,cache=none,aio=native,discard=unmap -device virtio-blk-pci,drive=d0 \diff --git a/tools/dgx-spark/qemu/build.sh b/tools/dgx-spark/qemu/build.shdeleted file mode 100755index 29d114d..0000000--- a/tools/dgx-spark/qemu/build.sh+++ /dev/null@@ -1,11 +0,0 @@-# SPDX-License-Identifier: GPL-2.0-only-# Build a copy of the vmapple QEMU with qemu-vmapple-lp-sip0.patch: SRC=<its checkout (deps/reims-vgpu, deps/metal2vulkan)> build.sh-set -e-HERE=$(cd "$(dirname "$0")" && pwd); : "${SRC:?}"; W=${W:-$HOME/xnuvm/qemu-sip}; mkdir -p "$W"; cd "$W"-[ -d reims-vgpu ] || cp -a "$SRC/deps/reims-vgpu" reims-vgpu-[ -d metal2vulkan ] || cp -a "$SRC/deps/metal2vulkan" metal2vulkan-grep -q QEMU_VMAPPLE_LP_SIP0 reims-vgpu/vendor/qemu/target/arm/kvm.c || patch -d reims-vgpu/vendor/qemu -p1 < "$HERE/qemu-vmapple-lp-sip0.patch"-mkdir -p build && cd build-export PATH=$SRC/.venv/bin:$HOME/.cargo/bin:/usr/lib/llvm-20/bin:$PATH-[ -f build.ninja ] || ../reims-vgpu/vendor/qemu/configure --target-list=aarch64-softmmu --enable-kvm --enable-tcg --enable-slirp --enable-fdt --disable-docs --disable-werror --disable-gtk --disable-sdl --disable-vnc --disable-capstone --disable-rust --enable-download --python=$SRC/.venv/bin/python3 -Dreims_vgpu_backend=vulkan-ninja qemu-system-aarch64diff --git a/tools/dgx-spark/qemu/qemu-vmapple-lp-sip0.patch b/tools/dgx-spark/qemu/qemu-vmapple-lp-sip0.patchdeleted file mode 100644index cd2c937..0000000--- a/tools/dgx-spark/qemu/qemu-vmapple-lp-sip0.patch+++ /dev/null@@ -1,99 +0,0 @@---- a/target/arm/kvm.c-+++ b/target/arm/kvm.c-@@ -1649,6 +1649,85 @@- return true;- }--+#define VMAPPLE_LP_SIP0_ENTRY (36u + 8u)-+static bool vmapple_find_asmb(uint8_t *tree, uint32_t size, uint32_t offset,-+ int depth, bool *found, uint32_t *node,-+ uint32_t *props_end, uint32_t *next)-+{-+ uint32_t properties, children, cursor, i;-+ bool is_asmb = false;-+ if (offset + 8 > size || depth > 128) {-+ return false;-+ }-+ properties = ldl_le_p(tree + offset);-+ children = ldl_le_p(tree + offset + 4);-+ cursor = offset + 8;-+ for (i = 0; i < properties; i++) {-+ const char *name;-+ uint32_t length, start;-+ if (cursor + 36 > size) {-+ return false;-+ }-+ name = (const char *)(tree + cursor);-+ length = ldl_le_p(tree + cursor + 32) & 0x00ffffffu;-+ start = cursor + 36;-+ if (start + length > size) {-+ return false;-+ }-+ if (!strcmp(name, "name") && length == 5 &&-+ !memcmp(tree + start, "asmb", 5)) {-+ is_asmb = true;-+ }-+ cursor = start + vmapple_align4(length);-+ }-+ if (is_asmb && !*found) {-+ *found = true;-+ *node = offset;-+ *props_end = cursor;-+ }-+ for (i = 0; i < children; i++) {-+ uint32_t child_next;-+ if (!vmapple_find_asmb(tree, size, cursor, depth + 1, found, node,-+ props_end, &child_next)) {-+ return false;-+ }-+ cursor = child_next;-+ }-+ *next = cursor;-+ return true;-+}-+-+static void vmapple_insert_lp_sip0(uint64_t tree_pa, uint32_t tree_len,-+ uint64_t value)-+{-+ uint8_t *tree = g_malloc0(tree_len);-+ uint32_t node = 0, end = 0, next = 0;-+ bool found = false;-+ if (address_space_read(&address_space_memory, tree_pa,-+ MEMTXATTRS_UNSPECIFIED, tree, tree_len) != MEMTX_OK) {-+ error_report("vmapple handoff: lp-sip0: cannot read the device tree");-+ goto out;-+ }-+ if (!vmapple_find_asmb(tree, tree_len, 0, 0, &found, &node, &end, &next) ||-+ !found || next + VMAPPLE_LP_SIP0_ENTRY > tree_len) {-+ error_report("vmapple handoff: lp-sip0: /chosen/asmb not found or no "-+ "room (found %d, tree ends at 0x%x of 0x%x)", found, next, tree_len);-+ goto out;-+ }-+ memmove(tree + end + VMAPPLE_LP_SIP0_ENTRY, tree + end, next - end);-+ memset(tree + end, 0, VMAPPLE_LP_SIP0_ENTRY);-+ memcpy(tree + end, "lp-sip0", 7);-+ stl_le_p(tree + end + 32, 8);-+ stq_le_p(tree + end + 36, value);-+ stl_le_p(tree + node, ldl_le_p(tree + node) + 1);-+ address_space_write(&address_space_memory, tree_pa, MEMTXATTRS_UNSPECIFIED,-+ tree, tree_len);-+ info_report("vmapple handoff: lp-sip0 = 0x%" PRIx64 " added to /chosen/asmb "-+ "(tree 0x%x of 0x%x bytes)", value, next + VMAPPLE_LP_SIP0_ENTRY, tree_len);-+out:-+ g_free(tree);-+}-+- static bool vmapple_handoff_apply(CPUState *cs)- {- ARMCPU *cpu = ARM_CPU(cs);-@@ -1713,6 +1792,10 @@- info_report("vmapple handoff: %d timebase properties set to %u Hz",- patched, freq);--+ if (g_getenv("QEMU_VMAPPLE_LP_SIP0")) {-+ vmapple_insert_lp_sip0(tree_pa, tree_len,-+ g_ascii_strtoull(g_getenv("QEMU_VMAPPLE_LP_SIP0"), NULL, 0));-+ }- vmapple_patch_gic_store(pbase);- return true;- }