XNU as a loadable kernel module inside Linux (macOS personality for arm64 Linux)
C
XNU patches as a topic series over a typed host interface; debug instrumentation out of the default build
Heyang Zhouddf4be48600b
diff --git a/README.md b/README.mdindex 2b7d2da..d831005 100644--- a/README.md+++ b/README.md@@ -11,7 +11,7 @@ The two sides are kept apart by license and only meet at the FKI (foreign kernel| `linux/` | GPL-2.0 | In-tree FKI patch for Linux (`drivers/fki`, `include/linux/fki.h`) || `fki-ko/` | GPL-2.0 | The same FKI v0 as an out-of-tree module, for stock distro kernels || `xnu-ko/` | APSL-2.0 side | `xnu.ko`: loads the XNU kernel collection and calls into it; uses only FKI |-| `xnu-patches/` | APSL-2.0 | The LINUX64 machine layer and hosted-kernel changes, applied to XNU's sources |+| `xnu-patches/` | APSL-2.0 | The LINUX64 machine layer and hosted-kernel changes, applied to XNU's sources; `include/linux64_abi.h` is the interface xnu.ko and XNU share || `kexts/` | BSD-2-Clause | Our kexts in the kernel collection: disk, display, input, Ethernet, keystore stand-ins, Metal accelerator, DRM bridge || `gpu/` | per directory | Metal plugin (`xnu-cpu-metal`), the DRM bridge's user-space ends (`xnu-drm`), Mesa Venus patches (`venus`) || `scripts/`, `tools/` | | Build, disk, boot and test tools |@@ -32,7 +32,8 @@ build time; it is never committed.- Rendering: `gpu/xnu-cpu-metal` is a Metal device (metal2vulkan) over Mesa lavapipe on the CPU. The DRM bridge(`fki-ko/fki_hostcall.c`, `kexts/XnuDrm`, `gpu/xnu-drm`) gives hosted processes the Linux host's GPU through Mesa Venus:on an Apple Silicon host the Linux VM runs under krunkit (`scripts/krun-vm.sh`) and Vulkan in the hosted macOS runs on the- host's GPU (`Virtio-GPU Venus (Apple M5 Max)`). Moving the Metal plugin onto it is in progress.+ host's GPU (`Virtio-GPU Venus (Apple M5 Max)`): the Metal plugin takes it when the bridge is there, and WindowServer+ composites the desktop on the host GPU.- From PoC to production: [`docs/production.md`](docs/production.md).## Runningdiff --git a/docs/production.md b/docs/production.mdindex 02c12e8..c210230 100644--- a/docs/production.md+++ b/docs/production.md@@ -6,18 +6,19 @@ What the PoC did to get each step running, and what replaces it. Ordered by what| Now | Replace with ||---|---|-| One 4300-line patch (`xnu-patches/0001-linux64-stage-hook.patch`, 61 files) | A topic series: `00xx-linux64-{config,el0,pmap,timer,upcall,iokit-platform,bsd-root,syscalls,amfi,debug}.patch`, each building on its own |-| `extern uintptr_t linux64_hook;` declared inline at ~60 call sites, `if (linux64_hook)` as the hosted test | One header (`osfmk/arm64/linux64.h`): `linux64_hosted()`, typed upcall wrappers; code under `CONFIG_LINUX64` so a non-hosted build is the stock kernel |-| Debug instrumentation in the hot paths (`linux64_dbg[16]` counters in the idle loop, scheduler, EL0 entry; a thread dump every 150000 idle rounds; `DEBUG_BSDINIT 1`) | Behind `LINUX64_DEBUG` (off by default), thread dump on demand (an upcall from the host), not on an idle counter |-| Dead paths from earlier milestones: the BSD `ifnet` half of `bsd/net/if_linux64.c` (`kexts/XnuEthernet` is en0 now; only its frame transport stays, as ABI calls), memdev host mode `hostdisk=` (replaced by `kexts/XnuDisk`), HFS+ read-write root | Removed |+| Done: four topic patches (`xnu-patches/000{1..4}-linux64-*.patch`: machine layer, host devices, boot without iBoot, macOS 27 userland), each file in one of them | Finer topics as they change (el0, pmap, timer within the machine layer) |+| Done: one header pair (`xnu-patches/include/linux64.h`, `linux64_abi.h`, copied into `EXTERNAL_HEADERS/linux64`); calls through `linux64_call()`; `if (linux64_hook)` as the hosted test | Code under `CONFIG_LINUX64` so a non-hosted build is the stock kernel |+| Done: bring-up stage markers, the dead second idle path, the kernel's own en0, unused page-table walkers and probes removed; the idle-loop thread dump behind `LINUX64_DEBUG`; system call and exec path logging only with boot-arg `linux64_trace`; monitor counters named (`enum linux64_counter`) | A thread dump on demand (a call from the host) instead of on an idle counter |+| Done: the PoC's non-cryptographic xorshift fallback for `read_random`/`cc_rand_generate` before corecrypto registers | The host's generator (`LINUX64_CALL_RANDOM`: Linux `get_random_bytes`) |+| memdev host mode `hostdisk=` (replaced by `kexts/XnuDisk`), HFS+ read-write root | Removed |## 2. The xnu.ko ↔ XNU boundary| Now | Replace with ||---|---|-| Upcalls are bare stage numbers (810–821, 993–995) with ad-hoc argument structs | `xnu-ko/linux64_abi.h`, shared by both sides: an enum of named calls, one request struct per call, a version number checked at load |+| Done: `linux64_abi.h` shared by both sides: named calls (`enum linux64_call`), one request struct per call, `LINUX64_ABI_VERSION`; xnu.ko logs a call it does not know and goes on | Check the version at load (XNU exports it) || Console input, input events, framebuffer: host files appended to or dumped on a timer (`console_in=`, `input_in=`, `fb_dump=`) | Character devices from fki.ko (`/dev/xnu/console`, `/dev/xnu/input`, `/dev/xnu/fb` with mmap), so a host program talks to them like any device |-| Module parameters for everything (`stop`, `kmax`, `idle_max`, `mode`, bisecting knobs) | Drop the PoC-only ones; the run ends when XNU halts, not on a counter |+| Module parameters from bring-up (`mode`, `kmax`, `idle_max`, `ramdisk`, `hostdisk`; `stop` is gone, `kmax`/`idle_max` default to no limit) | Drop the rest; the run ends when XNU halts |## 3. Boot and the system disk@@ -32,7 +33,7 @@ What the PoC did to get each step running, and what replaces it. Ordered by what| Now | Replace with ||---|---|-| ~30 scripts; the boot itself ran from `vm-m2-kbisect.sh` (now `xnulinux-boot.sh`: builds, checks, retries, GPU bridge) (`mode=3 stop=899 kmax=…`, a bisecting tool's knobs); several have session paths (`/Users/admin/...`), tty names, fixed `sleep`s | One driver (`xnulinux` CLI): `build`, `disk`, `boot`, `console`, `screenshot`, `test`; configuration in one file |+| ~30 scripts; the boot runs from `xnulinux-boot.sh` (builds, checks, retries, GPU bridge; the bisecting `vm-m2-kbisect.sh` is gone); several have session paths (`/Users/admin/...`), tty names, fixed `sleep`s | One driver (`xnulinux` CLI): `build`, `disk`, `boot`, `console`, `screenshot`, `test`; configuration in one file || HFS+ route scripts (`mk-fulldisk.sh`, `vm-sysdisk-*`, `vm-mk-sysdisk.sh`, `vm-m2-*`, `run-poc.sh`) | Removed (done: APFS route only) || `tools/hosted/tests/t*.sh`, `af*.sh`: one-off probes (removed) | A test suite with expected results: boot to desktop, Safari/Chrome page load (screenshot compare), `xcodebuild` of a pinned project, Metal unit tests || No CI | CI: fki.ko/xnu.ko build against a pinned kernel, XNU + collection build (x86_64 Linux works with the DroidVM toolchain), GPU plugin host tests on macOS |@@ -62,5 +63,9 @@ Venus → MoltenVK → Metal on the host GPU); on a Linux machine with its own Gthe render node), `gpu/xnu-drm/darwin` (libxnudrm, compiled into Mesa by `gpu/venus/patches/0002`).- Metal on it: the plugin (`gpu/xnu-cpu-metal`) carries both drivers and takes Venus when `XnuDrm` is there; a Metalprogram in the hosted macOS gets `Virtio-GPU Venus (Apple M5 Max)` (textures, IOSurface textures, buffers, blits).- Open: WindowServer still ends on lavapipe (the loader runs in secure mode there and sees both drivers); IOSurfaces- are still copied to and from GPU memory each frame (2-5 ms at 1080p-1440p, measured on the host).+- WindowServer composites on the host GPU: the plugin hands the loader the chosen driver directly+ (`VK_LUNARG_direct_driver_loading`, lavapipe is not loaded with Venus), the bridge's user client sits on the Metal+ accelerator service (the sandbox's `system-graphics` rule), and `newBufferWithBytesNoCopy` buffers, copied because+ Venus has no `VK_EXT_external_memory_host`, are synced from the caller's memory before each submission.+- Open: those copies (up to the 33 MB wallpaper per submission) and the IOSurface copies to and from GPU memory each+ frame (2-5 ms at 1080p-1440p, measured on the host): host-memory import and IOSurfaces backed by bridge blobs.diff --git a/kexts/XnuDrm/XnuDrm.cpp b/kexts/XnuDrm/XnuDrm.cppindex f2172e7..4c8a08f 100644--- a/kexts/XnuDrm/XnuDrm.cpp+++ b/kexts/XnuDrm/XnuDrm.cpp@@ -1,6 +1,6 @@// SPDX-License-Identifier: BSD-2-Clause// XnuDrm: the hosted macOS's door to the Linux host's GPU (the DRM bridge, gpu/xnu-drm). A process opens a user client-// (libxnudrm, inside Mesa's Venus driver); each of its requests is one host call (linux64_hostcall: upcall 830, xnu.ko,+// (libxnudrm, inside Mesa's Venus driver); each of its requests is one host call (linux64_hostcall: LINUX64_CALL_HOSTCALL, xnu.ko,// fki) answered by xnudrmd, the Linux service that owns the DRM render node. Buffer mappings come back as the physical// pages Linux mapped, which this kext maps into the calling task: the process and the GPU share the memory, no copies.//diff --git a/kexts/XnuEAN/XnuEAN.cpp b/kexts/XnuEAN/XnuEAN.cppindex 01feea0..f02b053 100644--- a/kexts/XnuEAN/XnuEAN.cpp+++ b/kexts/XnuEAN/XnuEAN.cpp@@ -10,7 +10,7 @@//// Here: an AppleNVMeEAN instance (never started: it has no device) is registered so the cast succeeds, and the four entry// points of the class are redirected to the functions below (a branch written over each one's first instruction). The blobs-// live in memory and are written through to a file on the Linux side (xnu.ko keystore=, upcall 819 in bsd/net/if_linux64.c),+// live in memory and are written through to a file on the Linux side (xnu.ko keystore=, linux64_store_rw in bsd/kern/linux64_host.c),// so they last as long as that file does. Nothing else on this system uses AppleNVMeEAN.#include <IOKit/IOLib.h>#include <IOKit/IOLocks.h>diff --git a/scripts/vm-m2-kbisect.sh b/scripts/vm-m2-kbisect.shdeleted file mode 100755index 828b4af..0000000--- a/scripts/vm-m2-kbisect.sh+++ /dev/null@@ -1,25 +0,0 @@-#!/bin/bash-# Inside the VM: run M2 with stop=999 (no stage stop) and kmax=K XNU kprintf lines, for each K.-cd ~/w/poc-make -s -C /lib/modules/$(uname -r)/build M=$PWD/fki-ko modules >/dev/null 2>&1-make -s -C /lib/modules/$(uname -r)/build M=$PWD/xnu-ko clean >/dev/null 2>&1-make -s -C /lib/modules/$(uname -r)/build M=$PWD/xnu-ko KBUILD_EXTRA_SYMBOLS=$PWD/fki-ko/Module.symvers modules >/dev/null 2>&1-sudo dmesg -n ${CONLEVEL:-8}-sudo rmmod xnu 2>/dev/null; sudo rmmod fki 2>/dev/null; sudo insmod fki-ko/fki.ko-bash scripts/vm-net-up.sh # the hosted macOS's en0: xnu0, NAT, DHCP/DNS-# a hosted XNU never unmounts its read-write root: check the host disk before each boot-if [ -n "$HOSTDISK" ] && [ "${HOSTDISK#/dev/}" = "$HOSTDISK" ]; then- for t in 1 2 3; do r=$(sudo fsck.hfsplus -fy "$HOSTDISK" 2>&1 | tail -1); echo "fsck: $r"; case "$r" in *"appears to be OK"*) break;; esac; done-fi-# XNU's DRAM is one physically contiguous block (GBs): free the page cache and compact first, or the allocation fails-sync; echo 3 | sudo tee /proc/sys/vm/drop_caches >/dev/null; echo 1 | sudo tee /proc/sys/vm/compact_memory >/dev/null-[ -n "${FB_DUMP:-}" ] && { : > "$FB_DUMP"; } # xnu.ko writes the framebuffer into this existing file-[ -n "${INPUT_IN:-}" ] && { touch "$INPUT_IN"; } # input events for XnuInput (tools/hosted/xnu-input.py appends)-for K in "$@"; do- sudo dmesg -C- echo ">>> kmax=$K"; sync- sudo insmod xnu-ko/xnu.ko mode=3 stop=899 kmax=$K idle_max=${IDLE_MAX:-200} ram_mb=${RAM_MB:-128} ${IMAGE:+image=$IMAGE} ${RAMDISK:+ramdisk=$RAMDISK} ${TRUSTCACHE:+trustcache=$TRUSTCACHE} ${HOSTDISK:+hostdisk=$HOSTDISK hostdisk_rw=1} ${CONSOLE_IN:+console_in=$CONSOLE_IN} ${FB_DUMP:+fb_dump=$FB_DUMP} ${INPUT_IN:+input_in=$INPUT_IN} ${KEYSTORE:+keystore=$KEYSTORE} ${DISK:+disk=$DISK} ${BOOT_UUID:+boot_uuid=$BOOT_UUID} ${PREBOOT_UUID:+preboot_uuid=$PREBOOT_UUID} ${ROOT_UUID:+root_uuid=$ROOT_UUID} ${BOOTARGS:+bootargs=\"$BOOTARGS\"}- echo "lines: $(sudo dmesg | grep -ac 'xnu\]')"- sudo dmesg | grep -a "xnu\]\|XNU stage 4\|budget\|panic\|run ended" | tail -${SHOW:-4}- sudo rmmod xnu-donediff --git a/scripts/vm-xnu-rebuild.sh b/scripts/vm-xnu-rebuild.shindex af5891e..9e81dd0 100755--- a/scripts/vm-xnu-rebuild.sh+++ b/scripts/vm-xnu-rebuild.sh@@ -6,10 +6,15 @@ set -e -o pipefail # a failed kernel build stops here: never repackage the previcd ~/w/dvmexport PATH=$PATH:/usr/lib/llvm-21/binT=out/k27/xnu-for p in ~/w/poc/xnu-patches/*.patch; do- for f in $(grep '^+++ b/' $p | sed 's|^+++ b/||'); do git -C $T checkout -q -- $f 2>/dev/null || rm -f $T/$f; done+# back to the tree's own sources: every file the patches touched last time (.linux64-patched) or touch now+P=~/w/poc/xnu-patches+for f in $(cat $T/.linux64-patched 2>/dev/null; grep -h '^+++ b/' $P/*.patch | sed 's|^+++ b/||'); do+ git -C $T checkout -q -- $f 2>/dev/null || rm -f $T/$fdone-for p in ~/w/poc/xnu-patches/*.patch; do git -C $T apply $p; echo "applied $(basename $p)"; done+for p in $P/*.patch; do git -C $T apply $p; echo "applied $(basename $p)"; done+grep -h '^+++ b/' $P/*.patch | sed 's|^+++ b/||' > $T/.linux64-patched+# the machine layer's headers (shared with xnu.ko), where every component's sources find them+mkdir -p $T/EXTERNAL_HEADERS/linux64 && cp $P/include/*.h $T/EXTERNAL_HEADERS/linux64/JOBS=12 bash k27/build-kernel27.sh 2>&1 | tail -15if [ -e out/kc/kc27.bin ]; then# the hosted system's extra Apple kexts (in kc27, not kept by default): IOSurface for actool, CoreImage and friendsdiff --git a/scripts/xnulinux-boot.sh b/scripts/xnulinux-boot.shindex 968809c..2826a3f 100755--- a/scripts/xnulinux-boot.sh+++ b/scripts/xnulinux-boot.sh@@ -45,12 +45,12 @@ rm -f "$KEYSTORE"; truncate -s 1M "$KEYSTORE" # fresh each boot, as the disk was# XNU's DRAM is one physically contiguous block (GBs, from CMA): free the page cache and compact first. Right after the VM# boots the allocation can still fail with the area free (a page in the way not yet migratable): wait and try again,# for up to three minutes.-# mode=3: the kernel collection; the run lasts until the hosted system halts (no stage stop, no line or idle budget).+# mode=3: the kernel collection; the run lasts until the hosted system halts.# insmod returns when the run ends: it runs detached, its output in /var/tmp/xnu-insmod.log.for try in 1 2 3 4 5 6 7 8 9; dosync; echo 3 | sudo tee /proc/sys/vm/drop_caches >/dev/null; echo 1 | sudo tee /proc/sys/vm/compact_memory >/dev/nullsudo dmesg -C- sudo setsid nohup insmod xnu-ko/xnu.ko mode=3 stop=899 kmax=1000000000 idle_max=2000000000 ram_mb="$RAM_MB" image="$IMAGE" \+ sudo setsid nohup insmod xnu-ko/xnu.ko mode=3 ram_mb="$RAM_MB" image="$IMAGE" \trustcache="$TRUSTCACHE" disk="$DISK" root_uuid="$ROOT_UUID" boot_uuid="$BOOT_UUID" preboot_uuid="$BOOT_UUID" \console_in="$CONSOLE_IN" input_in="$INPUT_IN" fb_dump="$FB_DUMP" keystore="$KEYSTORE" bootargs="\"$BOOTARGS\"" \> /var/tmp/xnu-insmod.log 2>&1 < /dev/null &diff --git a/xnu-ko/xnu_main.c b/xnu-ko/xnu_main.cindex a1e4bc7..0ddc2fd 100644--- a/xnu-ko/xnu_main.c+++ b/xnu-ko/xnu_main.c@@ -3,10 +3,10 @@* xnu.ko: hosts an XNU kernel image inside Linux. Talks to Linux only* through FKI (fki.h); <linux/module.h> provides the module ABI.*- * mode=1 (M1): load, slide and sign the image, call two XNU functions.- * mode=2 (M2a, default): hand XNU boot args and an ADT and run arm_init in- * the XNU world; XNU reports stages through linux64_hook, and the run- * ends at stage `stop`.+ * mode=1: load, slide and sign the image, call two XNU functions (a smoke test).+ * mode=2: a bare kernel image; mode=3: a kernel collection. Hand XNU boot args+ * and an ADT and run arm_init in the XNU world; XNU calls into this+ * module through linux64_hook (the interface: linux64_abi.h).*/#include <linux/module.h>#include "../fki-ko/fki.h"@@ -14,19 +14,18 @@#include "macho.h"#include "adt.h"#include "world.h"+#include "../xnu-patches/include/linux64_abi.h"static char *image = "xnu/kernel.macho";module_param(image, charp, 0444);static int mode = 2;module_param(mode, int, 0444);-static int stop = 199;-module_param(stop, int, 0444);static int ram_mb = 256;module_param(ram_mb, int, 0444);static int kmax; /* end the run after this many XNU kprintf lines (0: no limit) */module_param(kmax, int, 0444);static int kcount;-static int idle_max = 200; /* end the run after this many XNU idle rounds (0: never) */+static int idle_max; /* end the run after this many XNU idle rounds (0: never) */module_param(idle_max, int, 0444);static int quiet_console = 1; /* drop the known high-volume console and kprintf lines (see quiet_line) */module_param(quiet_console, int, 0444);@@ -81,27 +80,26 @@ module_param(fb_dump_ms, int, 0444);static u64_t fb_off; /* the framebuffer's offset in the contiguous region (its Linux address: img.region.va + fb_off) */#define FB_SIZE (fb_width > 0 && fb_height > 0 ? (u64_t)fb_width * fb_height * 4 : 0)#define BOOT_EXTRA (((rd_size + 0x3fff) & ~0x3fffULL) + ((TC_SEG_SIZE + 0x3fff) & ~0x3fffULL) + ((FB_SIZE + 0x3fff) & ~0x3fffULL))-/* A root disk backed by a host file (an HFS+ image): XNU's memdev md0 in host mode, stages 995 (size) and 994 (I/O). */+/* A root disk backed by a host file (an HFS+ image): XNU's memdev md0 in host mode (LINUX64_CALL_RAMDISK_SIZE, _RW). */static char *hostdisk;static int hostdisk_rw;module_param(hostdisk, charp, 0444);module_param(hostdisk_rw, int, 0444);static void *hd_file; static fki_u64 hd_size;-/* Console input for XNU's /dev/console: bytes appended to this host file are typed in (stage 993) */+/* Console input for XNU's /dev/console: bytes appended to this host file are typed in (LINUX64_CALL_CONSOLE_READ) */static char *console_in;module_param(console_in, charp, 0444);static void *ci_file; static fki_u64 ci_off;-struct xnu_cons_req { void *buf; u64_t len; long result; };/** Input events for XnuInput (kexts/XnuInput): a host file of 8-byte records {u16 type, u16 code, s32 value} as Linux's evdev- * (tools/hosted/xnu-input.py appends them); upcall 818 reads the whole records written since the load.+ * (tools/hosted/xnu-input.py appends them); LINUX64_CALL_INPUT_READ reads the whole records written since the load.*/static char *input_in;module_param(input_in, charp, 0444);-static char *keystore; /* the hosted keystore's file (XnuEAN's EAN blobs): read and written through upcall 819 */+static char *keystore; /* the hosted keystore's file (XnuEAN's EAN blobs): read and written through LINUX64_CALL_KEYSTORE_RW */module_param(keystore, charp, 0444);static void *ks_file;-/* The hosted system's block disk (kexts/XnuDisk: IOKit media, e.g. an APFS container), read-write: upcalls 821 (size), 820 (I/O) */+/* The hosted system's block disk (kexts/XnuDisk: IOKit media, e.g. an APFS container), read-write (LINUX64_CALL_DISK_SIZE, _RW) */static char *disk;module_param(disk, charp, 0444);static void *dk_file; static fki_u64 dk_size;@@ -122,11 +120,6 @@ static char *root_uuid;module_param(root_uuid, charp, 0444);static char root_matching[256];static void *in_file; static fki_u64 in_off;-/* hook returns must be 0 (nonzero ends the run): results come back through the request */-struct xnu_hostdisk_req { u64_t write, off, len; void *buf; long result; };-/* A host call (upcall 830, kexts/XnuDrm): request and reply buffers in XNU memory, through fki to a Linux service */-struct xnu_hostcall_req { const void *req; u64_t len; void *reply; u64_t max; long result; };-struct xnu_net_req { void *buf; u64_t len; long result; };struct xnu_world xnu_W;static void logs(const char *s) { fki_log(s, x_strlen(s)); }@@ -256,7 +249,7 @@ unsigned long xnu_fault_deferred(unsigned long *frame)}/* a fault loop runs with interrupts masked: let Linux take its interrupts now and then (RCU, network) */if ((repeats & 63) == 63)- ((void (*)(unsigned long, unsigned long, unsigned long))xnu_world_upcall)(811, 0, 0);+ ((void (*)(unsigned long, unsigned long, unsigned long))xnu_world_upcall)(LINUX64_CALL_PREEMPTED, 0, 0);return pc;}/* inside copyin/copyout: the routine's recovery path returns EFAULT to its caller, as XNU's own abort handler does */@@ -329,8 +322,9 @@ static int xnu_fault(unsigned long far, unsigned long esr, void *regs)return 0;}-static long xnu_hook_body(unsigned long stage, unsigned long a1, unsigned long a2);-long xnu_hook(unsigned long stage, unsigned long a1, unsigned long a2)+/* XNU calls into the host: enum linux64_call (linux64_abi.h); a non-zero return ends the run */+static long xnu_hook_body(unsigned long call, unsigned long a1, unsigned long a2);+long xnu_hook(unsigned long call, unsigned long a1, unsigned long a2){{/* debugging: an XNU stack Linux's overflow check would reject (bit 14 of sp set) */@@ -340,19 +334,19 @@ long xnu_hook(unsigned long stage, unsigned long a1, unsigned long a2)if ((sp & 0x4000) && told < 3) {told++;logkv("xnu: upcall on an XNU stack with sp bit 14 set, sp", sp);- logkv("xnu: stage", stage);+ logkv("xnu: call", call);}}in_xnu = 0;- long r = xnu_hook_body(stage, a1, a2);+ long r = xnu_hook_body(call, a1, a2);if (!r) in_xnu = 1;return r;}-static long xnu_hook_body(unsigned long stage, unsigned long a1, unsigned long a2)+static long xnu_hook_body(unsigned long call, unsigned long a1, unsigned long a2){- if (stage == 993) { /* console input: new bytes of console_in */- struct xnu_cons_req *q = (struct xnu_cons_req *)a1;+ if (call == LINUX64_CALL_CONSOLE_READ) { /* console input: new bytes of console_in */+ struct linux64_buf_req *q = (struct linux64_buf_req *)a1;if (!q) return 0;q->result = 0;if (ci_file) {@@ -361,8 +355,8 @@ static long xnu_hook_body(unsigned long stage, unsigned long a1, unsigned long a}return 0;}- if (stage == 818) { /* input events: whole 8-byte records of input_in, into q->buf */- struct xnu_cons_req *q = (struct xnu_cons_req *)a1;+ if (call == LINUX64_CALL_INPUT_READ) { /* input events: whole 8-byte records of input_in, into q->buf */+ struct linux64_buf_req *q = (struct linux64_buf_req *)a1;if (!q) return 0;q->result = 0;if (in_file && q->len >= 8) {@@ -371,53 +365,53 @@ static long xnu_hook_body(unsigned long stage, unsigned long a1, unsigned long a}return 0;}- if (stage == 815) { /* frames Linux sent on xnu0 waiting for XNU, into *a1 */- if (a1) *(u64_t *)a1 = (u64_t)fki_net_pending();- return 0;- }- if (stage == 816 || stage == 817) { /* XNU's Ethernet link: 816 sends q->buf (q->len bytes), 817 receives into it */- struct xnu_net_req *q = (struct xnu_net_req *)a1;+ if (call == LINUX64_CALL_NET_SEND || call == LINUX64_CALL_NET_RECV) { /* XNU's Ethernet link: one frame each way */+ struct linux64_buf_req *q = (struct linux64_buf_req *)a1;if (!q) return 0;- q->result = stage == 816 ? fki_net_send(q->buf, (unsigned long)q->len) : fki_net_recv(q->buf, (unsigned long)q->len);+ q->result = call == LINUX64_CALL_NET_SEND ? fki_net_send(q->buf, (unsigned long)q->len) : fki_net_recv(q->buf, (unsigned long)q->len);return 0;}- if (stage == 812) { /* the host's wall clock for XNU's calendar: a1 -> u64[2] {seconds, nanoseconds} UTC */+ if (call == LINUX64_CALL_WALLCLOCK) { /* the host's wall clock for XNU's calendar: a1 -> u64[2] {seconds, nanoseconds} UTC */if (a1) fki_realtime(&((fki_u64 *)a1)[0], &((fki_u64 *)a1)[1]);return 0;}- if (stage == 830) { /* host call: q->result = the reply's length or -errno */- struct xnu_hostcall_req *q = (struct xnu_hostcall_req *)a1;+ if (call == LINUX64_CALL_RANDOM) { /* a1: a2 bytes from Linux's generator */+ if (a1) fki_random((void *)a1, a2);+ return 0;+ }+ if (call == LINUX64_CALL_HOSTCALL) { /* host call: q->result = the reply's length or -errno */+ struct linux64_hostcall_req *q = (struct linux64_hostcall_req *)a1;if (q) q->result = fki_hostcall(q->req, (unsigned long)q->len, q->reply, (unsigned long)q->max);return 0;}- if (stage == 821) { /* the block disk's size in bytes into *a1, 0 when there is none */+ if (call == LINUX64_CALL_DISK_SIZE) { /* the block disk's size in bytes into *a1, 0 when there is none */if (a1) *(u64_t *)a1 = dk_file ? dk_size : 0;return 0;}- if (stage == 820) { /* block disk I/O: q->result = bytes moved or -errno */- struct xnu_hostdisk_req *q = (struct xnu_hostdisk_req *)a1;+ if (call == LINUX64_CALL_DISK_RW) { /* block disk I/O: q->result = bytes moved or -errno */+ struct linux64_rw_req *q = (struct linux64_rw_req *)a1;if (q) q->result = dk_file ? fki_file_rw(dk_file, (int)q->write, q->buf, (unsigned long)q->len, q->off) : -6;return 0;}- if (stage == 819) { /* the keystore file: q->result = bytes moved or -errno */- struct xnu_hostdisk_req *q = (struct xnu_hostdisk_req *)a1;+ if (call == LINUX64_CALL_KEYSTORE_RW) { /* the keystore file: q->result = bytes moved or -errno */+ struct linux64_rw_req *q = (struct linux64_rw_req *)a1;if (!q) return 0;q->result = ks_file ? fki_file_rw(ks_file, (int)q->write, q->buf, (unsigned long)q->len, q->off) : -6;return 0;}- if (stage == 995) { /* host disk size in bytes into *a1, 0 when there is none */+ if (call == LINUX64_CALL_RAMDISK_SIZE) { /* host disk size in bytes into *a1, 0 when there is none */if (a1) *(u64_t *)a1 = hd_file ? hd_size : 0;return 0;}- if (stage == 994) { /* host disk I/O: q->result = bytes moved or -errno */- struct xnu_hostdisk_req *q = (struct xnu_hostdisk_req *)a1;+ if (call == LINUX64_CALL_RAMDISK_RW) { /* host disk I/O: q->result = bytes moved or -errno */+ struct linux64_rw_req *q = (struct linux64_rw_req *)a1;if (!q) return 0;if (!hd_file) q->result = -6;else if (q->write && !hostdisk_rw) q->result = -30;else q->result = fki_file_rw(hd_file, (int)q->write, q->buf, (unsigned long)q->len, q->off);return 0;}- if (stage == 996) { /* XNU console bytes (/dev/console): line-buffered into the host log */+ if (call == LINUX64_CALL_CONSOLE_WRITE) { /* XNU console bytes (/dev/console): line-buffered into the host log */static char line[1000]; static unsigned n;const char *b = (const char *)a1; unsigned long i;for (i = 0; b && i < a2; i++) {@@ -447,7 +441,7 @@ static long xnu_hook_body(unsigned long stage, unsigned long a1, unsigned long a}return 0;}- if (stage == 998) { /* XNU kprintf */+ if (call == LINUX64_CALL_KPRINTF) { /* XNU kprintf */char m[260]; const char *f = (const char *)a1; unsigned i = 0, j = 0;m[j++] = 'x'; m[j++] = 'n'; m[j++] = 'u'; m[j++] = ']'; m[j++] = ' ';while (f && f[i] && j < sizeof(m) - 1) { if (f[i] != '\n') m[j++] = f[i]; i++; }@@ -458,7 +452,7 @@ static long xnu_hook_body(unsigned long stage, unsigned long a1, unsigned long aif (kmax && ++kcount >= kmax) { logs("xnu: kprintf budget reached"); return 1; }return 0;}- if (stage == 210 && window_l1) { /* install XNU's kernel L1 entries (the kernel VA range only) */+ if (call == LINUX64_CALL_KERNEL_TABLES && window_l1) { /* install XNU's kernel L1 entries (the kernel VA range only) */const unsigned long long *tte = (const unsigned long long *)a1;walk_log("xnu: XNU table walk for arm_init (text)", diag_va[0], tte);walk_log("xnu: XNU table walk for the Mach-O header", diag_va[1], tte);@@ -481,18 +475,19 @@ static long xnu_hook_body(unsigned long stage, unsigned long a1, unsigned long aif (diag_va[5]) { unsigned long l = ((unsigned long (*)(const char *))diag_va[5])("xnulinux"); logkv("xnu: probe exec strlen through XNU tables", l); }logs("xnu: probes done");}- if (stage == 811) { /* XNU busy: a host IRQ preempted its user code; let Linux handle it */+ if (call == LINUX64_CALL_PREEMPTED) { /* XNU busy: a host IRQ preempted its user code; let Linux handle it */fki_yield();return 0;}- if (stage == 810) { /* XNU idle: let Linux run until XNU's next timer deadline */+ if (call == LINUX64_CALL_IDLE) { /* XNU idle: let Linux run until XNU's next timer deadline */static unsigned long idles;- if ((++idles & (idles - 1)) == 0) logkv("xnu: XNU idle, count", idles);+ idles++;+ if ((idles & (idles - 1)) == 0) logkv("xnu: XNU idle, count", idles);fki_idle_until(a1, 20000000ULL); /* at most 20 ms per round */return idle_max && idles >= (unsigned long)idle_max;}- if (stage == 997) { /* XNU assert() failed */- const struct { const char *file; long line; const char *expr; } *a = (const void *)a1;+ if (call == LINUX64_CALL_ASSERT) { /* XNU assert() failed */+ const struct linux64_assert_info *a = (const void *)a1;char m[240]; unsigned j = 0, i;const char *parts[3] = { "xnu: XNU assert failed: ", a->file, ": " };for (int p = 0; p < 3; p++)@@ -503,11 +498,11 @@ static long xnu_hook_body(unsigned long stage, unsigned long a1, unsigned long alogkv("xnu: at line", a->line);return assert_fatal;}- if (stage == 9100) { /* the first entry into user space (linux64_el0_run follows) */+ if (call == LINUX64_CALL_USER_ENTER) { /* the first entry into user space (linux64_el0_run follows) */logkv("xnu: XNU enters user space (EL0); user pc", a1);return 0;}- if (stage == 999) {+ if (call == LINUX64_CALL_PANIC) {char m[500]; const char *f = (const char *)a1; unsigned i = 0;while (f && f[i] && i < sizeof(m) - 1) { m[i] = f[i]; i++; }m[i] = 0;@@ -526,39 +521,13 @@ static long xnu_hook_body(unsigned long stage, unsigned long a1, unsigned long a}return 1;}- static const struct { unsigned long s; const char *what; } names[] = {- { 101, "image slid, structors signed" }, { 110, "PE_init_platform: ADT parsed" },- { 120, "ml_parse_cpu_topology" }, { 130, "kernel_startup_bootstrap returned" },- { 140, "timer_call_init" }, { 150, "cpu_init" }, { 160, "processor_bootstrap" },- { 170, "boot-arg parsing" }, { 175, "nanoseconds_to_absolutetime" }, { 180, "/chosen dram-base/size" },- { 199, "arm_init reached arm_vm_init" },- { 201, "arm_vm_init: memory sizes" }, { 202, "arm_vm_init: physmap placed" }, { 203, "arm_vm_init: invalid_tte" },- { 204, "arm_vm_init: kernel tables (init_ptpages)" }, { 205, "arm_vm_init: segments, page size" },- { 206, "arm_vm_prot_init" }, { 207, "arm_vm_init: dynamic tables" }, { 208, "arm_vm_physmap_init" },- { 210, "arm_vm_init: XNU's kernel L1 entries installed in Linux's table" },- { 215, "arm_vm_init: running on XNU's own page tables" }, { 220, "pmap_bootstrap returned" },- { 230, "arm_vm_init returned" }, { 300, "kprintf initialized" },- { 360, "PE_create_console" }, { 370, "PE_init_printf" }, { 380, "cpu_machine_idle_init" },- { 390, "PE_init_platform(TRUE)" }, { 400, "ml_map_cpu_pio" }, { 410, "cpu_timebase_init" },- { 420, "PE_init_cpu" }, { 490, "about to call machine_startup" },- };- if (stage >= 1000) {- logkv("xnu: XNU sub-stage", stage);- return stop >= 1000 && (long)stage >= stop;+ if (call == LINUX64_CALL_KERNEL_TABLES)+ return 0;+ { /* a call this module does not know (an XNU built against a newer linux64_abi.h): say so once, go on */+ static unsigned long told;+ if (told != call) { told = call; logkv("xnu: unknown call from XNU", call); }}- const char *what = "?";- for (unsigned i = 0; i < sizeof(names) / sizeof(names[0]); i++)- if (names[i].s == stage) what = names[i].what;- char buf[96]; char *p = buf; const char *q = "xnu: XNU stage ";- while (*q) *p++ = *q++;- p[0] = '0' + stage / 100; p[1] = '0' + stage / 10 % 10; p[2] = '0' + stage % 10; p += 3;- *p++ = ':'; *p++ = ' ';- while (*what && p < buf + 94) *p++ = *what++;- *p = 0;- logs(buf);- if (stop >= 1000) /* sub-stage ids: stop exactly there */- return (long)stage == stop;- return (long)stage >= stop && stage < 900;+ return 0;}/*@@ -754,44 +723,32 @@ static char *put_dec(char *p, unsigned long v)return p;}+static void put_str(char **p, const char *s) { while (*s) *(*p)++ = *s++; }+static void put_hex(char **p, unsigned long v) { for (int i = 44; i >= 0; i -= 4) *(*p)++ = "0123456789abcdef"[(v >> i) & 15]; }++/* XNU's counters (enum linux64_counter) every 2 s for the first 3 minutes, then every 20 s */static int monitor_fn(void *arg){- static const char *const names[] = { "idleloop", "machine_idle", "cpu_idle", "host_idle", "invoke",- "-", "stage", "rtclock" };+ static const struct { int i; const char *name; } dec[] = {+ { LINUX64_CTR_IDLE_THREAD, " idle_thread=" }, { LINUX64_CTR_MACHINE_IDLE, " machine_idle=" },+ { LINUX64_CTR_CPU_IDLE, " cpu_idle=" }, { LINUX64_CTR_HOST_IDLE, " host_idle=" }, { LINUX64_CTR_SWITCHES, " switches=" },+ { LINUX64_CTR_LAST_CALL, " last_call=" }, { LINUX64_CTR_RTCLOCK, " rtclock=" }, { LINUX64_CTR_EL0_EXC, " el0exc=" },+ }, hex[] = {+ { LINUX64_CTR_EL0_ESR, " esr=0x" }, { LINUX64_CTR_EL0_FAR, " far=0x" }, { LINUX64_CTR_EL0_PC, " pc=0x" },+ { LINUX64_CTR_BAD_ESR, " bad_esr=0x" }, { LINUX64_CTR_THREAD, " thread=0x" },+ };int lines = 0;+ unsigned long ticks = 0;(void)arg;while (!fki_thread_should_stop()) {fki_msleep(2000);- /* every 2 s for the first 3 minutes, then every 20 s */- static unsigned long ticks;if (!xnu_dbg || (lines >= 90 && (++ticks % 10) != 0))continue;char buf[420]; char *p = buf;- const char *h = "xnu: monitor";- while (*h) *p++ = *h++;- for (int i = 0; i < 8; i++) {- if (i == 5) continue;- *p++ = ' ';- for (const char *n = names[i]; *n; n++) *p++ = *n;- *p++ = '=';- p = put_dec(p, xnu_dbg[i]);- }- h = " el0exc=";- while (*h) *p++ = *h++;- p = put_dec(p, xnu_dbg[10]);- h = " kfaults=";- while (*h) *p++ = *h++;- p = put_dec(p, kfaults);- {- static const char *const k[] = { " esr=0x", " far=0x", " pc=0x", " bad_esr=0x", " step=0x" };- for (int j = 0; j < 5; j++) {- for (h = k[j]; *h; h++) *p++ = *h;- for (int i = 44; i >= 0; i -= 4) *p++ = "0123456789abcdef"[(xnu_dbg[11 + j] >> i) & 15];- }- }- h = " thread=0x";- while (*h) *p++ = *h++;- for (int i = 44; i >= 0; i -= 4) *p++ = "0123456789abcdef"[(xnu_dbg[9] >> i) & 15];+ put_str(&p, "xnu: monitor");+ for (unsigned i = 0; i < sizeof(dec) / sizeof(dec[0]); i++) { put_str(&p, dec[i].name); p = put_dec(p, xnu_dbg[dec[i].i]); }+ put_str(&p, " kfaults="); p = put_dec(p, kfaults);+ for (unsigned i = 0; i < sizeof(hex) / sizeof(hex[0]); i++) { put_str(&p, hex[i].name); put_hex(&p, xnu_dbg[hex[i].i]); }*p = 0;logs(buf);lines++;diff --git a/xnu-patches/0001-linux64-machine-layer.patch b/xnu-patches/0001-linux64-machine-layer.patchnew file mode 100644index 0000000..1181c19--- /dev/null+++ b/xnu-patches/0001-linux64-machine-layer.patch@@ -0,0 +1,2138 @@+The LINUX64 machine layer: XNU hosted inside a Linux kernel by xnu.ko.++The CPU, MMU and exceptions are Linux's: XNU runs at EL1 on Linux's page tables (its kernel L1 entries installed by the+host), with hardware interrupts masked and a virtual interrupt flag; exceptions are taken in Linux's vectors and handed+back (kernel faults to linux64_kernel_fault, user space through linux64_el0_run/linux64_el0_exception). Idle, timers,+the console, printf/kprintf, panics and failed asserts go to the host; entropy comes from the host until corecrypto+registers. Every hosted path is behind `if (linux64_hook)`: the same kernel still boots on hardware.++The interface to the host is linux64/linux64_abi.h (shared with xnu.ko) and linux64/linux64.h, copied into+EXTERNAL_HEADERS/linux64 from xnu-patches/include by scripts/vm-xnu-rebuild.sh.++diff --git a/bsd/dev/arm64/sysctl.c b/bsd/dev/arm64/sysctl.c+index f380ae5..7db22a8 100644+--- a/bsd/dev/arm64/sysctl.c++++ b/bsd/dev/arm64/sysctl.c+@@ -303,7 +303,7 @@ static int+ virtual_address_size SYSCTL_HANDLER_ARGS+ {+ #pragma unused(arg1, arg2, oidp)+- int return_value = 64 - T0SZ_BOOT;++ int return_value = 64 - T0SZ_HW; /* LINUX64: the user address width (pmap_user_va_bits) */+ return SYSCTL_OUT(req, &return_value, sizeof(return_value));+ }++diff --git a/config/MASTER.arm64.bcm2837 b/config/MASTER.arm64.bcm2837+index 0c52cc6..87d19c7 100644+--- a/config/MASTER.arm64.bcm2837++++ b/config/MASTER.arm64.bcm2837+@@ -33,7 +33,7 @@+ # BSD_RELEASE = [ BSD_BASE no_printf_str no_kprintf_str secure_kernel config_imgsrc_access ]+ # BSD_DEV = [ BSD_BASE config_netboot config_imgsrc_access pgo config_vnguard rosetta BSD_EXTRAS_DEV ]+ # BSD_DEBUG = [ BSD_BASE config_netboot config_imgsrc_access pgo config_vnguard rosetta BSD_EXTRAS_DEBUG ]+-# FILESYS_BASE = [ devfs fifo fs_compression config_protect config_mnt_rootsnap config_triggers config_fse routefs namedstreams config_dataless_files bindfs config_ext_resolver config_firmlinks config_searchfs config_file_leases ]++# FILESYS_BASE = [ devfs fifo fs_compression config_protect config_mnt_rootsnap config_triggers config_fse routefs namedstreams config_dataless_files bindfs config_ext_resolver config_firmlinks config_searchfs config_file_leases config_mount_prebootrecovery ]+ # FILESYS_RELEASE= [ FILESYS_BASE ]+ # FILESYS_DEV = [ FILESYS_BASE fdesc config_union_mounts ]+ # FILESYS_DEBUG = [ FILESYS_BASE fdesc config_union_mounts ]+diff --git a/libkern/crypto/corecrypto_rand.c b/libkern/crypto/corecrypto_rand.c+index d46815b..acea296 100644+--- a/libkern/crypto/corecrypto_rand.c++++ b/libkern/crypto/corecrypto_rand.c+@@ -27,9 +27,19 @@+ */++ #include <libkern/crypto/crypto_internal.h>++#include <linux64/linux64.h>+ #include <corecrypto/ccrng.h>++#include <string.h>+ #include <libkern/crypto/rand.h>+++/*++ * LINUX64 (xnulinux): until the corecrypto kext registers g_crypto_funcs (and on a hosted kernel without it), random++ * bytes come from the host's generator (Linux's get_random_bytes, LINUX64_CALL_RANDOM). A context made before then++ * holds nothing (linux64_rng_ctx_size).++ */++#define linux64_rng_fallback() (g_crypto_funcs == NULL && linux64_hook != 0)++#define linux64_rng_ctx_size (2 * sizeof(uint64_t))+++ int+ cc_rand_generate(void *out, size_t outlen)+ {+@@ -41,6 +51,9 @@ cc_rand_generate(void *out, size_t outlen)+ if (rng_state != NULL) {+ error = ccrng_generate(rng_state, outlen, out);+ }++ } else if (linux64_rng_fallback()) {++ linux64_random(out, outlen);++ error = 0;+ }++ return error;+@@ -58,6 +71,10 @@ crypto_random_generate(+ void *random,+ size_t random_size)+ {++ if (linux64_rng_fallback()) {++ linux64_random(random, random_size);++ return;++ }+ g_crypto_funcs->random_generate_fn(ctx, random, random_size);+ }++@@ -67,12 +84,19 @@ crypto_random_uniform(+ uint64_t bound,+ uint64_t *random)+ {++ if (linux64_rng_fallback()) {++ *random = linux64_random_uniform(bound);++ return;++ }+ g_crypto_funcs->random_uniform_fn(ctx, bound, random);+ }++ size_t+ crypto_random_kmem_ctx_size(void)+ {++ if (linux64_rng_fallback()) {++ return linux64_rng_ctx_size;++ }+ return g_crypto_funcs->random_kmem_ctx_size_fn();+ }++@@ -80,5 +104,9 @@ void+ crypto_random_kmem_init(+ crypto_random_ctx_t ctx)+ {++ if (linux64_rng_fallback()) {++ memset(ctx, 0, linux64_rng_ctx_size);++ return;++ }+ g_crypto_funcs->random_kmem_init_fn(ctx);+ }+diff --git a/osfmk/arm/arm_init.c b/osfmk/arm/arm_init.c+index ac1713e..00fed5d 100644+--- a/osfmk/arm/arm_init.c++++ b/osfmk/arm/arm_init.c+@@ -1,4 +1,5 @@+ #include <kern/boot_progress.h>++#include <linux64/linux64.h>+ /*+ * Copyright (c) 2007-2024 Apple Inc. All rights reserved.+ *+@@ -228,6 +229,13 @@ extern vm_offset_t segLOWESTKC, segHIGHESTKC, segLOWESTROKC, segHIGHESTROKC;+ extern vm_offset_t segLOWESTAuxKC, segHIGHESTAuxKC, segLOWESTROAuxKC, segHIGHESTROAuxKC;+ extern vm_offset_t segLOWESTRXAuxKC, segHIGHESTRXAuxKC, segHIGHESTNLEAuxKC;+++/* LINUX64 (xnulinux): the hosted machine layer's state (linux64/linux64.h), set by xnu.ko before arm_init */++uintptr_t linux64_hook;++unsigned long linux64_tpidr;++uintptr_t linux64_slide;++unsigned int linux64_vint;++unsigned long linux64_dbg[LINUX64_NCOUNTERS];+++ static void+ arm_slide_rebase_and_sign_image(void)+ {+@@ -285,10 +293,14 @@ arm_slide_rebase_and_sign_image(void)+ * using hardcoded kernel link address+ */+ slide = (uintptr_t)k_mh - VM_KERNEL_LINK_ADDRESS;++ if (linux64_hook) {++ /* LINUX64: xnu.ko loaded, slid (load commands too) and signed the image already. */++ slide = linux64_slide;++ }++ /* rebase and sign jops */+ static_kernelcache = &__thread_starts_sect_end[0] != &__thread_starts_sect_start[0];+- if (static_kernelcache) {++ if (static_kernelcache && !linux64_hook) {+ rebase_threaded_starts( &__thread_starts_sect_start[0],+ &__thread_starts_sect_end[0],+ (uintptr_t)k_mh, (uintptr_t)k_mh - slide, slide);+@@ -341,6 +353,14 @@ arm_auxkc_init(void *mh, void *base)+ #endif /* defined(HAS_APPLE_PAC) */+ }+++/* LINUX64: a failed assert() while hosted (see kern/assert.h); the host may end the run. */++void++linux64_assert_report(const char *file, int line, const char *expr)++{++ struct linux64_assert_info a = { file, line, expr };++ linux64_call(LINUX64_CALL_ASSERT, &a);++}+++ /*+ * Routine: arm_init+ * Function: Runs on the boot CPU, once, on entry from iBoot.+diff --git a/osfmk/arm/cpu_data.h b/osfmk/arm/cpu_data.h+index 743117b..9dc298b 100644+--- a/osfmk/arm/cpu_data.h++++ b/osfmk/arm/cpu_data.h+@@ -61,8 +61,9 @@ current_thread_fast(void)+ *+ * and ignores the "attribute const", so do it the "dumb" way.+ */+- unsigned long result;+- __asm__ ("mrs %0, TPIDR_EL1" : "=r" (result));++ /* LINUX64 (xnulinux): TPIDR_EL1 belongs to Linux; the thread pointer lives in memory. */++ extern unsigned long linux64_tpidr;++ unsigned long result = linux64_tpidr;+ return __unsafe_forge_single(thread_t, result);+ #else+ // TPIDRPRW+@@ -100,8 +101,8 @@ current_thread_volatile(void)+ * The mrc used for arm32 should be treated as volatile however.+ */+ #if defined(__arm64__)+- unsigned long result;+- __asm__ volatile ("mrs %0, TPIDR_EL1" : "=r" (result));++ extern unsigned long linux64_tpidr;++ unsigned long result = *(volatile unsigned long *)&linux64_tpidr;+ return __unsafe_forge_single(thread_t, result);+ #else+ // TPIDRPRW+@@ -114,7 +115,16 @@ current_thread_volatile(void)+ static inline vm_offset_t+ exception_stack_pointer(void)+ {+- vm_offset_t result = 0;++ vm_offset_t result = 0, spsel;++ /*++ * LINUX64 (xnulinux): hosted XNU runs on Linux's SP_EL1 stack, and SP_EL0 is++ * Linux's `current`; never flip SPSel. When already on SP_EL1, sp is the answer.++ */++ __asm__ volatile ("mrs %0, SPSel" : "=r" (spsel));++ if (spsel & 1) {++ __asm__ volatile ("mov %0, sp" : "=r" (result));++ return result;++ }+ __asm__ volatile (+ "msr SPSel, #1 \n"+ "mov %0, sp \n"+diff --git a/osfmk/arm/machine_routines_common.c b/osfmk/arm/machine_routines_common.c+index b65f76c..b1ab2a2 100644+--- a/osfmk/arm/machine_routines_common.c++++ b/osfmk/arm/machine_routines_common.c+@@ -27,6 +27,7 @@+ */++ #include <arm/machine_cpu.h>++#include <linux64/linux64.h>+ #include <arm/cpu_internal.h>+ #include <arm/cpuid.h>+ #include <arm/cpuid_internal.h>+@@ -1094,6 +1095,46 @@ ml_set_interrupts_enabled_with_debug(boolean_t enable, boolean_t __unused debug)++ thread = current_thread();+++ {++ /*++ * LINUX64 (xnulinux): XNU runs on its own kernel stacks, where Linux cannot take an interrupt++ * (its entry code treats a foreign stack as overflow). Keep IRQs masked in hardware and track++ * XNU's view in linux64_vint; timer "interrupts" are delivered from cpu_idle.++ */++ if (linux64_hook) {++ boolean_t was = linux64_vint ? TRUE : FALSE;++ if (enable && !was) {++ /*++ * Kernel code that runs long without going to user space or idle never sees a host interrupt++ * (hardware IRQs stay masked in XNU's kernel), which stalls Linux (RCU) and stops XNU's own++ * clock. Where XNU would take a pending interrupt, re-enabling interrupts, let Linux run its++ * interrupts every 2 ms and deliver XNU's timer if it is due, as the IRQ path does.++ */++ static uint64_t linux64_last_kyield;++ uint64_t now = mach_absolute_time();++ if (now - linux64_last_kyield > 48000 && thread->machine.CpuDatap->cpu_int_state == NULL) {++ extern void rtclock_intr(unsigned int);++ cpu_data_t *cdp = thread->machine.CpuDatap;++ linux64_last_kyield = now;++ linux64_call2(LINUX64_CALL_PREEMPTED, 1, 0);++ if (cdp->rtcPop != 0 && cdp->rtcPop != 0xFFFFFFFFFFFFFFFFULL && mach_absolute_time() >= cdp->rtcPop) {++ cdp->cpu_decrementer = -1;++ rtclock_intr(FALSE);++ }++ }++ if (get_preemption_level() == 0) {++ while (thread->machine.CpuDatap->cpu_pending_ast & AST_URGENT) {++ ast_taken_kernel();++ }++ }++ linux64_vint = 1;++ } else if (!enable) {++ linux64_vint = 0;++ }++ return was;++ }++ }+++ state = __builtin_arm_rsr("DAIF");++ if (__improbable(!(state & DAIF_DEBUGF))) {+@@ -1384,6 +1425,12 @@ ml_wait_max_cpus(void)+ {+ assert(lockdown_done);+ lck_mtx_lock(&max_cpus_lock);++ {++ /* LINUX64 (xnulinux): hosted without the CPU kext that calls ml_set_max_cpus(); one CPU, known now. */++ if (linux64_hook) {++ max_cpus_initialized = MAX_CPUS_SET;++ }++ }+ while (max_cpus_initialized != MAX_CPUS_SET) {+ max_cpus_initialized = MAX_CPUS_WAIT;+ lck_mtx_sleep(&max_cpus_lock, LCK_SLEEP_DEFAULT, &max_cpus_initialized, THREAD_UNINT);+diff --git a/osfmk/arm/pmap/pmap.c b/osfmk/arm/pmap/pmap.c+index 79d0bc1..fc50363 100644+--- a/osfmk/arm/pmap/pmap.c++++ b/osfmk/arm/pmap/pmap.c+@@ -327,6 +327,32 @@ const struct page_table_attr * const native_pt_attr = &pmap_pt_attr_16k;+ const struct page_table_attr * const native_pt_attr = &pmap_pt_attr_4k;+ #endif /* !__ARM_16K_PG__ */+++#if !__ARM_16K_PG__ && !ARM_PARAMETERIZED_PMAP++/*++ * LINUX64 (xnulinux): user pmaps of a 4 KiB build walk from level 0 and span the 47 bits TTBR0 runs with (T0SZ_HW), as a macOS++ * userland expects (ThreadSanitizer's shadow, nano malloc and MACH_VM_MAX_ADDRESS all sit above the 39 bits a level-1 root reaches).++ * The kernel pmap keeps pmap_pt_attr_4k (TTBR1, level-1 root).++ */++const struct page_table_attr pmap_pt_attr_4k_user = {++ .pta_level_info = pmap_table_level_info_4k,++ .pta_root_level = PMAP_TT_L0_LEVEL,++ .pta_commpage_level = PMAP_TT_L1_LEVEL,++ .pta_max_level = PMAP_TT_L3_LEVEL,++ .pta_ops = &native_pt_ops,++ .ap_ro = ARM_PTE_AP(AP_RORO),++ .ap_rw = ARM_PTE_AP(AP_RWRW),++ .ap_rona = ARM_PTE_AP(AP_RONA),++ .ap_rwna = ARM_PTE_AP(AP_RWNA),++ .ap_xn = ARM_PTE_PNX | ARM_PTE_NX,++ .ap_x = ARM_PTE_PNX,++ .pta_page_size = 4096,++ .pta_pagezero_size = 4096,++ .pta_page_shift = 12,++ .pta_va_valid_mask = (1ULL << (64 - T0SZ_HW)) - 1,++};++const struct page_table_attr * const user_pt_attr = &pmap_pt_attr_4k_user;++#endif /* !__ARM_16K_PG__ && !ARM_PARAMETERIZED_PMAP */++++ #if DEVELOPMENT || DEBUG+ int vm_footprint_suspend_allowed = 1;+@@ -520,7 +546,7 @@ _Static_assert((ARM64_MAX_OFFSET_DEVICE_LARGE > ARM64_MIN_MAX_ADDRESS) && (ARM64+ _Static_assert((ARM64_MAX_OFFSET_DEVICE_SMALL > ARM64_MIN_MAX_ADDRESS) && (ARM64_MAX_OFFSET_DEVICE_SMALL <= MACH_VM_MAX_ADDRESS),+ "Small device address space size outside allowable range");++-# ifdef XNU_TARGET_OS_OSX++# if defined(XNU_TARGET_OS_OSX) || !__ARM_16K_PG__ /* LINUX64: macOS userland gets the whole 47-bit space by default */+ SECURITY_READ_ONLY_LATE(vm_map_offset_t) arm64_pmap_max_offset_default = MACH_VM_MAX_ADDRESS;+ # else+ SECURITY_READ_ONLY_LATE(vm_map_offset_t) arm64_pmap_max_offset_default = 0x0;+@@ -2983,7 +3009,8 @@ pmap_root_alloc_size(pmap_t pmap)+ const pt_attr_t * const pt_attr = pmap_get_pt_attr(pmap);+ unsigned int root_level = pt_attr_root_level(pt_attr);+ const uint64_t index = pt_attr_va_valid_mask(pt_attr);+- return ((index >> pt_attr_ln_shift(pt_attr, root_level)) + 1) * sizeof(tt_entry_t);++ vm_size_t size = ((index >> pt_attr_ln_shift(pt_attr, root_level)) + 1) * sizeof(tt_entry_t);++ return (size < PMAP_ROOT_ALLOC_SIZE) ? PMAP_ROOT_ALLOC_SIZE : size; /* LINUX64: a level-0 root fills half a page */+ }+++@@ -3108,6 +3135,16 @@ pmap_create_options_internal(+ }++ p->ttep = ml_static_vtop((vm_offset_t)p->tte);++ if (pt_attr_root_level(pmap_get_pt_attr(p)) == PMAP_TT_L0_LEVEL) {++ /* LINUX64: the root already is the level-0 table TTBR0 walks from */++ p->hw_tte = p->tte;++ p->hw_ttep = p->ttep;++ for (i = 0; i < tte_index_max; i++) {++ p->tte[i] = ARM_TTE_TYPE_FAULT;++ }++ FLUSH_PTE();++ goto root_ready;++ }+ p->hw_tte = pmap_tt1_allocate(p, pmap_root_alloc_size(p), 0);+ if (!p->hw_tte) {+ pmap_tt1_deallocate(p, p->tte, pmap_root_alloc_size(p), 0);+@@ -3129,6 +3166,7 @@ pmap_create_options_internal(+ p->hw_tte[0] = (p->ttep & ARM_TTE_TABLE_MASK) | ARM_TTE_TYPE_TABLE | ARM_TTE_VALID;++ FLUSH_PTE();++root_ready:++ /*+ * initialize the rest of the structure+@@ -3406,6 +3444,10 @@ pmap_destroy_internal(+++++ if (pmap->hw_tte == pmap->tte) {++ pmap->hw_tte = (tt_entry_t *) NULL; /* LINUX64: a level-0 root is both; free it once, below */++ pmap->hw_ttep = 0;++ }+ if (pmap->tte) {+ pmap_tt1_deallocate(pmap, pmap->tte, pmap_root_alloc_size(pmap), 0);+ pmap->tte = (tt_entry_t *) NULL;+@@ -12980,6 +13022,8 @@ pmap_user_va_bits(pmap_t pmap __unused)+ #if __ARM_MIXED_PAGE_SIZE__+ uint64_t tcr_value = pmap_get_pt_attr(pmap)->pta_tcr_value;+ return 64 - ((tcr_value >> TCR_T0SZ_SHIFT) & TCR_TSZ_MASK);++#elif !__ARM_16K_PG__ && !ARM_PARAMETERIZED_PMAP++ return 64 - T0SZ_HW; /* LINUX64: user pmaps walk from level 0 (pmap_pt_attr_4k_user) */+ #else+ return 64 - T0SZ_BOOT;+ #endif+diff --git a/osfmk/arm/pmap/pmap_pt_geometry.h b/osfmk/arm/pmap/pmap_pt_geometry.h+index fc64830..aaff3fb 100644+--- a/osfmk/arm/pmap/pmap_pt_geometry.h++++ b/osfmk/arm/pmap/pmap_pt_geometry.h+@@ -169,7 +169,14 @@ extern const struct page_table_ops native_pt_ops;+ #else /* ARM_PARAMETERIZED_PMAP */++ /* The page table attributes are fixed (to allow for const propagation) */++#if !__ARM_16K_PG__++/* LINUX64 (xnulinux): user pmaps walk from level 0 over 47 bits, the kernel pmap from level 1 (pmap.c, pmap_pt_attr_4k_user) */++extern const struct page_table_attr * const user_pt_attr;++extern const pmap_t kernel_pmap; /* as in vm/pmap.h, which not every includer of this header has */++#define pmap_get_pt_attr(pmap) ((pmap) == kernel_pmap ? native_pt_attr : user_pt_attr)++#else+ #define pmap_get_pt_attr(pmap) (native_pt_attr)++#endif+ #define pmap_get_pt_ops(pmap) (&native_pt_ops)++ #endif /* ARM_PARAMETERIZED_PMAP */+diff --git a/osfmk/arm/rtclock.c b/osfmk/arm/rtclock.c+index a17a07d..bf9934d 100644+--- a/osfmk/arm/rtclock.c++++ b/osfmk/arm/rtclock.c+@@ -38,6 +38,7 @@+ */++ #include <mach/mach_types.h>++#include <linux64/linux64.h>++ #include <kern/clock.h>+ #include <kern/thread.h>+@@ -327,6 +328,7 @@ rtclock_intr(__unused unsigned int is_user_context)+ struct arm_saved_state * regs;+ unsigned int user_mode;+ uintptr_t pc;++ linux64_count(LINUX64_CTR_RTCLOCK); /* LINUX64: for the host's monitor */++ #if XNU_NATIVE_DWC3_CONSOLE+ extern void unixnu_dwc3_poll(void);+diff --git a/osfmk/arm64/arm_vm_init.c b/osfmk/arm64/arm_vm_init.c+index f7f387e..cd928a3 100644+--- a/osfmk/arm64/arm_vm_init.c++++ b/osfmk/arm64/arm_vm_init.c+@@ -28,6 +28,7 @@++ extern volatile unsigned long long port_crumb; /* port bring-up breadcrumb (link_compat.c) */+ #include <mach_kdp.h>++#include <linux64/linux64.h>+ #include <debug.h>++ #include <kern/assert.h>+@@ -1089,7 +1090,8 @@ arm_vm_page_granular_helper(vm_offset_t start, vm_offset_t _end, vm_offset_t va,+ /*+ * Set the 'guarded page' flag to enable ARM BTI enforcement.+ */+- if (guarded) {++ /* LINUX64: Linux enables SCTLR_EL1.BT1, and this kernel is not built with BTI landing pads. */++ if (guarded && !linux64_hook) {+ ptmp |= ARM_PTE_GP;+ }+ #endif /* BTI_ENFORCED */+@@ -2194,14 +2196,28 @@ arm_vm_init(uint64_t memory_size, boot_args * args)++ arm_vm_physmap_init(args);+ port_crumb = 38;+- set_mmu_ttb_alternate(cpu_ttep & TTBR_BADDR_MASK);++ {++ if (linux64_hook) {++ /*++ * LINUX64 (xnulinux): TTBR1 is Linux's. The host installs XNU's kernel L1 entries++ * (the kernel VA range only) into Linux's top-level L1 table; TTBR0 stays Linux's.++ */++ linux64_call(LINUX64_CALL_KERNEL_TABLES, cpu_tte);++ } else {++ set_mmu_ttb_alternate(cpu_ttep & TTBR_BADDR_MASK);++ }++ }+ port_crumb = 39;++ #if XNU_MONITOR+ ml_enable_monitor();+ #endif++- set_mmu_ttb(invalid_ttep & TTBR_BADDR_MASK);++ {++ if (!linux64_hook) {++ set_mmu_ttb(invalid_ttep & TTBR_BADDR_MASK);++ }++ }++ flush_mmu_tlb();+ port_crumb = 40;+@@ -2267,9 +2283,14 @@ arm_vm_init(uint64_t memory_size, boot_args * args)+ vm_kernel_etext = segTEXTEXECB + segSizeTEXTEXEC;+ vm_kernel_slid_top = vm_slinkedit;+ } else {+- assert(segDATACONSTB == segTEXTB + segSizeTEXT);+- assert(segTEXTEXECB == segDATACONSTB + segSizeDATACONST);+- vm_kernel_etext = segTEXTB + segSizeTEXT + segSizeDATACONST + segSizeTEXTEXEC;++ if (linux64_hook) {++ /* LINUX64: this kernel is linked with the KC segment layout (k27): segments are not adjacent. */++ vm_kernel_etext = segTEXTEXECB + segSizeTEXTEXEC;++ } else {++ assert(segDATACONSTB == segTEXTB + segSizeTEXT);++ assert(segTEXTEXECB == segDATACONSTB + segSizeDATACONST);++ vm_kernel_etext = segTEXTB + segSizeTEXT + segSizeDATACONST + segSizeTEXTEXEC;++ }+ vm_kernel_slid_top = vm_prelink_einfo;+ }++diff --git a/osfmk/arm64/asm.h b/osfmk/arm64/asm.h+index 84deb3f..767b8f8 100644+--- a/osfmk/arm64/asm.h++++ b/osfmk/arm64/asm.h+@@ -135,7 +135,8 @@+ .endmacro++ .macro READ_THREAD+- mrs $0, TPIDR_EL1++ adrp $0, _linux64_tpidr@PAGE++ ldr $0, [$0, _linux64_tpidr@PAGEOFF]+ .endmacro++ .macro BRANCH_EXTERN+diff --git a/osfmk/arm64/cpu.c b/osfmk/arm64/cpu.c+index d10d7a1..956867d 100644+--- a/osfmk/arm64/cpu.c++++ b/osfmk/arm64/cpu.c+@@ -32,6 +32,7 @@+ */++ #include <pexpert/arm64/board_config.h>++#include <linux64/linux64.h>+ #include <kern/kalloc.h>+ #include <kern/machine.h>+ #include <kern/cpu_number.h>+@@ -100,6 +101,7 @@ extern void __attribute__((noreturn)) arm64_prepare_for_sleep(boolean_t deep_sle+ extern void __attribute__((noreturn)) arm64_prepare_for_sleep(boolean_t deep_sleep);+ #endif+ extern void arm64_force_wfi_clock_gate(void);++extern void rtclock_intr(unsigned int);+ #if defined(APPLETYPHOON)+ // <rdar://problem/15827409>+ extern void typhoon_prepare_for_wfi(void);+@@ -430,6 +432,11 @@ wfe_to_deadline_or_interrupt(uint32_t cid, uint64_t wfe_deadline, cpu_data_t *cd+ * another core/cluster in a powergated state.+ * Hence, optionally unmask IRQs+FIQs across WFE.+ */++ {++ if (linux64_hook) {++ unmask = false; /* LINUX64: never unmask hardware IRQs while hosted */++ }++ }+ if (unmask) {+ /* Latch SW IRQ+FIQ counter prior to unmasking+ * interrupts.+@@ -494,6 +501,35 @@ wfe_to_deadline_or_interrupt(uint32_t cid, uint64_t wfe_deadline, cpu_data_t *cd+ return ipending || (nirqc != irqc);+ }+++/*++ * LINUX64 (xnulinux): hosted, idle goes straight to the host, which runs Linux until XNU's next timer deadline and++ * comes back; the due timer is then delivered here as its interrupt would be. No WFE/WFI and no timer interrupt of++ * XNU's own apply (idle_enable stays FALSE without the CPU kext: cpu_machine_init never runs).++ */++static void++linux64_cpu_idle(cpu_data_t *cpu_data_ptr)++{++ uint64_t now = mach_absolute_time();++ uint64_t deadline = cpu_data_ptr->rtcPop;++++ linux64_count(LINUX64_CTR_CPU_IDLE);++ if (deadline == 0 || deadline == EndOfAllTime || deadline < now) {++ deadline = now + 24000; /* about 1 ms: check the run queue again */++ }++#if LINUX64_DEBUG++ if (++linux64_dbg[LINUX64_CTR_HOST_IDLE] % 150000 == 0) { /* every two to three minutes of idle */++ linux64_dump_threads(); /* who is blocked, and where */++ }++#else++ linux64_count(LINUX64_CTR_HOST_IDLE);++#endif++ linux64_call2(LINUX64_CALL_IDLE, (unsigned long)deadline, 0);++ cpu_data_ptr->cpu_decrementer = -1;++ rtclock_intr(FALSE);++ ClearIdlePop(TRUE);++ cpu_idle_exit(FALSE);++}+++ /*+ * Routine: cpu_idle+ * Function:+@@ -506,6 +542,9 @@ cpu_idle(void)+ uint64_t new_idle_timeout_ticks = 0x0ULL, lastPop;+ bool idle_disallowed = false;+++ if (linux64_hook) {++ linux64_cpu_idle(cpu_data_ptr);++ }+ if (__improbable((!idle_enable))) {+ idle_disallowed = true;+ os_atomic_inc(&virt_idle_disallowed[0], relaxed);+diff --git a/osfmk/arm64/cswitch.s b/osfmk/arm64/cswitch.s+index a191eb3..062cd5f 100644+--- a/osfmk/arm64/cswitch.s++++ b/osfmk/arm64/cswitch.s+@@ -185,7 +185,8 @@+ * arg2 - Scratch register+ */+ .macro set_thread_registers+- msr TPIDR_EL1, $0 // Write new thread pointer to TPIDR_EL1++ adrp $1, _linux64_tpidr@PAGE // LINUX64: thread pointer lives in memory, not TPIDR_EL1++ str $0, [$1, _linux64_tpidr@PAGEOFF]+ ldr $1, [$0, ACT_CPUDATAP]+ str $0, [$1, CPU_ACTIVE_THREAD]++@@ -333,7 +334,8 @@ LEXT(machine_load_context)++ LEXT(Call_continuation)+ ARM64_PROLOG+- mrs x4, TPIDR_EL1 // Get the current thread pointer++ adrp x4, _linux64_tpidr@PAGE++ ldr x4, [x4, _linux64_tpidr@PAGEOFF] // Get the current thread pointer++ /* ARM64_TODO arm loads the kstack top instead of arg4. What should we use? */+ LOAD_KERN_STACK_TOP dst=x5, src=x4, tmp=x6+@@ -359,7 +361,8 @@ LEXT(Call_continuation)+ #else+ blr x20 // Branch to the continuation+ #endif+- mrs x0, TPIDR_EL1 // Get the current thread pointer++ adrp x0, _linux64_tpidr@PAGE++ ldr x0, [x0, _linux64_tpidr@PAGEOFF] // Get the current thread pointer+ b EXT(thread_terminate) // Kill the thread+++@@ -394,7 +397,8 @@ Lswitch_threads:++ LEXT(Shutdown_context)+ ARM64_PROLOG+- mrs x10, TPIDR_EL1 // Get thread pointer++ adrp x10, _linux64_tpidr@PAGE++ ldr x10, [x10, _linux64_tpidr@PAGEOFF] // Get thread pointer+ LOAD_KERN_STACK_TOP dst=x11, src=x10, tmp=x12 // Get the top of the kernel stack+ save_general_registers x11, 12+ msr DAIFSet, #(DAIFSC_STANDARD_DISABLE) // Disable interrupts+@@ -412,7 +416,8 @@ LEXT(Shutdown_context)++ LEXT(Idle_context)+ ARM64_PROLOG+- mrs x0, TPIDR_EL1 // Get thread pointer++ adrp x0, _linux64_tpidr@PAGE++ ldr x0, [x0, _linux64_tpidr@PAGEOFF] // Get thread pointer+ LOAD_KERN_STACK_TOP dst=x1, src=x0, tmp=x2 // Get the top of the kernel stack+ save_general_registers x1, 2+ LOAD_INT_STACK_THREAD dst=x2, src=x0, tmp=x1+@@ -429,7 +434,8 @@ LEXT(Idle_context)++ LEXT(Idle_load_context)+ ARM64_PROLOG+- mrs x0, TPIDR_EL1 // Get thread pointer++ adrp x0, _linux64_tpidr@PAGE++ ldr x0, [x0, _linux64_tpidr@PAGEOFF] // Get thread pointer+ LOAD_KERN_STACK_TOP dst=x1, src=x0, tmp=x2 // Get the top of the kernel stack+ load_general_registers x1, 2+ set_process_dependent_keys_and_sync_context x0, x1, x2, x3, w4+@@ -444,3 +450,199 @@ LEXT(machine_set_current_thread)+++ /* vim: set ts=4: */++++/*++ * LINUX64 (xnulinux): user space while hosted. linux64_el0_run(ss) enters EL0 with the user state in ss++ * (IRQs stay masked at EL0), on this CPU, with VBAR_EL1 pointing at linux64_el0_vectors and SP_EL0 holding the++ * user sp; Linux's vectors and its `current` (SP_EL0) are kept in linux64_el0_save. An exception from EL0 builds a++ * register frame on the thread's kernel stack, puts Linux's VBAR and SP_EL0 back and calls++ * linux64_el0_exception(frame) (sleh.c), which hands it to sleh_synchronous and returns to user space again.++ */++ .data++ .align 3++ .globl EXT(linux64_el0_save)++LEXT(linux64_el0_save)++ .quad 0, 0, 0, 0 // Linux's SP_EL0 (current), VBAR_EL1, x18 (its shadow call stack), SCTLR_EL1++++ .text++ .align 2++ .globl EXT(linux64_el0_run)++LEXT(linux64_el0_run)++ ARM64_PROLOG++ adrp x9, EXT(linux64_el0_save)@page++ add x9, x9, EXT(linux64_el0_save)@pageoff++ mrs x10, SP_EL0++ str x10, [x9, #0]++ mrs x10, VBAR_EL1++ str x10, [x9, #8]++ str x18, [x9, #16]++ mrs x10, SCTLR_EL1++ str x10, [x9, #24]++ adrp x10, EXT(linux64_el0_vectors)@page++ add x10, x10, EXT(linux64_el0_vectors)@pageoff++ msr VBAR_EL1, x10++ ldr x10, [x0, SS64_SP]++ msr SP_EL0, x10++ ldr x10, [x0, SS64_PC]++ msr ELR_EL1, x10++ ldr w10, [x0, SS64_CPSR]++ orr w10, w10, #0x40 // FIQ stays masked at EL0 while hosted; a (Linux) IRQ preempts user code++ msr SPSR_EL1, x10++ // the user's NEON/FP state (arm_context_t ns, right after ss): upcalls may let Linux schedule, which reuses the registers++ add x9, x0, NS64_Q0++ ldp q0, q1, [x9, #0]++ ldp q2, q3, [x9, #32]++ ldp q4, q5, [x9, #64]++ ldp q6, q7, [x9, #96]++ ldp q8, q9, [x9, #128]++ ldp q10, q11, [x9, #160]++ ldp q12, q13, [x9, #192]++ ldp q14, q15, [x9, #224]++ ldp q16, q17, [x9, #256]++ ldp q18, q19, [x9, #288]++ ldp q20, q21, [x9, #320]++ ldp q22, q23, [x9, #352]++ ldp q24, q25, [x9, #384]++ ldp q26, q27, [x9, #416]++ ldp q28, q29, [x9, #448]++ ldp q30, q31, [x9, #480]++ ldr w10, [x9, #512]++ msr FPSR, x10++ ldr w10, [x9, #516]++ msr FPCR, x10++ // the next exception from EL0 starts from the top of this thread's kernel stack++ adrp x11, _linux64_tpidr@PAGE++ ldr x11, [x11, _linux64_tpidr@PAGEOFF]++ LOAD_KERN_STACK_TOP dst=x12, src=x11, tmp=x13++ mov sp, x12++ /*++ * x1: JOP off for this thread (arm64, not arm64e): EnIA (31) and EnDA (27) off at EL0. Only now, after the last++ * kernel pointer authentication above (LOAD_KERN_STACK_TOP authenticates; with EnDA off it would trap to brk).++ */++ cbz x1, 1f++ mrs x10, SCTLR_EL1++ mov x11, #((1 << 31) | (1 << 27))++ bic x10, x10, x11++ msr SCTLR_EL1, x10++1:++ isb++ add x30, x0, SS64_X0++ ldp x2, x3, [x30, #16]++ ldp x4, x5, [x30, #32]++ ldp x6, x7, [x30, #48]++ ldp x8, x9, [x30, #64]++ ldp x10, x11, [x30, #80]++ ldp x12, x13, [x30, #96]++ ldp x14, x15, [x30, #112]++ ldp x16, x17, [x30, #128]++ ldp x18, x19, [x30, #144]++ ldp x20, x21, [x30, #160]++ ldp x22, x23, [x30, #176]++ ldp x24, x25, [x30, #192]++ ldp x26, x27, [x30, #208]++ ldp x28, x29, [x30, #224]++ ldp x0, x1, [x30, #0]++ ldr x30, [x30, #240]++ eret++++ .text++ .align 11++ .globl EXT(linux64_el0_vectors)++LEXT(linux64_el0_vectors)++ .rept 8 // current EL (SP0, SPx): not expected while at EL0++ b Llinux64_el0_bad++ .align 7++ .endr++ b Llinux64_el0_entry // lower EL, AArch64: sync++ .align 7++ b Llinux64_el0_irq // IRQ: the host's interrupt arrived while user code ran++ .align 7++ .rept 2 // FIQ, SError++ b Llinux64_el0_entry++ .align 7++ .endr++ .rept 4 // lower EL, AArch32++ b .++ .align 7++ .endr++++Llinux64_el0_bad: // note it for the monitor (linux64_dbg[14] = ESR) and stop here++ adrp x9, _linux64_dbg@PAGE++ add x9, x9, _linux64_dbg@PAGEOFF++ mrs x10, ESR_EL1++ str x10, [x9, #112]++ b .++++Llinux64_el0_irq: // as an exception, with ESR = ~0 (LINUX64_EL0_ESR_IRQ: no ESR has bits 63:32 set)++ sub sp, sp, #(36 * 8 + 528)++ stp x0, x1, [sp, #0]++ mov x1, #1++ b Llinux64_el0_common++Llinux64_el0_entry:++ sub sp, sp, #(36 * 8 + 528)++ stp x0, x1, [sp, #0]++ mov x1, #0++Llinux64_el0_common:++ stp x2, x3, [sp, #16]++ stp x4, x5, [sp, #32]++ stp x6, x7, [sp, #48]++ stp x8, x9, [sp, #64]++ stp x10, x11, [sp, #80]++ stp x12, x13, [sp, #96]++ stp x14, x15, [sp, #112]++ stp x16, x17, [sp, #128]++ stp x18, x19, [sp, #144]++ stp x20, x21, [sp, #160]++ stp x22, x23, [sp, #176]++ stp x24, x25, [sp, #192]++ stp x26, x27, [sp, #208]++ stp x28, x29, [sp, #224]++ str x30, [sp, #240]++ mrs x0, SP_EL0++ str x0, [sp, #248]++ mrs x0, ELR_EL1++ str x0, [sp, #256]++ mrs x0, SPSR_EL1++ str x0, [sp, #264]++ mrs x0, ESR_EL1++ cbz x1, 1f++ mov x0, #-1++1:++ str x0, [sp, #272]++ mrs x0, FAR_EL1++ str x0, [sp, #280]++ add x9, sp, #288 // the user's NEON/FP registers (linux64_el0_exception keeps them in uNeon)++ stp q0, q1, [x9, #0]++ stp q2, q3, [x9, #32]++ stp q4, q5, [x9, #64]++ stp q6, q7, [x9, #96]++ stp q8, q9, [x9, #128]++ stp q10, q11, [x9, #160]++ stp q12, q13, [x9, #192]++ stp q14, q15, [x9, #224]++ stp q16, q17, [x9, #256]++ stp q18, q19, [x9, #288]++ stp q20, q21, [x9, #320]++ stp q22, q23, [x9, #352]++ stp q24, q25, [x9, #384]++ stp q26, q27, [x9, #416]++ stp q28, q29, [x9, #448]++ stp q30, q31, [x9, #480]++ mrs x10, FPSR++ str w10, [x9, #512]++ mrs x10, FPCR++ str w10, [x9, #516]++ adrp x9, EXT(linux64_el0_save)@page++ add x9, x9, EXT(linux64_el0_save)@pageoff++ ldr x10, [x9, #0]++ msr SP_EL0, x10++ ldr x10, [x9, #8]++ msr VBAR_EL1, x10++ ldr x18, [x9, #16] // the host's x18 again (user code owns x18 at EL0)++ ldr x10, [x9, #24] // SCTLR_EL1 as the kernels expect it (EnIA/EnDA back on)++ msr SCTLR_EL1, x10++ isb++ mov x0, sp++ mov x29, xzr++ bl EXT(linux64_el0_exception)++ b .+diff --git a/osfmk/arm64/exception_asm.h b/osfmk/arm64/exception_asm.h+index b0772a7..ea5e679 100644+--- a/osfmk/arm64/exception_asm.h++++ b/osfmk/arm64/exception_asm.h+@@ -299,7 +299,8 @@ Lspill_registers_skip_elr_far_\@:+ * SP0 is expected to already be selected. Clobbers x1 and tmp.+ */+ .macro SWITCH_TO_INT_STACK tmp+- mrs x1, TPIDR_EL1++ adrp x1, _linux64_tpidr@PAGE++ ldr x1, [x1, _linux64_tpidr@PAGEOFF]+ LOAD_INT_STACK_THREAD dst=x1, src=x1, tmp=\tmp+ mov sp, x1 // Set the stack pointer to the interrupt stack+ .endmacro+diff --git a/osfmk/arm64/locore.s b/osfmk/arm64/locore.s+index 13d2819..d71ba86 100644+--- a/osfmk/arm64/locore.s++++ b/osfmk/arm64/locore.s+@@ -144,7 +144,8 @@++ #endif /* DEVELOPMENT || DEBUG */+ #if CONFIG_XNUPOST+- mrs x0, TPIDR_EL1++ adrp x0, _linux64_tpidr@PAGE++ ldr x0, [x0, _linux64_tpidr@PAGEOFF]+ /*+ * If hitting this with a null TPIDR, it's likely that this was an unexpected+ * exception in early boot rather than an expected one as a part of a test.+@@ -257,7 +258,8 @@ Lbegin_panic_lockdown_continue_\@:+ * Find the kernelcache table for the exception vectors by accessing+ * the per-CPU data.+ */+- mrs x18, TPIDR_EL1++ adrp x18, _linux64_tpidr@PAGE++ ldr x18, [x18, _linux64_tpidr@PAGEOFF]+ ldr x18, [x18, ACT_CPUDATAP]+ ldr x18, [x18, CPU_EXC_VECTORS]++@@ -354,7 +356,8 @@ Lbegin_panic_lockdown_continue_\@:+ str x1, [x0, #24] // spsr+ mrs x1, SP_EL0+ str x1, [x0, #32] // sp+- mrs x1, TPIDR_EL1++ adrp x1, _linux64_tpidr@PAGE++ ldr x1, [x1, _linux64_tpidr@PAGEOFF]+ str x1, [x0, #40] // tpidr (thread pointer)++ /* Get timestamp */+@@ -396,7 +399,8 @@ Lbegin_panic_lockdown_continue_\@:+ cmp x1, x2 // If we have a data abort, we need to+ b.ne Lvalid_stack_\@ // ...validate the stack pointer+ mrs x0, SP_EL0 // Get SP_EL0+- mrs x1, TPIDR_EL1 // Get thread pointer++ adrp x1, _linux64_tpidr@PAGE++ ldr x1, [x1, _linux64_tpidr@PAGEOFF] // Get thread pointer+ /*+ * Check for either a NULL TPIDR or a NULL kernel stack, both of which+ * are expected in early boot, but will cause recursive faults if not+@@ -490,7 +494,8 @@ Lvalid_stack_\@:+ * Clobbers NZCV.+ */+ .macro CHECK_EXCEPTION_STACK invalid_stack_label+- mrs x18, TPIDR_EL1 // Get thread pointer++ adrp x18, _linux64_tpidr@PAGE++ ldr x18, [x18, _linux64_tpidr@PAGEOFF] // Get thread pointer+ /*+ * The thread pointer might be invalid during early boot.+ * Return zero in x18 to indicate that we failed to execute the check.+@@ -631,7 +636,8 @@ Lel0_serror_vector_64:+ // SWITCH_TO_INT_STACK requires a clobberable tmp register, but at this+ // point in the exception vector we can't spare the extra GPR. Instead note+ // that EL1_SP0_VECTOR ends with x0 == sp and use this to unclobber x0.+- mrs x1, TPIDR_EL1++ adrp x1, _linux64_tpidr@PAGE++ ldr x1, [x1, _linux64_tpidr@PAGEOFF]+ LOAD_INT_STACK_THREAD dst=x1, src=x1, tmp=x0+ mov x0, sp+ mov sp, x1+@@ -701,7 +707,8 @@ Lkernel_stack_valid:+ * Slow path: check/map redzone.+ * Skip redzone mapping if preemption is disabled (e.g. possibly in SPTM context)+ */+- mrs x0, TPIDR_EL1++ adrp x0, _linux64_tpidr@PAGE++ ldr x0, [x0, _linux64_tpidr@PAGEOFF]+ ldr w0, [x0, ACT_PREEMPT_CNT]+ cbnz w0, Lel1_sp0_redzone_done_\@ // Preemption disabled, skip redzone++@@ -822,7 +829,8 @@ Lel1_sp1_synchronous_vector_continue:+ *+ * Ensure that we actually performed the check on a legitmate value now.+ */+- mrs x0, TPIDR_EL1++ adrp x0, _linux64_tpidr@PAGE++ ldr x0, [x0, _linux64_tpidr@PAGEOFF]+ LOAD_EXCEP_STACK_THREAD dst=x0, src=x0, tmp=x1+ cmp x0, x18+ /* If we aren't equal, something is very wrong and we should lockdown. */+@@ -875,7 +883,8 @@ LEXT(el1_sp1_synchronous_vector_long_spill_failed)+ /* Macro returns x0=1 if it performed a simulated lockdown */+ cbz x0, 0f+ /* This was a test; return to fault handler so they can fixup the system. */+- mrs x0, TPIDR_EL1++ adrp x0, _linux64_tpidr@PAGE++ ldr x0, [x0, _linux64_tpidr@PAGEOFF]+ ldr x16, [x0, TH_EXPECTED_FAULT_HANDLER]+ #if __has_feature(ptrauth_calls)+ movk x17, #TH_EXPECTED_FAULT_HANDLER_DIVERSIFIER+@@ -944,7 +953,8 @@ el1_sp1_serror_vector_long:+ #if __ARM_KERNEL_PROTECT__+ mov x18, #0 // Zero x18 to avoid leaking data to user SS+ #endif+- mrs x0, TPIDR_EL1 // Load the thread register++ adrp x0, _linux64_tpidr@PAGE++ ldr x0, [x0, _linux64_tpidr@PAGEOFF] // Load the thread register+ LOAD_USER_PCB dst=x0, src=x0, tmp=x1 // Load the user context pointer+ mrs x1, SP_EL0 // Load the user stack pointer+ str x1, [x0, SS64_SP] // Store the user stack pointer in the user PCB+@@ -953,7 +963,8 @@ el1_sp1_serror_vector_long:+ msr SPSel, #0 // Switch to SP0+ stp x0, x1, [sp, SS64_X0] // Save x0, x1 to the user PCB+ stp x2, x3, [sp, SS64_X2] // Save x2, x3 to the user PCB+- mrs x1, TPIDR_EL1 // Load the thread register++ adrp x1, _linux64_tpidr@PAGE++ ldr x1, [x1, _linux64_tpidr@PAGEOFF] // Load the thread register++++@@ -1321,7 +1332,8 @@ Lblocked_user_sync_exception:+ * sp - Interrupt stack for the current CPU+ */+ .macro BEGIN_INTERRUPT_HANDLER+- mrs x22, TPIDR_EL1++ adrp x22, _linux64_tpidr@PAGE++ ldr x22, [x22, _linux64_tpidr@PAGEOFF]+ ldr x23, [x22, ACT_CPUDATAP] // Get current cpu+ /* Update IRQ count; CPU_STAT_IRQ.* is required to be accurate for the WFE idle sequence */+ ldr w1, [x23, CPU_STAT_IRQ]+@@ -1529,7 +1541,8 @@ LEXT(fleh_check_map_redzone)+ PUSH_FRAME++ /* Check if we have a valid thread */+- mrs x1, TPIDR_EL1++ adrp x1, _linux64_tpidr@PAGE++ ldr x1, [x1, _linux64_tpidr@PAGEOFF]+ cbz x1, Lfleh_check_map_redzone_skip++ /* Get kernel stack bottom */+@@ -1671,7 +1684,8 @@ Lfleh_synchronous_sp1_skip_panic_lockdown:+ * still on init_thread) and we try to panic(), we'll end up in an infinite+ * nested exception, so just stop here instead to preserve the call stack.+ */+- mrs x9, TPIDR_EL1++ adrp x9, _linux64_tpidr@PAGE++ ldr x9, [x9, _linux64_tpidr@PAGEOFF]+ cbz x9, 0f+ ldr x9, [x9, TH_KSTACKPTR]+ cbz x9, 0f+@@ -1742,7 +1756,8 @@ LEXT(xnu_return_to_gl2)+ * If thread->txm_thread_stack is set, we need to tell SPTM dispatch to+ * resume the TXM thread in x0.+ */+- mrs x8, TPIDR_EL1++ adrp x8, _linux64_tpidr@PAGE++ ldr x8, [x8, _linux64_tpidr@PAGEOFF]+ ldr x8, [x8, TH_TXM_THREAD_STACK]+ cbz x8, 1f+ mov x0, x8+@@ -1756,7 +1771,8 @@ LEXT(xnu_return_to_gl2)+ * we need to tell SPTM dispatch to resume the SK thread.+ */+ 1:+- mrs x8, TPIDR_EL1++ adrp x8, _linux64_tpidr@PAGE++ ldr x8, [x8, _linux64_tpidr@PAGEOFF]+ ldr x9, [x8, TH_EXCLAVES_INTSTATE]+ and x9, x9, TH_EXCLAVES_EXECUTION+ cbz x9, 1f+@@ -1783,7 +1799,8 @@ LEXT(return_to_kernel)+ UNWIND_PROLOGUE+ RETURN_TO_KERNEL_UNWIND+ tbnz w0, #DAIF_IRQF_SHIFT, exception_return // Skip AST check if IRQ disabled+- mrs x3, TPIDR_EL1 // Load thread pointer++ adrp x3, _linux64_tpidr@PAGE++ ldr x3, [x3, _linux64_tpidr@PAGEOFF] // Load thread pointer+ ldr w1, [x3, ACT_PREEMPT_CNT] // Load preemption count+ msr DAIFSet, #DAIFSC_ALL // Disable exceptions+ cbnz x1, exception_return_unint_tpidr_x3 // If preemption disabled, skip AST check+@@ -1802,6 +1819,12 @@ LEXT(return_to_kernel)+ .globl EXT(thread_bootstrap_return)+ LEXT(thread_bootstrap_return)+ ARM64_PROLOG++ // LINUX64 (xnulinux): hosted, a new user thread's first return goes through C (user space is not hosted yet)++ adrp x9, _linux64_hook@PAGE++ ldr x9, [x9, _linux64_hook@PAGEOFF]++ cbz x9, 1f++ b EXT(linux64_thread_bootstrap_return)++1:+ #if CONFIG_DTRACE+ bl EXT(dtrace_thread_bootstrap)+ #endif+@@ -1816,7 +1839,14 @@ LEXT(thread_bootstrap_return)+ .globl EXT(arm64_thread_exception_return)+ LEXT(arm64_thread_exception_return)+ ARM64_PROLOG+- mrs x0, TPIDR_EL1++ // LINUX64 (xnulinux): hosted, a return to user space goes through C (user space is not hosted yet)++ adrp x9, _linux64_hook@PAGE++ ldr x9, [x9, _linux64_hook@PAGEOFF]++ cbz x9, 1f++ b EXT(linux64_thread_bootstrap_return)++1:++ adrp x0, _linux64_tpidr@PAGE++ ldr x0, [x0, _linux64_tpidr@PAGEOFF]+ LOAD_USER_PCB dst=x21, src=x0, tmp=x28+ mov x28, xzr++@@ -1835,7 +1865,8 @@ check_user_asts:+ bl EXT(__asan_handle_no_return)+ POP_FRAME_WITHOUT_LR+ #endif /* KASAN_TBI */+- mrs x3, TPIDR_EL1 // Load thread pointer++ adrp x3, _linux64_tpidr@PAGE++ ldr x3, [x3, _linux64_tpidr@PAGEOFF] // Load thread pointer++ movn w2, #0+ str w2, [x3, TH_IOTIER_OVERRIDE] // Reset IO tier override to -1 before returning to user+@@ -1927,7 +1958,8 @@ no_asts:+ PUSH_FRAME+ bl EXT(arm_debug_set) // Establish thread debug state in live regs+ POP_FRAME_WITHOUT_LR+- mrs x3, TPIDR_EL1 // Reload thread pointer++ adrp x3, _linux64_tpidr@PAGE++ ldr x3, [x3, _linux64_tpidr@PAGEOFF] // Reload thread pointer+ ldr x4, [x3, ACT_CPUDATAP] // Reload CPU data pointer+ L_skip_user_set_debug_state:++@@ -1937,7 +1969,8 @@ L_skip_user_set_debug_state:+ exception_return:+ msr DAIFSet, #DAIFSC_ALL // Disable exceptions+ exception_return_unint:+- mrs x3, TPIDR_EL1 // Load thread pointer++ adrp x3, _linux64_tpidr@PAGE++ ldr x3, [x3, _linux64_tpidr@PAGEOFF] // Load thread pointer+ exception_return_unint_tpidr_x3:+ mov sp, x21 // Reload the pcb pointer++@@ -2006,7 +2039,9 @@ Lexception_return_restore_registers:+ // SPSR_EL1.M != EL0: no SME state to restore+ bne Lno_sme_saved_state++- mrs x3, TPIDR_EL1++ adrp x3, _linux64_tpidr@PAGE++++ ldr x3, [x3, _linux64_tpidr@PAGEOFF]+ add x3, x3, ACT_UMATRIX_HDR+ ldr x2, [x3]+ cbz x2, Lno_sme_saved_state+@@ -2071,7 +2106,8 @@ Lno_gcr_mask_el0_reset:+ #endif /* HAS_MTE */+ // If sync_on_cswitch and ERET is not a CSE, issue an ISB now. Unconditionally clear the+ // sync_on_cswitch flag.+- mrs x1, TPIDR_EL1++ adrp x1, _linux64_tpidr@PAGE++ ldr x1, [x1, _linux64_tpidr@PAGEOFF]+ ldr x1, [x1, ACT_CPUDATAP]++ // Redefined for backporting.+@@ -2095,7 +2131,8 @@ Lno_gcr_mask_el0_reset:+ mrs x2, SPSR_EL1+ tst x2, #(PSR64_MODE_EL_MASK)+ b.ne 1f+- mrs x2, TPIDR_EL1++ adrp x2, _linux64_tpidr@PAGE++ ldr x2, [x2, _linux64_tpidr@PAGEOFF]+ ldr w2, [x2, TH_ARM_MACHINE_FLAGS]+ tbz w2, #ARM_MACHINE_THREAD_DISABLE_USER_JOP_SHIFT, 1f+ mrs x2, SCTLR_EL1+@@ -2184,7 +2221,8 @@ user_take_ast:+ .text+ .align 2+ preempt_underflow:+- mrs x0, TPIDR_EL1++ adrp x0, _linux64_tpidr@PAGE++ ldr x0, [x0, _linux64_tpidr@PAGEOFF]+ str x0, [sp, #-16]! // We'll print thread pointer+ adr x0, L_underflow_str // Format string+ CALL_EXTERN panic // Game over+@@ -2197,7 +2235,8 @@ L_underflow_str:+ .text+ .align 2+ preempt_count_notzero:+- mrs x0, TPIDR_EL1++ adrp x0, _linux64_tpidr@PAGE++ ldr x0, [x0, _linux64_tpidr@PAGEOFF]+ str x0, [sp, #-16]! // We'll print thread pointer+ ldr w0, [x0, ACT_PREEMPT_CNT]+ str w0, [sp, #8]+@@ -2457,7 +2496,8 @@ ppl_exit:+ add x15, x15, x10, lsl #32++ /* Load the preemption count. */+- mrs x10, TPIDR_EL1++ adrp x10, _linux64_tpidr@PAGE++ ldr x10, [x10, _linux64_tpidr@PAGEOFF]+ ldr w12, [x10, ACT_PREEMPT_CNT]++ /* Detect underflow */+@@ -2493,7 +2533,8 @@ Lno_preempt_underflow:+ mov w12, #0++ /* Restore the thread pointer into x10. */+- mrs x10, TPIDR_EL1++ adrp x10, _linux64_tpidr@PAGE++ ldr x10, [x10, _linux64_tpidr@PAGEOFF]++ Lskip_collect_measurement:+ #endif /* SCHED_HYGIENE_DEBUG */+@@ -2743,7 +2784,8 @@ LEXT(_sptm_pre_entry_hook)+ stp x6, x7, [sp, #0x30]++ /* Increase the preemption count. */+- mrs x9, TPIDR_EL1++ adrp x9, _linux64_tpidr@PAGE++ ldr x9, [x9, _linux64_tpidr@PAGEOFF]+ cbz x9, Lskip_preemption_check_sptmhook+ ldr w10, [x9, ACT_PREEMPT_CNT]+ add w10, w10, #1+@@ -2803,7 +2845,8 @@ LEXT(_sptm_post_exit_hook)+++ /* Load the preemption count. */+- mrs x0, TPIDR_EL1++ adrp x0, _linux64_tpidr@PAGE++ ldr x0, [x0, _linux64_tpidr@PAGEOFF]+ cbz x0, Lsptm_skip_ast_taken_sptmhook+ ldr w12, [x0, ACT_PREEMPT_CNT]++@@ -2834,7 +2877,8 @@ Lno_preempt_underflow_sptmhook:+ mov w12, #0++ /* Restore x0 as the thread pointer */+- mrs x0, TPIDR_EL1++ adrp x0, _linux64_tpidr@PAGE++ ldr x0, [x0, _linux64_tpidr@PAGEOFF]++ Lskip_collect_measurement_sptmhook:+ #endif /* SCHED_HYGIENE_DEBUG */+@@ -2916,7 +2960,9 @@ LEXT(panic_lockdown_record_debug_data)+ mov x1, sp+ str x1, [x0, #PANIC_LOCKDOWN_INITIATOR_STATE_INITIATOR_SP]++- mrs x1, TPIDR_EL1++ adrp x1, _linux64_tpidr@PAGE++++ ldr x1, [x1, _linux64_tpidr@PAGEOFF]+ str x1, [x0, #PANIC_LOCKDOWN_INITIATOR_STATE_INITIATOR_TPIDR]++ mrs x1, MPIDR_EL1+diff --git a/osfmk/arm64/machine_routines.c b/osfmk/arm64/machine_routines.c+index f456377..5bde82d 100644+--- a/osfmk/arm64/machine_routines.c++++ b/osfmk/arm64/machine_routines.c+@@ -27,6 +27,7 @@+ */++ #include <arm64/machine_machdep.h>++#include <linux64/linux64.h>+ #include <arm64/proc_reg.h>+ #include <arm/machine_cpu.h>+ #include <arm/cpu_internal.h>+@@ -385,6 +386,7 @@ wfe_process_recommendation(void)+ void+ machine_idle(void)+ {++ linux64_count(LINUX64_CTR_MACHINE_IDLE); /* LINUX64: for the host's monitor */+ /* Interrupts are expected to be masked on entry or re-entry via+ * Idle_load_context()+ */+@@ -400,6 +402,13 @@ machine_idle(void)+ */+ Idle_context();+ }++ {++ /* LINUX64 (xnulinux): hosted, hardware IRQs stay masked; only the virtual flag changes. */++ if (linux64_hook) {++ linux64_vint = 1;++ return;++ }++ }+ __builtin_arm_wsr("DAIFClr", DAIFSC_STANDARD_DISABLE);+ }++@@ -441,6 +450,12 @@ ml_get_interrupts_enabled(void)+ {+ uint64_t value;+++ {++ /* LINUX64: interrupts are virtual while hosted (see ml_set_interrupts_enabled_with_debug). */++ if (linux64_hook) {++ return linux64_vint ? TRUE : FALSE;++ }++ }+ MRS(value, "DAIF");+ if ((value & DAIF_STANDARD_DISABLE) == DAIF_STANDARD_DISABLE) {+ return FALSE;+@@ -2529,6 +2544,12 @@ ml_set_decrementer(uint32_t dec_value)+ }+ }+++ {++ /* LINUX64 (xnulinux): the generic timer is Linux's; cpu_idle hands the deadline to the host. */++ if (linux64_hook) {++ return;++ }++ }+ if (cdp->cpu_set_decrementer_func) {+ cdp->cpu_set_decrementer_func((uint32_t)counter_value);+ } else {+diff --git a/osfmk/arm64/machine_routines_asm.s b/osfmk/arm64/machine_routines_asm.s+index 96650a0..8986f4f 100644+--- a/osfmk/arm64/machine_routines_asm.s++++ b/osfmk/arm64/machine_routines_asm.s+@@ -95,7 +95,8 @@ Lcre_start_\@:+++ .macro LOAD_CPU_JOP_KEY dst, tmp+- mrs \tmp, TPIDR_EL1++ adrp \tmp, _linux64_tpidr@PAGE++ ldr \tmp, [\tmp, _linux64_tpidr@PAGEOFF]+ ldr \tmp, [\tmp, ACT_CPUDATAP]+ ldr \dst, [\tmp, CPU_JOP_KEY]+ .endmacro+@@ -1748,6 +1749,11 @@ LEXT(arm64_force_wfi_clock_gate)+ LEXT(arm64_replace_bootstack)+ ARM64_STACK_PROLOG+ PUSH_FRAME++ // LINUX64 (xnulinux): hosted, SP_EL1 is Linux's kernel stack and SP_EL0 is Linux's `current`;++ // XNU must not touch either. Its exception stacks are unused while hosted.++ adrp x9, _linux64_hook@PAGE++ ldr x9, [x9, _linux64_hook@PAGEOFF]++ cbnz x9, Lreplace_bootstack_hosted+ // Set the exception stack pointer+ ldr x0, [x0, CPU_EXCEPSTACK_TOP]+ mrs x4, DAIF // Load current DAIF; use x4 as pinst may trash x1-x3+@@ -1763,6 +1769,7 @@ LEXT(arm64_replace_bootstack)+ mov sp, x0+ msr SPSel, #0+ msr DAIF, x4 // Restore interrupt state++Lreplace_bootstack_hosted:+ POP_FRAME+ ARM64_STACK_EPILOG EXT(arm64_replace_bootstack)++diff --git a/osfmk/arm64/pac_asm.h b/osfmk/arm64/pac_asm.h+index d211433..dc247da 100644+--- a/osfmk/arm64/pac_asm.h++++ b/osfmk/arm64/pac_asm.h+@@ -216,7 +216,8 @@+ * Expects interrupts to be disabled.+ */+ .macro PACGA_IRG_RESEED x, y, z+- mrs \x, TPIDR_EL1++ adrp \x, _linux64_tpidr@PAGE++ ldr \x, [\x, _linux64_tpidr@PAGEOFF]+ ldr \x, [\x, ACT_CPUDATAP]++ // No need for atomic - These are per CPU and interrupts are disabled+diff --git a/osfmk/arm64/sleh.c b/osfmk/arm64/sleh.c+index d8f1b19..9e0422b 100644+--- a/osfmk/arm64/sleh.c++++ b/osfmk/arm64/sleh.c+@@ -1,4 +1,5 @@+ #include <kern/boot_progress.h>++#include <linux64/linux64.h>+ /*+ * Copyright (c) 2012-2023 Apple Inc. All rights reserved.+ *+@@ -78,6 +79,7 @@+ #if CONFIG_TELEMETRY+ #include <kern/telemetry.h>+ #include <kern/trap_telemetry.h>++#include <kern/recount.h>+ #endif++ #include <prng/entropy.h>+@@ -3646,3 +3648,210 @@ sleh_panic_lockdown_should_initiate_el1_sp0_sync(uint64_t esr, uint64_t elr,+ }+ __SECURITY_STACK_DISALLOWED_POP+ #endif /* CONFIG_SPTM */++++/*++ * LINUX64 (xnulinux): a data or instruction abort on an XNU kernel address, taken in Linux's vectors and forwarded by++ * the host (xnu.ko through FKI). Does what handle_kernel_abort does for a kernel-map fault: the pmap fast path for++ * permission/access-flag faults, then vm_fault. Returns KERN_SUCCESS when the access can be retried.++ */++kern_return_t linux64_kernel_fault(uint64_t far, uint64_t esr);++kern_return_t++linux64_kernel_fault(uint64_t far, uint64_t esr)++{++ uint32_t ec = (uint32_t)((esr >> 26) & 0x3f);++ fault_status_t fault_code = (fault_status_t)(esr & 0x3f);++ vm_prot_t fault_type = VM_PROT_READ;++ kern_return_t result = KERN_FAILURE;++++ if (ec == 0x21) { /* instruction abort, current EL */++ fault_type = VM_PROT_READ | VM_PROT_EXECUTE;++ } else if (ec == 0x25) { /* data abort, current EL */++ if (esr & (1u << 6)) { /* WnR */++ fault_type = VM_PROT_READ | VM_PROT_WRITE;++ }++ } else {++ return KERN_FAILURE;++ }++ if (!is_vm_fault(fault_code)) {++ return KERN_FAILURE;++ }++ /* a kernel address faults on the kernel map; a user one (copyio) on the current thread's map */++ vm_map_t map = kernel_map;++ if (!VM_KERNEL_ADDRESS(far)) {++ thread_t thread = current_thread();++ if (thread == THREAD_NULL || thread->map == VM_MAP_NULL || thread->map == kernel_map) {++ return KERN_FAILURE;++ }++ map = thread->map;++ }++ kern_return_t ffr = KERN_FAILURE;++ if (!is_translation_fault(fault_code)) {++ ffr = arm_fast_fault(map->pmap, far, fault_type, (fault_code == FSC_ACCESS_FLAG_FAULT_L3), FALSE);++ }++ kern_return_t kr = ffr == KERN_SUCCESS ? KERN_SUCCESS :++ vm_fault(map, far, fault_type, FALSE, VM_KERN_MEMORY_NONE, THREAD_UNINT, NULL, 0);++ if (ffr == KERN_SUCCESS) {++ return KERN_SUCCESS;++ }++ return kr;++}++++/*++ * LINUX64 (xnulinux): a kernel fault vm_fault could not resolve, taken inside a copyin/copyout routine: the pc its++ * copyio recovery entry returns through (the routine then returns an error; x0 = EFAULT), 0 when pc has none.++ */++uint64_t linux64_kernel_fault_recover(uint64_t pc, uint64_t far, uint64_t esr);++uint64_t++linux64_kernel_fault_recover(uint64_t pc, uint64_t far, uint64_t esr)++{++ struct copyio_recovery_entry *e = find_copyio_recovery_entry(pc);++ thread_t thread = current_thread();++++ if (e == NULL) {++ return 0;++ }++ if (thread != THREAD_NULL) {++ thread->machine.recover_esr = esr;++ thread->machine.recover_far = far;++ }++ return (uint64_t)copyio_recover_table + (uint64_t)e->cre_recovery;++}++++/*++ * LINUX64 (xnulinux): the first return of a new user thread (thread_bootstrap_return) while hosted. The pending ASTs++ * run as on the way to user space (for the first BSD thread: bsdinit_task, which execs launchd), and the thread enters++ * user space through linux64_el0_run (the host is told where user space starts the first time).++ */++void linux64_thread_bootstrap_return(void) __attribute__((noreturn));++/* boot-arg linux64_trace=1 logs every EL0 exception, and system calls with their paths and results */++static int linux64_trace_level = -1;++static inline int++linux64_tracing(void)++{++ if (__improbable(linux64_trace_level < 0)) {++ int v = 0;++ if (!PE_parse_boot_argn("linux64_trace", &v, sizeof(v))) {++ v = 0;++ }++ linux64_trace_level = v;++ }++ return linux64_trace_level;++}++++static thread_t linux64_svc_thread; /* linux64_trace: the thread whose system call is in flight, and its number */++static long long linux64_svc_num;++++void++linux64_thread_bootstrap_return(void)++{++ thread_t thread = current_thread();++++ static int reported;++++ (void)ml_set_interrupts_enabled(FALSE);++ ast_taken_user();++ if (linux64_svc_thread == thread && linux64_tracing()) { /* what the system call returned (C set: x0 is errno) */++ linux64_svc_thread = NULL;++ extern int proc_selfpid(void);++ kprintf("linux64: [%d] svc %lld -> x0 0x%llx x1 0x%llx%s\n", proc_selfpid(), linux64_svc_num, get_saved_state_reg(thread->machine.upcb, 0),++ get_saved_state_reg(thread->machine.upcb, 1), (get_saved_state_cpsr(thread->machine.upcb) & PSR64_C) ? " (error)" : "");++ }++ if (reported++ == 0) {++ linux64_call2(LINUX64_CALL_USER_ENTER, get_saved_state_pc(thread->machine.upcb), 0);++ }++ /*++ * An arm64 (not arm64e) process runs the arm64e system libraries with JOP off: Apple hardware disables the user++ * IA/DA keys for it; hosted, user code runs with SCTLR_EL1.EnIA/EnDA cleared (linux64_el0_run puts them back on++ * the next exception), or a blraaz on one of its unsigned function pointers fails (EXC_ARM_PAC_FAIL).++ */++#if PRECISE_USER_KERNEL_TIME++ recount_enter_user(); /* user time vs system time, as locore's return to user space does */++#endif++ linux64_el0_run(thread->machine.upcb, (thread->machine.arm_machine_flags & ARM_MACHINE_THREAD_DISABLE_USER_JOP) != 0);++}++++/* LINUX64: the registers linux64_el0_vectors saved for an exception taken at EL0 (cswitch.s) */++struct linux64_el0_frame {++ uint64_t x[31];++ uint64_t sp, pc, cpsr, esr, far;++ uint64_t neon[64]; /* q0..q31 */++ uint32_t fpsr, fpcr;++ uint64_t pad;++};++_Static_assert(__builtin_offsetof(struct linux64_el0_frame, neon) == 288, "linux64_el0_frame layout");++_Static_assert(sizeof(struct linux64_el0_frame) == 36 * 8 + 528, "linux64_el0_frame size");++++void linux64_el0_exception(struct linux64_el0_frame *f) __attribute__((noreturn));++void++linux64_el0_exception(struct linux64_el0_frame *f)++{++ thread_t thread = current_thread();++ arm_saved_state_t *ss = thread->machine.upcb;++++#if PRECISE_USER_KERNEL_TIME++ recount_leave_user(); /* interrupts are still off here, as on locore's exception entry */++#endif++ linux64_count(LINUX64_CTR_EL0_EXC); /* for the host's monitor: EL0 exceptions, the last one's ESR, FAR, PC */++ linux64_dbg[LINUX64_CTR_EL0_ESR] = f->esr;++ linux64_dbg[LINUX64_CTR_EL0_FAR] = f->far;++ linux64_dbg[LINUX64_CTR_EL0_PC] = f->pc;++ if (linux64_tracing()) kprintf("linux64: EL0 exception esr 0x%llx far 0x%llx pc 0x%llx x16 %lld ttbr0 0x%llx ttep 0x%llx\n", f->esr, f->far, f->pc, f->x[16],++ __builtin_arm_rsr64("TTBR0_EL1"), (uint64_t)thread->map->pmap->ttep);++ for (unsigned i = 0; i < 29; i++) {++ set_saved_state_reg(ss, i, f->x[i]);++ }++ set_saved_state_fp(ss, f->x[29]);++ set_saved_state_lr(ss, f->x[30]);++ set_saved_state_sp(ss, f->sp);++ set_saved_state_pc(ss, f->pc);++ /* EL0 runs with IRQ/FIQ masked while hosted (no XNU interrupts at EL0 yet); XNU must see the user's own PSTATE,++ * or its abort path takes the user fault for one from a non-interruptible context */++ set_saved_state_cpsr(ss, (uint32_t)f->cpsr & ~(uint32_t)0x3c0);++ {++ arm_neon_saved_state_t *ns = thread->machine.uNeon;++ memcpy(&ns->ns_64.v.q[0], f->neon, sizeof(f->neon));++ ns->ns_64.fpsr = f->fpsr;++ ns->ns_64.fpcr = f->fpcr;++ }++ if (f->esr == ~0ULL) {++ /*++ * A host IRQ arrived while user code ran (EL0 runs with IRQs unmasked). Let Linux take it and run what it++ * must (its tick, RCU, other tasks), then deliver XNU's timer "interrupt" if it is due, as sleh_irq++ * would: the quantum expiry it may raise preempts this thread on the way back to user space.++ */++ cpu_data_t *cdp = getCpuDatap();++ (void)ml_set_interrupts_enabled(FALSE); /* XNU's (virtual) interrupt state: off, as in sleh_irq */++ linux64_call2(LINUX64_CALL_PREEMPTED, 0, 0);++ if (cdp->rtcPop != EndOfAllTime && cdp->rtcPop != 0 && mach_absolute_time() >= cdp->rtcPop) {++ cdp->cpu_int_state = ss;++ cdp->cpu_stat.irq_ex_cnt++;++ cdp->cpu_decrementer = -1;++ rtclock_intr(TRUE);++ cdp->cpu_int_state = NULL;++ }++ thread_exception_return();++ }++ if (ESR_EC(f->esr) == ESR_EC_SVC_64 && linux64_tracing()) {++ long long num = (long long)f->x[16];++ linux64_svc_thread = thread;++ linux64_svc_num = num;++ if (num == 202 && f->x[1] > 0 && f->x[1] <= 8) { /* sysctl: the MIB and this thread's kernel stack */++ int mib[8] = {0};++ if (copyin((user_addr_t)f->x[0], mib, f->x[1] * sizeof(int)) == 0) {++ kprintf("linux64: svc 202 mib %d.%d.%d.%d (len %llu) kstack 0x%llx\n", mib[0], mib[1], mib[2], mib[3], f->x[1],++ (uint64_t)thread->kernel_stack);++ }++ }++ if (num == 59 || num == 244 || num == 5 || num == 398 || num == 463 || num == 33 || num == 338 || num == 340 || num == 466 || num == 469) {++ char path[128];++ size_t len = 0;++ uint64_t ua = (num == 463 || num == 466 || num == 469 || num == 244) ? f->x[1] : f->x[0];++ if (copyinstr((user_addr_t)ua, path, sizeof(path), &len) == 0) {++ extern int proc_selfpid(void);++ kprintf("linux64: [%d] svc %lld path \"%s\"\n", proc_selfpid(), num, path);++ }++ }++ }++ sleh_synchronous(thread->machine.contextData, f->esr, (vm_offset_t)f->far, false);++ thread_exception_return();++}+diff --git a/osfmk/arm64/status.c b/osfmk/arm64/status.c+index c615764..72ec4a7 100644+--- a/osfmk/arm64/status.c++++ b/osfmk/arm64/status.c+@@ -2103,16 +2103,17 @@ machine_thread_state_initialize(thread_t thread)+ "mov x3, #0" "\n"+ "mov x4, #0" "\n"+ "mov x5, #0" "\n"++ "mrs x10, SPSel" "\n"+ "msr SPSel, #1" "\n"+ VERIFY_USER_THREAD_STATE_INSTR "\n"+ "mov x6, lr" "\n"+ "bl _ml_sign_thread_state" "\n"+- "msr SPSel, #0" "\n"++ "msr SPSel, x10" "\n"+ "mov lr, x6" "\n"+ :+ : [iss] "r"(thread->machine.upcb), [usr] "r"(thread->machine.upcb->ss_64.cpsr),+ VERIFY_USER_THREAD_STATE_INPUTS+- : "x0", "x1", "x2", "x3", "x4", "x5", "x6", "x17"++ : "x0", "x1", "x2", "x3", "x4", "x5", "x6", "x10", "x17"+ );+ ml_pac_safe_interrupts_restore(intr);+ }+diff --git a/osfmk/console/serial_console.c b/osfmk/console/serial_console.c+index 11d9eb4..8c59a02 100644+--- a/osfmk/console/serial_console.c++++ b/osfmk/console/serial_console.c+@@ -1,4 +1,5 @@+ #include <kern/boot_progress.h>++#include <linux64/linux64.h>+ /*+ * Copyright (c) 2000-2020 Apple, Inc. All rights reserved.+ *+@@ -532,6 +533,13 @@ console_resume()+ void+ console_write(char *str, int size)+ {++ {++ /* LINUX64 (xnulinux): hosted XNU's console (/dev/console, km) goes to the host (stage 996: bytes, length). */++ if (linux64_hook && str && size > 0) {++ linux64_call2(LINUX64_CALL_CONSOLE_WRITE, (unsigned long)str, (unsigned long)size);++ return;++ }++ }+ if (disableConsoleOutput) {+ return;+ }+diff --git a/osfmk/console/serial_general.c b/osfmk/console/serial_general.c+index b1ca47a..d878442 100644+--- a/osfmk/console/serial_general.c++++ b/osfmk/console/serial_general.c+@@ -33,6 +33,7 @@+ */++ #include <kern/spl.h>++#include <linux64/linux64.h>+ #include <mach/std_types.h>+ #include <types.h>+ #include <kern/thread.h>+@@ -48,13 +49,32 @@ SECURITY_READ_ONLY_LATE(unsigned int) serialmode;+ * characters that have been typed.+ */+++/*++ * LINUX64 (xnulinux): a hosted XNU's console input comes from the host (LINUX64_CALL_CONSOLE_READ), polled by the serial keyboard thread like a UART.++ */++static int++linux64_cons_getc(void)++{++ static char buf[64];++ static int n, i;++++ if (i < n) {++ return (unsigned char)buf[i++];++ }++ struct linux64_buf_req q = { .buf = buf, .len = sizeof(buf), .result = 0 };++ linux64_call(LINUX64_CALL_CONSOLE_READ, &q);++ n = q.result > 0 ? (int)q.result : 0;++ i = 0;++ return n ? (unsigned char)buf[i++] : -1;++}+++ void+ serial_keyboard_init(void)+ {+ kern_return_t result;+ thread_t thread;++- if (!(serialmode & SERIALMODE_INPUT)) { /* Leave if we do not want a serial console */++ if (!(serialmode & SERIALMODE_INPUT) && !linux64_hook) { /* Leave if we do not want a serial console */+ return;+ }++@@ -82,7 +102,7 @@ serial_keyboard_poll(void)+ uint64_t next;++ while (1) {+- chr = _serial_getc(false); /* Get a character if there is one */++ chr = linux64_hook ? linux64_cons_getc() : _serial_getc(false); /* Get a character if there is one */+ if (chr < 0) { /* The serial buffer is empty */+ break;+ }+diff --git a/osfmk/kern/assert.h b/osfmk/kern/assert.h+index 4224c9d..4a1fe94 100644+--- a/osfmk/kern/assert.h++++ b/osfmk/kern/assert.h+@@ -193,9 +193,28 @@ STATIC_IF_KEY_DECLARE_TRUE(mach_assert);+ #define mach_assert_enabled_expr(ex) \+ (mach_assert_enabled() || __builtin_constant_p(!(ex)))+++#if defined(XNU_KERNEL_PRIVATE) && defined(__arm64__)++/*++ * LINUX64 (xnulinux): hosted inside Linux there is no XNU exception vector for the assert brk, so a++ * failed assert() is reported to the host, which decides whether XNU continues or the run ends.++ */++#ifdef __cplusplus++extern "C" {++#endif++extern unsigned long linux64_hook;++extern void linux64_assert_report(const char *file, int line, const char *expr);++#ifdef __cplusplus++}++#endif++#define assert(ex) \++ (mach_assert_enabled_expr(ex) && !(ex) \++ ? (linux64_hook ? linux64_assert_report(__FILE_NAME__, __LINE__, #ex) \++ : (void)mach_assert_abort(#ex)) : (void)0)++#else+ #define assert(ex) \+ (mach_assert_enabled_expr(ex) && !(ex) \+ ? (void)mach_assert_abort(#ex) : (void)0)++#endif++ #define assertf(ex, fmt, args...) ({ \+ if (mach_assert_enabled_expr(ex) && __builtin_expect(!(ex), 0L)) { \+diff --git a/osfmk/kern/backtrace.c b/osfmk/kern/backtrace.c+index 77044be..2c195af 100644+--- a/osfmk/kern/backtrace.c++++ b/osfmk/kern/backtrace.c+@@ -48,7 +48,7 @@+ #include <arm64/mte.h>+ #endif // HAS_MTE++-#if __x86_64__++#if __x86_64__ || __arm64__ /* LINUX64: hosted, a kernel stack also has frames in Linux's text, beyond 32 bits of stext */+ static void+ _backtrace_packed_out_of_reach(void)+ {+@@ -58,7 +58,7 @@ _backtrace_packed_out_of_reach(void)+ //+ // This is an Intel only issue.+ }+-#endif // __x86_64__++#endif // __x86_64__ || __arm64__++ // Pack an address according to a particular packing format.+ static size_t+@@ -74,7 +74,7 @@ _backtrace_pack_addr(backtrace_pack_t packing, uint8_t *dst, size_t dst_size,+ case BTP_KERN_OFFSET_32:;+ uintptr_t addr_delta = addr - vm_kernel_stext;+ int32_t addr_packed = (int32_t)addr_delta;+-#if __x86_64__++#if __x86_64__ || __arm64__+ if ((uintptr_t)(int32_t)addr_delta != addr_delta) {+ addr = (vm_offset_t)&_backtrace_packed_out_of_reach;+ addr_delta = addr - vm_kernel_stext;+diff --git a/osfmk/kern/debug.c b/osfmk/kern/debug.c+index 0eae1f6..8d31f1d 100644+--- a/osfmk/kern/debug.c++++ b/osfmk/kern/debug.c+@@ -55,6 +55,7 @@+ */++ #include <mach_assert.h>++#include <linux64/linux64.h>+ #include <mach_kdp.h>+ #include <kdp/kdp.h>+ #include <kdp/kdp_core.h>+@@ -754,7 +755,20 @@ DebuggerTrapWithState(debugger_op db_op, const char *db_message, const char *db_+ * The rest of the cores are halted by IPI if possible; if that+ * fails it will fall back to dbgwrap.+ */++ {++ /*++ * LINUX64 (xnulinux): the hosted kernel's exceptions are taken by Linux, which does not hand XNU this trap++ * (an uncategorized exception), so a stackshot (spindump, tailspin, sysdiagnose) ended the whole run. The++ * stackshot needs no trap frame (handle_debugger_trap takes it with do_stackshot(NULL)) and there is one CPU:++ * call the handler here, as the trap would (kdp_trap -> handle_debugger_trap).++ */++ if (linux64_hook && db_op == DBOP_STACKSHOT) {++ handle_debugger_trap(0, 0, 0, NULL); /* the exception number only matters for breakpoints */++ goto trapped;++ }++ }+ TRAP_DEBUGGER;++trapped:++ ret = CPUDEBUGGERRET;++@@ -1253,6 +1267,26 @@ panic_trap_to_debugger(const char *panic_format_str, va_list *panic_args, unsign+ {+ #pragma clang diagnostic pop+++#if defined(__arm64__)++ {++ /* LINUX64 (xnulinux): report the panic to the host (see arm_init.c). */++ if (linux64_hook) {++ /* the formatted message when there are arguments (the format string alone otherwise) */++ static char linux64_panic_buf[512];++ const char *msg = panic_format_str;++ if (panic_args != NULL && panic_format_str != NULL) {++ extern int vsnprintf(char *, size_t, const char *, va_list);++ va_list ap;++ va_copy(ap, *panic_args);++ vsnprintf(linux64_panic_buf, sizeof(linux64_panic_buf), panic_format_str, ap);++ va_end(ap);++ msg = linux64_panic_buf;++ }++ linux64_call2(LINUX64_CALL_PANIC, (unsigned long)msg, panic_caller);++ }++ }++#endif+++ #if defined(__x86_64__) && (DEVELOPMENT || DEBUG)+ read_lbr();+ #endif+diff --git a/osfmk/kern/kext_alloc.c b/osfmk/kern/kext_alloc.c+index 119c6c7..f3e43a6 100644+--- a/osfmk/kern/kext_alloc.c++++ b/osfmk/kern/kext_alloc.c+@@ -26,6 +26,7 @@+ * @APPLE_OSREFERENCE_LICENSE_HEADER_END@+ */+ #include <kern/assert.h>++#include <linux64/linux64.h>+ #include <kern/debug.h>+ #include <kern/kext_alloc.h>+ #include <kern/misc_protos.h>+@@ -218,6 +219,18 @@ check_reachable:+ }+ #endif+++ {++ /*++ * LINUX64 (xnulinux): hosted XNU has no page-fault path of its own yet (Linux takes the abort), so kext++ * memory is wired up front instead of faulted in on first touch.++ */++ if (linux64_hook) {++ kern_return_t wr = vm_map_wire_kernel(g_kext_map, addr, addr + size, VM_PROT_DEFAULT, VM_KERN_MEMORY_KEXT, FALSE);++ if (wr != KERN_SUCCESS) {++ printf("linux64: kext_alloc wire failed %d\n", wr);++ }++ }++ }+ /* Check that the memory is reachable by kernel text */+ if ((addr + size) > kext_alloc_max) {+ kext_free((vm_offset_t)addr, size);+diff --git a/osfmk/kern/link_compat.c b/osfmk/kern/link_compat.c+index e494eab..fc40514 100644+--- a/osfmk/kern/link_compat.c++++ b/osfmk/kern/link_compat.c+@@ -65,3 +65,21 @@ native_verified_block_manifest_sha384(unsigned int device, const char *uuid, uin+ }++ #endif++++/*++ * LINUX64 (xnulinux): macOS 27 kernel functions that 27.2's RTBuddy kext imports and xnu-12377 does not have.++ * The hosted kernel has no coprocessors; both are no-ops.++ */++int os_log_coprocessor_with_handle(void);++int++os_log_coprocessor_with_handle(void)++{++ return 0;++}++++int os_metric_coprocessor(void);++int++os_metric_coprocessor(void)++{++ return 0;++}+diff --git a/osfmk/kern/printf.c b/osfmk/kern/printf.c+index 2fc6931..d581670 100644+--- a/osfmk/kern/printf.c++++ b/osfmk/kern/printf.c+@@ -155,6 +155,7 @@+ */++ #include <debug.h>++#include <linux64/linux64.h>+ #include <mach_kdp.h>+ #include <mach/boolean.h>+ #include <kern/cpu_number.h>+@@ -876,6 +877,20 @@ __printflike(1, 0)+ static int+ vprintf_internal(const char *fmt, va_list ap_in, void *caller)+ {++ {++ /* LINUX64 (xnulinux): hosted XNU prints through the host (dmesg), like kprintf. */++ if (linux64_hook && fmt) {++ extern int vsnprintf(char *, size_t, const char *, va_list);++ char buf[256];++ va_list ap;++ va_copy(ap, ap_in);++ vsnprintf(buf, sizeof(buf), fmt, ap);++ va_end(ap);++ linux64_call(LINUX64_CALL_KPRINTF, buf);++ (void)caller;++ return 0;++ }++ }+ if (fmt) {+ struct console_printbuf_state info_data;++diff --git a/osfmk/kern/sched_prim.c b/osfmk/kern/sched_prim.c+index b2aae03..3e83e72 100644+--- a/osfmk/kern/sched_prim.c++++ b/osfmk/kern/sched_prim.c+@@ -65,6 +65,7 @@+ */++ #include <kern/sched_prim.h>++#include <linux64/linux64.h>++ #if !SCHED_TEST_HARNESS++@@ -3010,6 +3011,7 @@ thread_invoke(++ thread_continue_t continuation = self->continuation;+ void *parameter = self->parameter;++ linux64_count(LINUX64_CTR_SWITCHES); linux64_dbg[LINUX64_CTR_THREAD] = (unsigned long)thread; /* LINUX64: for the host's monitor */++ struct recount_snap snap = { 0 };+ recount_snapshot(&snap);+@@ -6452,6 +6454,7 @@ processor_idle(+ recount_processor_idle(&processor->pr_recount, &snap);++ while (1) {++ linux64_count(LINUX64_CTR_IDLE_THREAD); /* LINUX64: for the host's monitor */+ /*+ * Ensure that updates to my processor and pset state,+ * made by the IPI source processor before sending the IPI,+@@ -9984,3 +9987,46 @@ sysctl_clutch_thread_group_cpu_time_for_thread(__unused thread_t thread,+ #endif /* !SCHED_TEST_HARNESS */++ #endif /* DEVELOPMENT || DEBUG */++++#if LINUX64_DEBUG++/*++ * LINUX64 (xnulinux) debug: print every thread's state, wait event, continuation and a few saved frames.++ * Called from the hosted idle path (single CPU, interrupts off), so the list is walked without its lock.++ */++void++linux64_dump_threads(void)++{++ thread_t t;++ int n = 0;++ extern int proc_pid(struct proc *);++ queue_iterate(&threads, t, thread_t, threads) {++ if (++n > 400) {++ break;++ }++ void *bp = get_bsdthreadtask_info(t);++ if (bp == NULL || proc_pid((struct proc *)bp) == 0) {++ /* the kernel's own threads: only those blocked with a saved stack (not parked on a continuation) */++ if (t->continuation != NULL || t->kernel_stack == 0) {++ continue;++ }++ kprintf("linux64 proc 0 kernel_task\n");++ } else {++ kprintf("linux64 proc %d %s\n", proc_pid((struct proc *)bp), proc_name_address((struct proc *)bp));++ }++ struct arm_kernel_saved_state *ss = (struct arm_kernel_saved_state *)(void *)t->machine.kstackptr;++ uint64_t lr = 0, fp = 0;++ if (ss != NULL && t->kernel_stack != 0) {++ lr = ss->lr | 0xffffff8000000000ULL;++ fp = ss->fp;++ }++ kprintf("linux64 thread %p tid %llu state 0x%x pri %d wait %p cont %p lr 0x%llx\n",++ t, t->thread_id, t->state, t->sched_pri, (void *)t->wait_event, (void *)t->continuation, lr);++ for (int f = 0; f < 14 && fp != 0 && t->kernel_stack != 0 &&++ fp >= t->kernel_stack && fp < t->kernel_stack + kernel_stack_size; f++) {++ uint64_t *frame = (uint64_t *)fp;++ kprintf("linux64 frame 0x%llx\n", frame[1] | 0xffffff8000000000ULL);++ fp = frame[0];++ }++ }++}++#endif /* LINUX64_DEBUG */+diff --git a/osfmk/kern/stack.c b/osfmk/kern/stack.c+index 1111ccf..9bc5118 100644+--- a/osfmk/kern/stack.c++++ b/osfmk/kern/stack.c+@@ -30,6 +30,7 @@+ */++ #include <mach/mach_host.h>++#include <linux64/linux64.h>+ #include <mach/mach_types.h>+ #include <mach/processor_set.h>++@@ -185,6 +186,23 @@ STARTUP(TUNABLES, STARTUP_RANK_MIDDLE, stack_init);+ * block.+ */+++/*++ * LINUX64 (xnulinux): an exception taken on an XNU kernel stack enters Linux's vectors, whose overflow check wants++ * bit THREAD_SHIFT (14) of sp clear, as on Linux's 2*THREAD_SIZE-aligned stacks. Hosted, each stack starts on a++ * 32 KiB boundary: the allocation is 32 KiB aligned and the stack sits 32 KiB above its start (guard pages first,++ * then unused wired pages, then the stack, then the upper guard page).++ */++static inline vm_offset_t++linux64_stack_lead(void)++{++ return linux64_hook ? 0x8000 : ptoa(2);++}++static inline vm_offset_t++linux64_stack_mask(void)++{++ return linux64_hook ? (stack_addr_mask | 0x7fff) : stack_addr_mask;++}+++ static vm_offset_t+ stack_alloc_internal(void)+ {+@@ -218,7 +236,7 @@ stack_alloc_internal(void)+ */++ kernel_memory_allocate(kernel_map, &stack,+- kernel_stack_size + ptoa(3), stack_addr_mask,++ kernel_stack_size + linux64_stack_lead() + ptoa(1), linux64_stack_mask(),+ flags, VM_KERN_MEMORY_STACK);++ /*+@@ -226,7 +244,7 @@ stack_alloc_internal(void)+ * guard pages. Skip past them to get the actual stack base address.+ */++- stack += ptoa(2);++ stack += linux64_stack_lead();+ }+ return stack;+ }+@@ -389,8 +407,8 @@ stack_collect(void)+ stack = (vm_offset_t)vm_map_trunc_page(+ stack,+ VM_MAP_PAGE_MASK(kernel_map));+- stack -= ptoa(2);+- kmem_free(kernel_map, stack, kernel_stack_size + ptoa(3),++ stack -= linux64_stack_lead();++ kmem_free(kernel_map, stack, kernel_stack_size + linux64_stack_lead() + ptoa(1),+ KMF_GUARD_FIRST | KMF_GUARD_LAST | KMF_GUARD_STACK);+ stack = 0;++diff --git a/osfmk/mach/arm/thread_status.h b/osfmk/mach/arm/thread_status.h+index 99971b0..efc6ab8 100644+--- a/osfmk/mach/arm/thread_status.h++++ b/osfmk/mach/arm/thread_status.h+@@ -522,6 +522,7 @@ extern void ml_check_signed_state(const arm_saved_state_t *, uint64_t, uint32_t,+ asm volatile ( \+ "mov x9, lr" "\n" \+ "mov x0, %[iss]" "\n" \++ "mrs x10, SPSel" "\n" \+ "msr SPSel, #1" "\n" \+ "ldp x4, x5, [x0, %[SS64_X16]]" "\n" \+ "ldr x7, [x0, %[SS64_PC]]" "\n" \+@@ -535,7 +536,7 @@ extern void ml_check_signed_state(const arm_saved_state_t *, uint64_t, uint32_t,+ _instr "\n" \+ "bl _ml_sign_thread_state" "\n" \+ "0:" "\n" \+- "msr SPSel, #0" "\n" \++ "msr SPSel, x10" "\n" \+ "mov lr, x9" "\n" \+ : \+ : [iss] "r"(_iss), \+@@ -544,7 +545,7 @@ extern void ml_check_signed_state(const arm_saved_state_t *, uint64_t, uint32_t,+ [SS64_CPSR] "i"(ss64_offsetof(cpsr)), \+ [SS64_LR] "i"(ss64_offsetof(lr)),##__VA_ARGS__ \+ : "x0", "x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", \+- "x9", "x16", "x17" \++ "x9", "x10", "x16", "x17" \+ ); \+ ml_pac_safe_interrupts_restore(_intr); \+ } while (0)+diff --git a/osfmk/mach/arm/vm_param.h b/osfmk/mach/arm/vm_param.h+index bb62cdd..9bea611 100644+--- a/osfmk/mach/arm/vm_param.h++++ b/osfmk/mach/arm/vm_param.h+@@ -149,6 +149,11 @@ extern int PAGE_SHIFT_CONST;+ #undef MACH_VM_MAX_ADDRESS_RAW+ #define MACH_VM_MAX_ADDRESS_RAW 0x00007FFFFE000000ULL+ #endif /* defined(XNU_PLATFORM_iPhoneOS) && EXTENDED_USER_VA_SUPPORT */++#if !__ARM_16K_PG__ && !defined(XNU_PLATFORM_MacOSX)++/* LINUX64 (xnulinux): 4 KiB user pmaps span 47 bits (pmap_pt_attr_4k_user), the macOS layout its userland expects */++#undef MACH_VM_MAX_ADDRESS_RAW++#define MACH_VM_MAX_ADDRESS_RAW 0x00007FFFFE000000ULL++#endif+ /* threshold for allocations to be placed in the large file range */+ #define VM_LARGE_FILE_THRESHOLD (1ULL << 30)+ #define MACH_VM_JUMBO_ADDRESS ((mach_vm_offset_t) 0x0000000FC0000000ULL)+@@ -294,7 +299,7 @@ extern int PAGE_SHIFT_CONST;++ #if XNU_KERNEL_PRIVATE+ #define VM_KERNEL_STRIP_MASK (-1ULL << (64 - T1SZ_BOOT))+-#define VM_USER_STRIP_MASK (-1ULL >> (T0SZ_BOOT))++#define VM_USER_STRIP_MASK (-1ULL >> (T0SZ_HW)) /* LINUX64: user addresses span the width TTBR0 runs with */+ #define _VM_KERNEL_STRIP_PTR(_va) ({((_va) & 1ULL << 55) ? ((_va) | VM_KERNEL_STRIP_MASK) : ((_va) & VM_USER_STRIP_MASK);})+ #else /* XNU_KERNEL_PRIVATE */++diff --git a/osfmk/prng/prng_random.c b/osfmk/prng/prng_random.c+index 44b993c..4ce279b 100644+--- a/osfmk/prng/prng_random.c++++ b/osfmk/prng/prng_random.c+@@ -28,6 +28,7 @@++ extern volatile unsigned long long port_crumb; /* port bring-up breadcrumb (link_compat.c) */+ #include <kern/locks.h>++#include <linux64/linux64.h>+ #include <kern/cpu_number.h>+ #include <libkern/section_keywords.h>+ #include <libkern/crypto/sha2.h>+@@ -368,13 +369,23 @@ random_cpu_init(int cpu)+ panic("random_cpu_init: kernel prng has not been installed");+ }++- prng_funcs.initgen(prng_ctx, cpu);++ if (prng_funcs.initgen != NULL) {++ prng_funcs.initgen(prng_ctx, cpu);++ }+ }++ /* export good random numbers to the rest of the kernel */+ __mockable void+ read_random(void * buffer, u_int numbytes)+ {++ /*++ * LINUX64 (xnulinux): without the corecrypto kext nobody calls register_and_init_prng() and prng_funcs stays++ * zeroed; hosted, the host's generator (Linux's get_random_bytes) stands in.++ */++ if (prng_funcs.generate == NULL && linux64_hook) {++ linux64_random(buffer, numbytes);++ return;++ }+ prng_funcs.refresh(prng_ctx);+ read_random_generate(buffer, numbytes);+ }+@@ -433,7 +444,9 @@ write_random(void * buffer, u_int numbytes)+ memcpy(seed, buffer, numbytes);+ }++- prng_funcs.reseed(prng_ctx, sizeof(seed), seed);++ if (prng_funcs.reseed != NULL) {++ prng_funcs.reseed(prng_ctx, sizeof(seed), seed);++ }+ cc_clear(sizeof(seed), seed);++ return 0;+diff --git a/pexpert/arm/pe_kprintf.c b/pexpert/arm/pe_kprintf.c+index fea9411..cdccb1f 100644+--- a/pexpert/arm/pe_kprintf.c++++ b/pexpert/arm/pe_kprintf.c+@@ -1,4 +1,5 @@+ #include <kern/boot_progress.h>++#include <linux64/linux64.h>+ /*+ * Copyright (c) 2000-2019 Apple Inc. All rights reserved.+ */+@@ -107,6 +108,20 @@ kprintf(const char *fmt, ...)+ boolean_t state;+ void *caller = __builtin_return_address(0);+++ {++ /* LINUX64 (xnulinux): hosted XNU prints through the host (dmesg). */++ if (linux64_hook) {++ extern int vsnprintf(char *, size_t, const char *, va_list);++ char buf[256];++ va_start(listp, fmt);++ vsnprintf(buf, sizeof(buf), fmt, listp);++ va_end(listp);++ linux64_call(LINUX64_CALL_KPRINTF, buf);++ (void)caller;++ return;++ }++ }+++ if (!disable_serial_output && !disable_kprintf_output) {+ va_start(listp, fmt);+ va_copy(listp2, listp);diff --git a/xnu-patches/0001-linux64-stage-hook.patch b/xnu-patches/0001-linux64-stage-hook.patchdeleted file mode 100644index 2fe435c..0000000--- a/xnu-patches/0001-linux64-stage-hook.patch+++ /dev/null@@ -1,4322 +0,0 @@-diff --git a/bsd/conf/files b/bsd/conf/files-index 7a2a873..27843d7 100644---- a/bsd/conf/files-+++ b/bsd/conf/files-@@ -177,6 +177,7 @@ bsd/net/ether_if_module.c optional ether bound-checks- bsd/net/ether_inet_pr_module.c optional ether inet bound-checks- bsd/net/ether_inet6_pr_module.c optional ether inet bound-checks- bsd/net/if_loop.c optional loop bound-checks-+bsd/net/if_linux64.c optional ether- bsd/net/if_mib.c optional networking bound-checks- bsd/net/if_vlan.c optional vlan bound-checks- bsd/net/if_fake.c optional if_fake bound-checks-diff --git a/bsd/dev/arm/systemcalls.c b/bsd/dev/arm/systemcalls.c-index 5a7b717..5c12c8f 100644---- a/bsd/dev/arm/systemcalls.c-+++ b/bsd/dev/arm/systemcalls.c-@@ -132,6 +132,10 @@ unix_syscall(-- uthread->uu_flag |= UT_NOTCANCELPT;- uthread->syscall_code = code;-+ if (__improbable(callp->sy_call == (sy_call_t *)nosys)) { /* LINUX64: who calls a system call this kernel does not have */-+ kprintf("linux64: nosys %d from pid %d %s pc 0x%llx lr 0x%llx\n", code, proc_pid(proc), proc->p_comm,-+ (unsigned long long)get_saved_state_pc(state), (unsigned long long)get_saved_state_lr(state));-+ }-- uthread->uu_rval[0] = 0;--diff --git a/bsd/dev/arm64/sysctl.c b/bsd/dev/arm64/sysctl.c-index f380ae5..7db22a8 100644---- a/bsd/dev/arm64/sysctl.c-+++ b/bsd/dev/arm64/sysctl.c-@@ -303,7 +303,7 @@ static int- virtual_address_size SYSCTL_HANDLER_ARGS- {- #pragma unused(arg1, arg2, oidp)-- int return_value = 64 - T0SZ_BOOT;-+ int return_value = 64 - T0SZ_HW; /* LINUX64: the user address width (pmap_user_va_bits) */- return SYSCTL_OUT(req, &return_value, sizeof(return_value));- }--diff --git a/bsd/dev/memdev.c b/bsd/dev/memdev.c-index d24535d..5c2aafb 100644---- a/bsd/dev/memdev.c-+++ b/bsd/dev/memdev.c-@@ -95,6 +95,7 @@- #include <vm/vm_pager_xnu.h>- #include <mach/memory_object_types.h>- #include <kern/debug.h>-+#include <kern/kalloc.h>-- #include <miscfs/devfs/devfs.h>--@@ -172,6 +173,7 @@ struct mdev {- #define mdInited 0x01 /* This device defined */- #define mdRO 0x02 /* This device is read-only */- #define mdPhys 0x04 /* This device is in physical memory */-+#define mdHost 0x08 /* LINUX64 (xnulinux): backed by a host file, I/O through the host */-- int mdevBMajor = -1;- int mdevCMajor = -1;-@@ -180,6 +182,39 @@ static int mdevioctl(dev_t dev, u_long cmd, caddr_t data, int flag, struct- dev_t mdevadd(int devid, uint64_t base, unsigned int size, int phys);- dev_t mdevlookup(int devid);- void mdevremoveall(void);-+dev_t mdevadd_host(void);-+-+/*-+ * LINUX64 (xnulinux): a hosted XNU's disk backed by a host file. Stage 995 returns its size in bytes (0: none),-+ * stage 994 moves bytes between it and a wired kernel buffer (returns the count or -errno).-+ */-+extern uintptr_t linux64_hook;-+struct mdev_host_req { uint64_t write, off, len; void *buf; long result; }; /* the hook itself must return 0 */-+-+static long-+mdev_host_call(unsigned long stage, unsigned long arg)-+{-+ register unsigned long x0 __asm__("x0") = stage;-+ register unsigned long x1 __asm__("x1") = arg;-+ register unsigned long x2 __asm__("x2") = 0;-+ __asm__ volatile ("blr %3" : "+r"(x0), "+r"(x1), "+r"(x2) : "r"(linux64_hook)-+ : "x3", "x4", "x5", "x6", "x7", "x8", "x9", "x10", "x11", "x12", "x13",-+ "x14", "x15", "x16", "x17", "x30", "cc", "memory");-+ return (long)x0;-+}-+-+static int-+mdev_host_io(int write, uint64_t off, void *buf, uint64_t len)-+{-+ struct mdev_host_req q = { .write = (uint64_t)write, .off = off, .len = len, .buf = buf, .result = -EIO };-+ long r;-+ mdev_host_call(994, (unsigned long)&q);-+ r = q.result;-+ if (r < 0) {-+ return (int)-r;-+ }-+ return (uint64_t)r == len ? 0 : EIO;-+}- int mdevgetrange(int devid, uint64_t *base, uint64_t *size);-- static int-@@ -228,6 +263,32 @@ mdevrw(dev_t dev, struct uio *uio, __unused int ioflag)- if (uio_resid(uio) < 0) {- return EINVAL;- }-+ if (mdev[devid].mdFlags & mdHost) { /* LINUX64 (xnulinux): host-file disk, through a bounce buffer */-+ uint64_t end = (uint64_t)mdev[devid].mdSize << 12;-+ int write = (uio_rw(uio) == UIO_WRITE);-+ char *bounce = kalloc_data(65536, Z_WAITOK);-+ status = bounce ? 0 : ENOMEM;-+ while (!status && uio_resid(uio) > 0 && (uint64_t)uio->uio_offset < end) {-+ uint64_t off = (uint64_t)uio->uio_offset;-+ count = (int)MIN((uint64_t)uio_resid(uio), MIN(65536ULL, end - off));-+ if (write) {-+ status = uiomove(bounce, count, uio);-+ if (!status) {-+ status = mdev_host_io(1, off, bounce, count);-+ }-+ } else {-+ status = mdev_host_io(0, off, bounce, count);-+ if (!status) {-+ status = uiomove(bounce, count, uio);-+ }-+ }-+ }-+ if (bounce) {-+ kfree_data(bounce, 65536);-+ }-+ return status;-+ }-+- mdata = ((addr64_t)mdev[devid].mdBase << 12) + uio->uio_offset; /* Point to the area in "file" */-- saveflag = uio->uio_segflg; /* Remember what the request is */-@@ -242,10 +303,10 @@ mdevrw(dev_t dev, struct uio *uio, __unused int ioflag)- }- }--- if (uio->uio_offset > (mdev[devid].mdSize << 12)) {-+ if (uio->uio_offset > ((uint64_t)mdev[devid].mdSize << 12)) {- count = 0;- } else {-- count = imin(uio_resid(uio), (mdev[devid].mdSize << 12) - uio->uio_offset);-+ count = imin(uio_resid(uio), ((uint64_t)mdev[devid].mdSize << 12) - uio->uio_offset);- }-- status = uiomove64(mdata, count, uio); /* Move the data */-@@ -280,16 +341,16 @@ mdevstrategy(struct buf *bp)- * we just return with resid == count.- */--- if (blkoff >= (mdev[devid].mdSize << 12)) { /* Are they trying to read/write at/after end? */-- if (blkoff != (mdev[devid].mdSize << 12)) { /* Are we trying to read after EOF? */-+ if (blkoff >= ((uint64_t)mdev[devid].mdSize << 12)) { /* Are they trying to read/write at/after end? */-+ if (blkoff != ((uint64_t)mdev[devid].mdSize << 12)) { /* Are we trying to read after EOF? */- buf_seterror(bp, EINVAL); /* Yeah, this is an error */- }- buf_biodone(bp); /* Return */- return;- }--- if ((blkoff + buf_count(bp)) > (mdev[devid].mdSize << 12)) { /* Will this read go past end? */-- buf_setcount(bp, (uint32_t)((mdev[devid].mdSize << 12) - blkoff)); /* Yes, trim to max */-+ if ((blkoff + buf_count(bp)) > ((uint64_t)mdev[devid].mdSize << 12)) { /* Will this read go past end? */-+ buf_setcount(bp, (uint32_t)(((uint64_t)mdev[devid].mdSize << 12) - blkoff)); /* Yes, trim to max */- }- /*- * make sure the buffer's data area is-@@ -299,6 +360,18 @@ mdevstrategy(struct buf *bp)- panic("ramstrategy: buf_map failed");- }--+ if (mdev[devid].mdFlags & mdHost) { /* LINUX64 (xnulinux): host-file disk */-+ int err = mdev_host_io(!(buf_flags(bp) & B_READ), blkoff, (void *)vaddr, buf_count(bp));-+ buf_unmap(bp);-+ if (err) {-+ buf_seterror(bp, err);-+ } else {-+ buf_setresid(bp, 0);-+ }-+ buf_biodone(bp);-+ return;-+ }-+- fvaddr = (mdev[devid].mdBase << 12) + blkoff; /* Point to offset into ram disk */-- if (buf_flags(bp) & B_READ) { /* Is this a read? */-@@ -434,7 +507,7 @@ mdevioctl(dev_t dev, u_long cmd, caddr_t data, __unused int flag,- if (!(mdev[devid].mdFlags & mdInited)) {- return ENXIO;- }-- *o = ((mdev[devid].mdSize << 12) + mdev[devid].mdSecsize - 1) / mdev[devid].mdSecsize;-+ *o = (((uint64_t)mdev[devid].mdSize << 12) + mdev[devid].mdSecsize - 1) / mdev[devid].mdSecsize;- break;-- /*-@@ -708,6 +781,37 @@ mdevadd(int devid, uint64_t base, unsigned int size, int phys)- }---+/* LINUX64 (xnulinux): add the host-file disk (if the host has one) as the first free md unit. */-+dev_t-+mdevadd_host(void)-+{-+ uint64_t size = 0;-+ long bytes;-+ dev_t dev;-+ int i;-+-+ if (!linux64_hook) {-+ return -1;-+ }-+ mdev_host_call(995, (unsigned long)&size);-+ bytes = (long)size;-+ if (bytes < 4096) {-+ return -1;-+ }-+ /* a page-number range no RAM disk can overlap: the host disk has no memory behind it */-+ dev = mdevadd(-1, 1ULL << 40, (unsigned int)((uint64_t)bytes >> 12), 0);-+ if (dev == (dev_t)-1) {-+ return dev;-+ }-+ for (i = 0; i < NB_MAX_MDEVICES; i++) {-+ if ((mdev[i].mdFlags & mdInited) && mdev[i].mdBDev == dev) {-+ mdev[i].mdFlags |= mdHost;-+ }-+ }-+ printf("LINUX64: md%x is the host disk (%ld bytes)\n", minor(dev), bytes);-+ return dev;-+}-+- dev_t- mdevlookup(int devid)- {-@@ -760,7 +864,7 @@ mdevgetrange(int devid, uint64_t *base, uint64_t *size)- }-- *base = mdev[devid].mdBase << 12;-- *size = mdev[devid].mdSize << 12;-+ *size = (uint64_t)mdev[devid].mdSize << 12;-- /* make sure (base, size) is a valid range and will not overflow */- assert(*size < (UINT64_MAX - *base));-diff --git a/bsd/dev/unix_startup.c b/bsd/dev/unix_startup.c-index ec19ee7..6baf626 100644---- a/bsd/dev/unix_startup.c-+++ b/bsd/dev/unix_startup.c-@@ -186,6 +186,21 @@ bsd_startupearly(void)- }- #endif- }-+ {-+ /* LINUX64 (xnulinux): hosted, size the vnode table from the DRAM xnu.ko gave us (sane_size may not be set yet) */-+ extern uintptr_t linux64_hook;-+ extern uint64_t max_mem;-+ if (linux64_hook) {-+ kprintf("linux64: desiredvnodes %d (sane_size 0x%llx max_mem 0x%llx)\n", desiredvnodes, (uint64_t)sane_size, (uint64_t)max_mem);-+ /* the k27 config's CONFIG_VNODES (1024) is for a small device; a full macOS userland needs far more */-+ if (desiredvnodes < (int)(max_mem / 65536) + 1024) {-+ desiredvnodes = (int)(max_mem / 65536) + 1024;-+ if (desiredvnodes > 263168) {-+ desiredvnodes = 263168;-+ }-+ }-+ }-+ }- vnodes_sized = 1;- }- }-diff --git a/bsd/kern/bsd_init.c b/bsd/kern/bsd_init.c-index 5362b32..6345650 100644---- a/bsd/kern/bsd_init.c-+++ b/bsd/kern/bsd_init.c-@@ -585,7 +585,7 @@ bsd_init(void)- check_for_failure_injection(XNU_STAGE_BSD_INIT_START);- #endif---#define DEBUG_BSDINIT 0-+#define DEBUG_BSDINIT 1 /* LINUX64 (xnulinux) PoC: bsd_init progress to kprintf */-- #if DEBUG_BSDINIT- #define bsd_init_kprintf(x, ...) kprintf("bsd_init: " x, ## __VA_ARGS__)-@@ -963,6 +963,11 @@ bsd_init(void)- /* Register the built-in dlil ethernet interface family */- bsd_init_kprintf("calling ether_family_init\n");- ether_family_init();-+ {-+ /* LINUX64: the hosted kernel's Ethernet interface en0, framed through the host's xnu0 (bsd/net/if_linux64.c) */-+ extern void linux64_net_attach(void);-+ linux64_net_attach();-+ }- #endif /* ETHER */-- #if NETWORKING-@@ -1083,6 +1088,17 @@ bsd_init(void)- }- }- #endif-+ {-+ /*-+ * LINUX64 (xnulinux): a hosted APFS root is the host's own image, unsealed, with no boot manifest to-+ * authenticate it against. With SIP's unauthenticated-root allowance (boot-arg lp-sip0 with 0x800, what-+ * "csrutil authenticated-root disable" sets on a Mac) it mounts as it is.-+ */-+ extern uintptr_t linux64_hook;-+ if (linux64_hook && csr_check(CSR_ALLOW_UNAUTHENTICATED_ROOT) == 0) {-+ require_rootauth = FALSE;-+ }-+ }- if (require_rootauth) {- /* enforce sealedness */- int autherr = VNOP_IOCTL(rootvnode, FSIOC_KERNEL_ROOTAUTH, NULL, 0, vfs_context_kernel());-@@ -1177,6 +1193,25 @@ bsd_init(void)- }- #endif /* DEVFS */--+#if CONFIG_MOUNT_PREBOOTRECOVERY-+ {-+ /*-+ * LINUX64 (xnulinux): a hosted APFS root from a Mac's own disk. On a Mac, dyld in launchd grafts the boot-+ * cryptexes (the OS cryptex holds the dyld shared cache) from the ignition blob AppleImage4 builds out of iBoot's-+ * boot object manifests; a hosted boot has no iBoot. The OS and App cryptexes' contents sit in the Preboot-+ * volume's Cryptexes/OS and Cryptexes/App (scripts/mk-macvm-disk.sh), where dyld finds the shared cache: mount-+ * the Preboot volume of the root's container at its usual place before launchd runs, as Recovery is mounted.-+ */-+ extern uintptr_t linux64_hook;-+ if (linux64_hook && rootvnode && strcmp(rootvnode->v_mount->mnt_vfsstat.f_fstypename, "apfs") == 0) {-+ char prebootpath[] = "/System/Volumes/Preboot"; /* !const because of internal casting */-+ int perr = kernel_mount("apfs", NULLVP, NULLVP, prebootpath, rootvnode->v_mount, 0, 0,-+ KERNEL_MOUNT_PREBOOTVOL, vfs_context_kernel());-+ printf("LINUX64: Preboot volume at %s: %d\n", prebootpath, perr);-+ }-+ }-+#endif-+- #if CONFIG_BASESYSTEMROOT- #if CONFIG_IMAGEBOOT- if (bsdmgroot_bootable()) {-diff --git a/bsd/kern/kern_csr.c b/bsd/kern/kern_csr.c-index 604f16a..7cffe13 100644---- a/bsd/kern/kern_csr.c-+++ b/bsd/kern/kern_csr.c-@@ -226,6 +226,13 @@ csr_bootstrap(void)- } else {- csr_config &= ~CSR_ALLOW_UNAUTHENTICATED_ROOT;- }-+-+ /* LINUX64 (xnulinux): hosted XNU has no boot policy in its device tree; the boot-arg lp-sip0 stands in for it (0x2 lets-+ * rootless_check_trusted_class accept /Library/GPUBundles, where Metal finds the hosted system's plugin). */-+ uint32_t hosted_sip;-+ if (PE_parse_boot_argn("lp-sip0", &hosted_sip, sizeof(hosted_sip))) {-+ csr_config |= hosted_sip & ~CSR_ALLOW_APPLE_INTERNAL;-+ }- }- STARTUP(TUNABLES, STARTUP_RANK_FIRST, csr_bootstrap);--diff --git a/bsd/kern/kern_descrip.c b/bsd/kern/kern_descrip.c-index fac307f..23e1d06 100644---- a/bsd/kern/kern_descrip.c-+++ b/bsd/kern/kern_descrip.c-@@ -113,11 +113,25 @@- #include <kern/waitq.h>- #include <kern/ipc_kobject.h>- #include <kern/ipc_misc.h>-+#include <pexpert/pexpert.h>- #include <kern/ast.h>-- #include <vm/vm_protos.h>- #include <mach/mach_port.h>--+/* LINUX64: hosted with the amfi_get_out_of_my_way boot-arg, code signing lets any locally built code load (kern_mman.c too) */-+int linux64_amfi_off(void);-+int-+linux64_amfi_off(void)-+{-+ static int off = -1;-+ if (off < 0) {-+ int v = 0;-+ off = PE_parse_boot_argn("amfi_get_out_of_my_way", &v, sizeof(v)) && v != 0;-+ }-+ return off;-+}-+- #include <security/audit/audit.h>- #if CONFIG_MACF- #include <security/mac_framework.h>-@@ -2525,6 +2539,32 @@ sys_dup2(proc_t p, struct dup2_args *uap, int32_t *retval)- return dup2(p, p_cred, uap->from, uap->to, retval);- }--+/*-+ * LINUX64: dup3(from, to, flags), system call 149 in macOS 27's libsystem_kernel: dup2 that fails when from == to and-+ * takes O_CLOEXEC for the new descriptor.-+ */-+int-+sys_dup3(proc_t p, struct dup3_args *uap, int32_t *retval)-+{-+ kauth_cred_t p_cred = current_cached_proc_cred(p);-+ int error;-+-+ if ((uap->flags & ~O_CLOEXEC) || uap->from == uap->to) {-+ return EINVAL;-+ }-+ error = dup2(p, p_cred, uap->from, uap->to, retval);-+ if (error == 0 && (uap->flags & O_CLOEXEC)) {-+ struct fileproc *fp;-+-+ proc_fdlock(p);-+ if ((fp = fp_get_noref_locked(p, uap->to)) != NULL) {-+ fp->fp_flags |= FP_CLOEXEC;-+ }-+ proc_fdunlock(p);-+ }-+ return error;-+}-+- int- dup2(proc_t p, kauth_cred_t p_cred, int old, int new, int *retval)- {-@@ -4412,8 +4452,15 @@ dropboth:- }-- #if CONFIG_MACF-- error = mac_file_check_library_validation(p, fg, lv.lv_file_start,-- (user_long_t)lv.lv_error_message, lv.lv_error_message_size);-+ /*-+ * LINUX64: hosted with amfi_get_out_of_my_way, a process may load any library, as it may run any binary:-+ * AMFI otherwise rejects the locally built (ad-hoc, linker-signed) Python extension modules a locally built-+ * python dlopens ("mapping process and mapped file (non-platform) have different Team IDs").-+ */-+ if (!linux64_amfi_off()) {-+ error = mac_file_check_library_validation(p, fg, lv.lv_file_start,-+ (user_long_t)lv.lv_error_message, lv.lv_error_message_size);-+ }- #endif-- break;-diff --git a/bsd/kern/kern_exec.c b/bsd/kern/kern_exec.c-index 2bf34ab..5eb1c78 100644---- a/bsd/kern/kern_exec.c-+++ b/bsd/kern/kern_exec.c-@@ -2888,6 +2888,7 @@ badtoolate:- if (bootarg_execfailurereports) {- set_proc_name(imgp, current_proc());- }-+ { if (exec_failure_reason) kprintf("linux64: exec kill (badtoolate) \"%s\" reason ns %u code 0x%llx\n", current_proc()->p_name, exec_failure_reason->osr_namespace, (unsigned long long)exec_failure_reason->osr_code); }- psignal_with_reason(current_proc(), SIGKILL, exec_failure_reason);- exec_failure_reason = OS_REASON_NULL;--@@ -5701,6 +5702,7 @@ bad:- }-- if (exec_failure_reason && !spawn_no_exec) {-+ { if (exec_failure_reason) kprintf("linux64: exec kill (exec end) \"%s\" reason ns %u code 0x%llx\n", current_proc()->p_name, exec_failure_reason->osr_namespace, (unsigned long long)exec_failure_reason->osr_code); }- psignal_with_reason(p, SIGKILL, exec_failure_reason);- exec_failure_reason = NULL;- }-@@ -8304,6 +8306,14 @@ load_init_program(proc_t p)- boot_progress_stage("root check enter");- int cache_error = native_owner_cache_prepare(p, (user_addr_t)scratch_addr, &init_envp);- boot_progress_stage("root check returned");-+ {-+ /* LINUX64 (xnulinux): a hosted test root (no macOS OS volume, no boot manifest) skips the owner root check */-+ extern uintptr_t linux64_hook;-+ if (cache_error && linux64_hook) {-+ printf("linux64: owner root check failed (%d); continuing on a test root\n", cache_error);-+ cache_error = 0;-+ }-+ }- if (cache_error) panic("offline owner root check failed: %d", cache_error);- #endif- #if defined(XNU_BOOT_PROGRESS) && XNU_BOOT_PROGRESS-@@ -8741,6 +8751,7 @@ proc_process_signature(proc_t p, os_reason_t *signature_failure_reason)-- if (kr != KERN_SUCCESS) {- error = EINVAL;-+ kprintf("linux64: exec refused \"%s\": machine_task_process_signature: %s\n", p->p_name, error_msg ? error_msg : "(no message)");-- if (error_msg != NULL) {- uint32_t error_msg_len = (uint32_t)strlen(error_msg) + 1;-@@ -8843,6 +8854,24 @@ process_signature(proc_t p, struct image_params *imgp)- * which is unexpected but security framework does not- * approve of exec, kill and return immediately.- */-+ if (imgp->ip_mac_return != 0) {-+ /*-+ * LINUX64 (xnulinux): under amfi_get_out_of_my_way AMFI's other verdicts on code are already skipped (F_CHECK_LV, exec-+ * mmap); its execve hook still refuses some of Apple's own daemons ("dyld signature cannot be verified": system_installd,-+ * MobileSoftwareUpdate services), so the same mode lets those execs go on.-+ */-+ extern int linux64_amfi_off(void);-+ if (linux64_amfi_off()) {-+ kprintf("linux64: exec \"%s\": MAC policy verdict %d ignored (amfi_get_out_of_my_way)\n",-+ imgp->ip_vp ? imgp->ip_vp->v_name : "?", imgp->ip_mac_return);-+ imgp->ip_mac_return = 0;-+ if (imgp->ip_cs_error != OS_REASON_NULL) {-+ /* the same hook files its refusal as a code-signing exit reason too */-+ os_reason_free(imgp->ip_cs_error);-+ imgp->ip_cs_error = OS_REASON_NULL;-+ }-+ }-+ }- if (imgp->ip_mac_return != 0) {- boot_progress_process_stage(proc_getpid(p),p->p_name,"exec MAC policy REFUSED");- KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,-@@ -8850,6 +8879,7 @@ process_signature(proc_t p, struct image_params *imgp)- signature_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_SECURITY_POLICY);- error = imgp->ip_mac_return;- unexpected_failure = TRUE;-+ kprintf("linux64: exec refused \"%s\": MAC policy (ip_mac_return %d)\n", imgp->ip_vp ? imgp->ip_vp->v_name : "?", error);- goto done;- }--@@ -8857,6 +8887,8 @@ process_signature(proc_t p, struct image_params *imgp)- signature_failure_reason = imgp->ip_cs_error;- imgp->ip_cs_error = OS_REASON_NULL;- error = EACCES;-+ kprintf("linux64: exec refused \"%s\": code signature error (ns %u code 0x%llx)\n", imgp->ip_vp ? imgp->ip_vp->v_name : "?",-+ signature_failure_reason->osr_namespace, (unsigned long long)signature_failure_reason->osr_code);- goto done;- }--@@ -8864,6 +8896,7 @@ process_signature(proc_t p, struct image_params *imgp)- os_reason_t launch_constraint_reason;- if ((error = mac_proc_check_launch_constraints(p, imgp, &launch_constraint_reason)) != 0) {- signature_failure_reason = launch_constraint_reason;-+ kprintf("linux64: exec refused \"%s\": launch constraints (error %d)\n", imgp->ip_vp ? imgp->ip_vp->v_name : "?", error);- goto done;- }--@@ -9059,6 +9092,7 @@ done:- proc_csflags_set(p, CS_KILLED);- }- /* make very sure execution fails */-+ { if (signature_failure_reason) kprintf("linux64: exec kill (signature) \"%s\" reason ns %u code 0x%llx\n", current_proc()->p_name, signature_failure_reason->osr_namespace, (unsigned long long)signature_failure_reason->osr_code); }- if (vfexec || spawn) {- assert(signature_failure_reason != OS_REASON_NULL);- psignal_vfork_with_reason(p, proc_task(p), imgp->ip_new_thread,-diff --git a/bsd/kern/kern_exit.c b/bsd/kern/kern_exit.c-index 6e740c2..bfbdd29 100644---- a/bsd/kern/kern_exit.c-+++ b/bsd/kern/kern_exit.c-@@ -3792,6 +3792,9 @@ exit_with_mach_exception(-- printf("[%s: killed] exiting with signal %d, force exiting the process\n",- proc_best_name(p), SIGKILL);-+ kprintf("linux64: [%s] fatal mach exception type %d code 0x%llx subcode 0x%llx reason ns %u code 0x%llx\n",-+ proc_best_name(p), (int)exception.exception_type, (unsigned long long)exception.mx_code,-+ (unsigned long long)exception.mx_subcode, reason->osr_namespace, (unsigned long long)reason->osr_code);-- /* consumes reason */- return exit_with_reason(p, W_EXITCODE(0, SIGKILL), NULL,-diff --git a/bsd/kern/kern_mman.c b/bsd/kern/kern_mman.c-index 32d27c9..20aa26b 100644---- a/bsd/kern/kern_mman.c-+++ b/bsd/kern/kern_mman.c-@@ -487,7 +487,13 @@ mmap(proc_t p, struct mmap_args *uap, user_addr_t *retval)- /*- * Entitlement check.- */-- error = mac_proc_check_map_anon(p, current_cached_proc_cred(p),-+ /*-+ * LINUX64 (xnulinux): under amfi_get_out_of_my_way a JIT mapping is let through without the JIT entitlement, as-+ * AMFI's other verdicts on code are (F_CHECK_LV, executable mmap): the CPU Metal device (Mesa's llvmpipe) compiles-+ * shaders to machine code in every Metal client, WindowServer included, which is hardened and not JIT-entitled.-+ */-+ extern int linux64_amfi_off(void);-+ error = ((flags & MAP_JIT) && linux64_amfi_off()) ? 0 : mac_proc_check_map_anon(p, current_cached_proc_cred(p),- user_addr, user_size, prot, flags, &maxprot);- if (error) {- return EINVAL;-@@ -669,7 +675,9 @@ mmap(proc_t p, struct mmap_args *uap, user_addr_t *retval)-- handle = (void *)vp;- #if CONFIG_MACF-- error = mac_file_check_mmap(vfs_context_ucred(ctx),-+ extern int linux64_amfi_off(void);-+ /* LINUX64: with amfi_get_out_of_my_way, executable mappings of locally built (ad-hoc signed) libraries too */-+ error = linux64_amfi_off() ? 0 : mac_file_check_mmap(vfs_context_ucred(ctx),- fp->fp_glob, prot, flags, file_pos, &maxprot);- if (error) {- (void)vnode_put(vp);-diff --git a/bsd/kern/kern_trustcache.c b/bsd/kern/kern_trustcache.c-index 4b1e8a9..f979bb6 100644---- a/bsd/kern/kern_trustcache.c-+++ b/bsd/kern/kern_trustcache.c-@@ -78,6 +78,30 @@ SYSCTL_UINT(- 0, "number of loadable trust caches loaded"- );--+/* LINUX64 (xnulinux) */-+extern uintptr_t linux64_hook;-+static bool linux64_trust_cache_skipped = false;-+-+/*-+ * LINUX64 (xnulinux): the runtime is skipped at boot until the AppleImage4 and AMFI kexts register their interfaces-+ * (they start with the kernel collection); once both are there, set it up and load the static trust cache the host-+ * passes (chosen/memory-map/TrustCache), so AMFI validates the OS's platform binaries as on a booted Mac.-+ */-+void linux64_trust_cache_late_init(void);-+void-+linux64_trust_cache_late_init(void)-+{-+ if (!linux64_trust_cache_skipped || img4if == NULL || amfi == NULL) {-+ return;-+ }-+ linux64_trust_cache_skipped = false;-+ trust_cache_runtime_init();-+ if (!linux64_trust_cache_skipped) {-+ load_static_trust_cache();-+ printf("linux64: trust cache runtime set up late; static trust caches: %u\n", num_static_trust_caches);-+ }-+}-+- #if CONFIG_SPTM- /*- * We have the TrustedExecutionMonitor environment available. All of our artifacts-@@ -124,6 +148,16 @@ get_trust_cache_info(void)- void- trust_cache_runtime_init(void)- {-+ /*-+ * LINUX64 (xnulinux): hosted without the AppleImage4/AMFI kexts that register img4if/amfi.-+ * Skip the trust cache runtime until they are loaded (M2e).-+ */-+ if (linux64_hook != 0 && (img4if == NULL || amfi == NULL)) {-+ linux64_trust_cache_skipped = true;-+ printf("linux64: no image4/AMFI interface, trust cache runtime skipped\n");-+ return;-+ }-+- /* Image4 interface needs to be available */- if (img4if == NULL) {- panic("image4 interface not available");-@@ -402,6 +436,16 @@ trust_cache_runtime_init(void)- allow_engineering_caches = true;- }--+ /*-+ * LINUX64 (xnulinux): hosted without the AppleImage4/AMFI kexts that register img4if/amfi.-+ * Skip the trust cache runtime until they are loaded (M2e).-+ */-+ if (linux64_hook != 0 && (img4if == NULL || amfi == NULL)) {-+ linux64_trust_cache_skipped = true;-+ printf("linux64: no image4/AMFI interface, trust cache runtime skipped\n");-+ return;-+ }-+- /* Image4 interface needs to be available */- if (img4if == NULL) {- panic("image4 interface not available");-@@ -579,6 +623,16 @@ trust_cache_runtime_init(void)- allow_legacy_caches = true;- #endif--+ /*-+ * LINUX64 (xnulinux): hosted without the AppleImage4/AMFI kexts that register img4if/amfi.-+ * Skip the trust cache runtime until they are loaded (M2e).-+ */-+ if (linux64_hook != 0 && (img4if == NULL || amfi == NULL)) {-+ linux64_trust_cache_skipped = true;-+ printf("linux64: no image4/AMFI interface, trust cache runtime skipped\n");-+ return;-+ }-+- /* Image4 interface needs to be available */- if (img4if == NULL) {- panic("image4 interface not available");-@@ -1175,6 +1229,10 @@ load_static_trust_cache(void)- /* Mark this function as having been called */- trust_cache_static_init = true;--+ if (linux64_trust_cache_skipped) {-+ return;-+ }-+- /* Nothing to do when the runtime isn't set */- if (trust_cache_rt == NULL) {- return;-diff --git a/bsd/kern/sys_pipe.c b/bsd/kern/sys_pipe.c-index bd682ab..64d7fa9 100644---- a/bsd/kern/sys_pipe.c-+++ b/bsd/kern/sys_pipe.c-@@ -388,8 +388,29 @@ expand_pipespace(struct pipe *p, int target_size)- */-- /* ARGSUSED */-+static int pipe_flags(proc_t p, int32_t *retval, int flags);-+- int- pipe(proc_t p, __unused struct pipe_args *uap, int32_t *retval)-+{-+ return pipe_flags(p, retval, 0);-+}-+-+/*-+ * LINUX64: pipe2(fildes, flags), system call 148 in macOS 27's libsystem_kernel (__pipe2 returns the two descriptors in-+ * x0/x1 as __pipe does, then stores them). Flags: O_CLOEXEC and O_NONBLOCK, on both ends.-+ */-+int-+pipe2(proc_t p, struct pipe2_args *uap, int32_t *retval)-+{-+ if (uap->flags & ~(O_CLOEXEC | O_NONBLOCK)) {-+ return EINVAL;-+ }-+ return pipe_flags(p, retval, uap->flags);-+}-+-+static int-+pipe_flags(proc_t p, int32_t *retval, int flags)- {- struct fileproc *rf, *wf;- struct pipe *rpipe, *wpipe;-@@ -409,7 +430,10 @@ pipe(proc_t p, __unused struct pipe_args *uap, int32_t *retval)- if (error) {- goto freepipes;- }-- rf->f_flag = FREAD;-+ rf->f_flag = FREAD | ((flags & O_NONBLOCK) ? FNONBLOCK : 0);-+ if (flags & O_CLOEXEC) {-+ rf->fp_flags |= FP_CLOEXEC;-+ }- rf->f_ops = &pipeops;- fp_set_data(rf, rpipe);--@@ -418,7 +442,10 @@ pipe(proc_t p, __unused struct pipe_args *uap, int32_t *retval)- fp_free(p, retval[0], rf);- goto freepipes;- }-- wf->f_flag = FWRITE;-+ wf->f_flag = FWRITE | ((flags & O_NONBLOCK) ? FNONBLOCK : 0);-+ if (flags & O_CLOEXEC) {-+ wf->fp_flags |= FP_CLOEXEC;-+ }- wf->f_ops = &pipeops;- fp_set_data(wf, wpipe);--diff --git a/bsd/kern/syscalls.master b/bsd/kern/syscalls.master-index c08a74c..1e26f75 100644---- a/bsd/kern/syscalls.master-+++ b/bsd/kern/syscalls.master-@@ -229,8 +229,8 @@- 145 AUE_NULL ALL { int nosys(void); } { old setrlimit }- 146 AUE_NULL ALL { int nosys(void); } { old killpg }- 147 AUE_SETSID ALL { int setsid(void); }--148 AUE_NULL ALL { int nosys(void); } { old setquota }--149 AUE_NULL ALL { int nosys(void); } { old qquota }-+148 AUE_PIPE ALL { int pipe2(user_addr_t fildes, int flags) NO_SYSCALL_STUB; } { LINUX64 macOS 27 pipe2 }-+149 AUE_DUP2 ALL { int sys_dup3(u_int from, u_int to, int flags); } { LINUX64 macOS 27 dup3 }- 150 AUE_NULL ALL { int nosys(void); } { old getsockname }- 151 AUE_GETPGID ALL { int getpgid(pid_t pid); }- 152 AUE_SETPRIVEXEC ALL { int setprivexec(int flag); }-@@ -309,8 +309,8 @@- 212 AUE_NULL ALL { int nosys(void); } { old ATgetrsp }- 213 AUE_NULL ALL { int nosys(void); } { Reserved for AppleTalk }---214 AUE_NULL ALL { int nosys(void); }--215 AUE_NULL ALL { int nosys(void); }-+214 AUE_CHFLAGS ALL { int fchflagsat(int fd, user_addr_t path, int flags, int atflag); } { LINUX64 macOS 27 fchflagsat }-+215 AUE_UMASK ALL { int getumask(void); } { LINUX64 macOS 27 getumask }-- ; System Calls 216 - 230 are reserved for calls to support HFS/HFS Plus- ; file system semantics. Currently, we only use 215-227. The rest is-@@ -351,8 +351,8 @@- 243 AUE_INITGROUPS ALL { int initgroups(u_int gidsetsize, gid_t *gidset, int gmuid) NO_SYSCALL_STUB; }- 244 AUE_POSIX_SPAWN ALL { int posix_spawn(pid_t *pid, const char *path, const struct _posix_spawn_args_desc *adesc, char **argv, char **envp) NO_SYSCALL_STUB; }- 245 AUE_FFSCTL ALL { int ffsctl(int fd, u_long cmd, caddr_t data, u_int options); }--246 AUE_NULL ALL { int nosys(void); }--247 AUE_NULL ALL { int nosys(void); } { old nfsclnt }-+246 AUE_NULL ALL { int enosys(void); } { LINUX64 macOS 27 aio_readv ENOSYS without SIGSYS }-+247 AUE_NULL ALL { int enosys(void); } { LINUX64 macOS 27 aio_writev ENOSYS without SIGSYS }-- #if NFSSERVER /* XXX */- 248 AUE_FHOPEN ALL { int fhopen(const struct fhandle *u_fhp, int flags); }-@@ -360,7 +360,7 @@- 248 AUE_NULL ALL { int nosys(void); }- #endif---249 AUE_NULL ALL { int nosys(void); }-+249 AUE_NULL ALL { int enosys(void); } { LINUX64 macOS 27 fsctlat ENOSYS without SIGSYS }- 250 AUE_MINHERIT ALL { int minherit(caddr_ut addr, size_ut len, int inherit); }- #if SYSV_SEM- 251 AUE_SEMSYS ALL { int semsys(u_int which, int a2, int a3, int a4, int a5) NO_SYSCALL_STUB; }-@@ -530,7 +530,7 @@- 349 AUE_NULL ALL { int __pthread_fchdir(int fd); }- 350 AUE_AUDIT ALL { int audit(void *record, int length); }- 351 AUE_AUDITON ALL { int auditon(int cmd, void *data, int length); }--352 AUE_NULL ALL { int nosys(void); }-+352 AUE_NULL ALL { int enosys(void); } { LINUX64 macOS 27 guarded_ftruncate_np ENOSYS without SIGSYS }- 353 AUE_GETAUID ALL { int getauid(au_id_t *auid); }- 354 AUE_SETAUID ALL { int setauid(au_id_t *auid); }- 355 AUE_NULL ALL { int nosys(void); } { old getaudit }-diff --git a/bsd/net/if_linux64.c b/bsd/net/if_linux64.c-new file mode 100644-index 0000000..29cf3df---- /dev/null-+++ b/bsd/net/if_linux64.c-@@ -0,0 +1,331 @@-+/*-+ * LINUX64 (xnulinux): the hosted kernel's Ethernet interface en0.-+ *-+ * Its frames travel through the host: upcall 816 hands an outgoing frame to Linux (it arrives on the Linux netdev-+ * "xnu0"), upcall 817 takes the next frame Linux sent on xnu0, upcall 815 says how many wait. Linux routes, NATs and-+ * answers DHCP on xnu0. A receive thread polls the host (every 2 ms, and at once when the idle loop sees a frame).-+ */-+#include <sys/param.h>-+#include <sys/systm.h>-+#include <sys/kernel.h>-+#include <sys/mbuf.h>-+#include <sys/socket.h>-+#include <sys/sockio.h>-+#include <sys/kpi_mbuf.h>-+#include <net/if.h>-+#include <net/if_types.h>-+#include <net/if_ether.h>-+#include <net/ethernet.h>-+#include <net/kpi_interface.h>-+#include <kern/thread.h>-+#include <kern/locks.h>-+#include <kern/sched_prim.h>-+#include <pexpert/pexpert.h>-+-+extern uintptr_t linux64_hook;-+extern void linux64_stage_arg(unsigned long, unsigned long);-+-+struct linux64_net_req {-+ void *buf;-+ uint64_t len;-+ long result;-+};-+-+#define L64_FRAME_MAX (ETHER_MAX_LEN + 64)-+-+static ifnet_t l64_ifp;-+static uint8_t l64_txbuf[L64_FRAME_MAX];-+static uint8_t l64_rxbuf[L64_FRAME_MAX];-+static LCK_GRP_DECLARE(l64_lck_grp, "linux64_net");-+static LCK_MTX_DECLARE(l64_tx_lock, &l64_lck_grp);-+static int l64_rx_event;-+-+/* the MAC is locally administered: 02:58:4e:55:00:01 ("XNU") */-+static const uint8_t l64_mac[ETHER_ADDR_LEN] = { 0x02, 0x58, 0x4e, 0x55, 0x00, 0x01 };-+-+static errno_t-+l64_output(ifnet_t ifp, mbuf_t m)-+{-+ size_t len = mbuf_pkthdr_len(m);-+-+ if (len < ETHER_HDR_LEN || len > sizeof(l64_txbuf)) {-+ ifnet_stat_increment_out(ifp, 0, 0, 1);-+ mbuf_freem(m);-+ return 0;-+ }-+ lck_mtx_lock(&l64_tx_lock);-+ if (mbuf_copydata(m, 0, len, l64_txbuf) == 0) {-+ struct linux64_net_req q = { .buf = l64_txbuf, .len = len, .result = 0 };-+ linux64_stage_arg(816, (unsigned long)&q);-+ if (q.result > 0) {-+ ifnet_stat_increment_out(ifp, 1, (uint32_t)len, 0);-+ } else {-+ ifnet_stat_increment_out(ifp, 0, 0, 1);-+ }-+ }-+ lck_mtx_unlock(&l64_tx_lock);-+ mbuf_freem(m);-+ return 0;-+}-+-+static errno_t-+l64_ioctl(ifnet_t ifp, u_long cmd, void *data)-+{-+ switch (cmd) {-+ case SIOCSIFFLAGS:-+ /* the link to the host is always there: running whenever it is up */-+ ifnet_set_flags(ifp, (ifnet_flags(ifp) & IFF_UP) ? IFF_RUNNING : 0, IFF_RUNNING);-+ return 0;-+ case SIOCSIFADDR:-+ case SIOCAIFADDR:-+ case SIOCADDMULTI:-+ case SIOCDELMULTI:-+ return 0;-+ case SIOCSIFMTU: {-+ struct ifreq *ifr = (struct ifreq *)data;-+ if (ifr->ifr_mtu < 68 || ifr->ifr_mtu > ETHERMTU) {-+ return EINVAL;-+ }-+ return ifnet_set_mtu(ifp, (uint32_t)ifr->ifr_mtu);-+ }-+ default:-+ return EOPNOTSUPP;-+ }-+}-+-+static void-+l64_input_one(long len)-+{-+ mbuf_t m = NULL;-+ struct ifnet_stat_increment_param stats = {};-+-+ /* one packet-header mbuf with a 2 KB cluster holds any frame (ETHER_MAX_LEN 1518): no chain to walk */-+ if (len > MCLBYTES || mbuf_getpacket(MBUF_WAITOK, &m) != 0 || m == NULL) {-+ return;-+ }-+ memcpy(mbuf_data(m), l64_rxbuf, (size_t)len);-+ mbuf_setlen(m, (size_t)len);-+ mbuf_pkthdr_setlen(m, (size_t)len);-+ mbuf_pkthdr_setrcvif(m, l64_ifp);-+ mbuf_pkthdr_setheader(m, mbuf_data(m));-+ mbuf_setdata(m, (char *)mbuf_data(m) + ETHER_HDR_LEN, mbuf_len(m) - ETHER_HDR_LEN);-+ mbuf_pkthdr_adjustlen(m, -ETHER_HDR_LEN);-+ stats.packets_in = 1;-+ stats.bytes_in = (uint32_t)len;-+ ifnet_input(l64_ifp, m, &stats);-+}-+-+static void-+l64_rx_thread(__unused void *arg, __unused wait_result_t wr)-+{-+ for (;;) {-+ for (int n = 0; n < 256; n++) {-+ struct linux64_net_req q = { .buf = l64_rxbuf, .len = sizeof(l64_rxbuf), .result = 0 };-+ linux64_stage_arg(817, (unsigned long)&q);-+ if (q.result < ETHER_HDR_LEN) {-+ break;-+ }-+ l64_input_one(q.result);-+ }-+ assert_wait_timeout((event_t)&l64_rx_event, THREAD_UNINT, 2, NSEC_PER_MSEC);-+ thread_block(THREAD_CONTINUE_NULL);-+ }-+}-+-+/*-+ * The transport for the IOKit driver (kexts/XnuEthernet), which is en0 normally: an IOEthernetInterface is what IOTimeSync takes-+ * its clock identifier from (WindowServer waits on it). One frame to the host (its length when sent, 0 when not), and the next-+ * frame from it (its length, 0 when none waits).-+ */-+long linux64_net_send(const void *frame, unsigned long length);-+long-+linux64_net_send(const void *frame, unsigned long length)-+{-+ struct linux64_net_req q = { .buf = (void *)(uintptr_t)frame, .len = length, .result = 0 };-+-+ if (linux64_hook == 0 || length < ETHER_HDR_LEN || length > L64_FRAME_MAX) {-+ return 0;-+ }-+ linux64_stage_arg(816, (unsigned long)&q);-+ return q.result > 0 ? (long)length : 0;-+}-+-+long linux64_net_recv(void *buffer, unsigned long size);-+long-+linux64_net_recv(void *buffer, unsigned long size)-+{-+ struct linux64_net_req q = { .buf = buffer, .len = size, .result = 0 };-+-+ if (linux64_hook == 0) {-+ return 0;-+ }-+ linux64_stage_arg(817, (unsigned long)&q);-+ return q.result > 0 ? q.result : 0;-+}-+-+/*-+ * The host's input events for the IOKit HID driver (kexts/XnuInput), through the same kind of upcall: whole 8-byte evdev-+ * records {u16 type, u16 code, s32 value} into buffer, their bytes (0 when none wait).-+ */-+long linux64_input_read(void *buffer, unsigned long size);-+long-+linux64_input_read(void *buffer, unsigned long size)-+{-+ struct linux64_net_req q = { .buf = buffer, .len = size, .result = 0 };-+-+ if (linux64_hook == 0) {-+ return 0;-+ }-+ linux64_stage_arg(818, (unsigned long)&q);-+ return q.result > 0 ? q.result : 0;-+}-+-+/*-+ * The hosted keystore's backing file (xnu.ko keystore=): XnuEAN keeps the EAN blobs of the virtual platform's xART there.-+ * Reads or writes `length` bytes at `offset`; bytes moved, or a negative error.-+ */-+struct linux64_store_req {-+ uint64_t write, off, len;-+ void *buf;-+ long result;-+};-+long linux64_store_rw(int write, void *buffer, unsigned long length, unsigned long offset);-+long-+linux64_store_rw(int write, void *buffer, unsigned long length, unsigned long offset)-+{-+ struct linux64_store_req q = { .write = (uint64_t)write, .off = offset, .len = length, .buf = buffer, .result = -6 };-+-+ if (linux64_hook == 0) {-+ return -6;-+ }-+ linux64_stage_arg(819, (unsigned long)&q);-+ return q.result;-+}-+-+/*-+ * The hosted system's block disk (XnuDisk, kexts/XnuDisk): a second host file, an APFS container, served to IOKit as media.-+ * Upcall 821 returns its size in bytes (0: none), 820 reads or writes `length` bytes at `offset` (bytes moved or -errno).-+ */-+uint64_t linux64_disk_size(void);-+uint64_t-+linux64_disk_size(void)-+{-+ uint64_t size = 0;-+-+ if (linux64_hook != 0) {-+ linux64_stage_arg(821, (unsigned long)&size);-+ }-+ return size;-+}-+-+long linux64_disk_rw(int write, void *buffer, unsigned long length, unsigned long offset);-+long-+linux64_disk_rw(int write, void *buffer, unsigned long length, unsigned long offset)-+{-+ struct linux64_store_req q = { .write = (uint64_t)write, .off = offset, .len = length, .buf = buffer, .result = -6 };-+-+ if (linux64_hook == 0) {-+ return -6;-+ }-+ linux64_stage_arg(820, (unsigned long)&q);-+ return q.result;-+}-+-+/*-+ * A host call (kexts/XnuDrm): len bytes at req to a Linux service through xnu.ko and fki (upcall 830), its reply into-+ * reply (at most max bytes). Returns the reply's length or a negative errno. The CPU waits in the call.-+ */-+struct linux64_hostcall_req {-+ const void *req;-+ uint64_t len;-+ void *reply;-+ uint64_t max;-+ long result;-+};-+long linux64_hostcall(const void *req, unsigned long len, void *reply, unsigned long max);-+long-+linux64_hostcall(const void *req, unsigned long len, void *reply, unsigned long max)-+{-+ struct linux64_hostcall_req q = { .req = req, .len = len, .reply = reply, .max = max, .result = -6 };-+-+ if (linux64_hook == 0) {-+ return -6;-+ }-+ linux64_stage_arg(830, (unsigned long)&q);-+ return q.result;-+}-+-+/* From the hosted idle loop, after the host let it sleep: wake the receive thread when Linux queued frames. */-+void linux64_net_idle_poll(void);-+void-+linux64_net_idle_poll(void)-+{-+ uint64_t waiting = 0;-+-+ if (l64_ifp == NULL) {-+ return;-+ }-+ linux64_stage_arg(815, (unsigned long)&waiting);-+ if (waiting != 0) {-+ thread_wakeup((event_t)&l64_rx_event);-+ }-+}-+-+void linux64_net_attach(void);-+void-+linux64_net_attach(void)-+{-+ struct ifnet_init_eparams init = {};-+ ifnet_t ifp = NULL;-+ thread_t th = THREAD_NULL;-+ errno_t err;-+-+ if (linux64_hook == 0) {-+ return;-+ }-+ /* the kernel's own en0 only on request (boot-arg linux64-ifnet=1): XnuEthernet is en0 otherwise */-+ int own = 0;-+ if (!PE_parse_boot_argn("linux64-ifnet", &own, sizeof(own)) || !own) {-+ return;-+ }-+ init.ver = IFNET_INIT_CURRENT_VERSION;-+ init.len = sizeof(init);-+ init.flags = IFNET_INIT_LEGACY | IFNET_INIT_NX_NOAUTO;-+ init.uniqueid = "linux64-en0";-+ init.uniqueid_len = sizeof("linux64-en0") - 1;-+ init.name = "en";-+ init.unit = 0;-+ init.family = IFNET_FAMILY_ETHERNET;-+ init.type = IFT_ETHER;-+ init.output = l64_output;-+ init.demux = ether_demux;-+ init.add_proto = ether_add_proto;-+ init.del_proto = ether_del_proto;-+ init.check_multi = ether_check_multi;-+ init.framer_extended = ether_frameout_extended;-+ init.ioctl = l64_ioctl;-+ init.broadcast_addr = etherbroadcastaddr;-+ init.broadcast_len = ETHER_ADDR_LEN;-+ err = ifnet_allocate_extended(&init, &ifp);-+ if (err != 0) {-+ printf("linux64: en0 allocate failed %d\n", err);-+ return;-+ }-+ ifnet_set_mtu(ifp, ETHERMTU);-+ ifnet_set_hdrlen(ifp, ETHER_HDR_LEN);-+ ifnet_set_flags(ifp, IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST | IFF_RUNNING, 0xffff);-+ ifnet_set_baudrate(ifp, 1000ULL * 1000 * 1000);-+ err = ifnet_attach(ifp, NULL);-+ if (err != 0) {-+ printf("linux64: en0 attach failed %d\n", err);-+ ifnet_release(ifp);-+ return;-+ }-+ ifnet_set_lladdr(ifp, l64_mac, sizeof(l64_mac));-+ l64_ifp = ifp;-+ if (kernel_thread_start(l64_rx_thread, NULL, &th) == KERN_SUCCESS) {-+ thread_deallocate(th);-+ }-+ printf("linux64: en0 attached (%02x:%02x:%02x:%02x:%02x:%02x), frames through the host's xnu0\n",-+ l64_mac[0], l64_mac[1], l64_mac[2], l64_mac[3], l64_mac[4], l64_mac[5]);-+}-diff --git a/bsd/pthread/pthread_shims.c b/bsd/pthread/pthread_shims.c-index e5e58b5..6e6596d 100644---- a/bsd/pthread/pthread_shims.c-+++ b/bsd/pthread/pthread_shims.c-@@ -316,6 +316,12 @@ void- pthread_init(void)- {- if (!pthread_functions) {-+ /* LINUX64 (xnulinux): hosted without pthread.kext until kexts load (M2e); continue without it. */-+ extern uintptr_t linux64_hook;-+ if (linux64_hook) {-+ printf("linux64: pthread kext not loaded, pthread support skipped\n");-+ return;-+ }- panic("pthread kernel extension not loaded (function table is NULL).");- }- pthread_functions->pthread_init();-@@ -324,6 +330,9 @@ pthread_init(void)- void- pth_proc_hashinit(proc_t p)- {-+ if (!pthread_functions) {-+ return; /* LINUX64: hosted without pthread.kext */-+ }- pthread_functions->pth_proc_hashinit(p);- }--diff --git a/bsd/pthread/pthread_workqueue.c b/bsd/pthread/pthread_workqueue.c-index cb27db6..2a73564 100644---- a/bsd/pthread/pthread_workqueue.c-+++ b/bsd/pthread/pthread_workqueue.c-@@ -2117,6 +2117,21 @@ workq_open(struct proc *p, __unused struct workq_open_args *uap,- }-- wq_max_cooperative_threads = num_cpus;-+ {-+ /*-+ * LINUX64 (xnulinux): hosted XNU has one CPU. With a parallelism of 1 a process whose main thread waits-+ * on work it queued (ld's layout: dispatch_group_wait) never got a worker admitted; allow a few-+ * constrained threads per QoS bucket (the cooperative pool stays at the CPU count), as a small multi-core machine would.-+ */-+ extern uintptr_t linux64_hook;-+ if (linux64_hook) {-+ for (int b = 0; b < WORKQ_NUM_QOS_BUCKETS; b++) {-+ if (wq_max_parallelism[b] < 4) {-+ wq_max_parallelism[b] = 4;-+ }-+ }-+ }-+ }-- wq_init_constrained_limit = 0;- }-diff --git a/bsd/vfs/vfs_subr.c b/bsd/vfs/vfs_subr.c-index 229d6a1..cb42a6f 100644---- a/bsd/vfs/vfs_subr.c-+++ b/bsd/vfs/vfs_subr.c-@@ -1144,7 +1144,15 @@ vfs_rootmountalloc_internal(struct vfstable *vfsp, const char *devname)-- mp->mnt_vtable = vfsp;- mp->mnt_op = vfsp->vfc_vfsops;-- mp->mnt_flag = MNT_RDONLY | MNT_ROOTFS;-+ {-+ /*-+ * LINUX64 (xnulinux): a hosted HFS+ root (the host-file disk) mounts read-write; nothing here runs the boot-+ * tasks that would remount it (logd traps on EROFS writing /private/var/db/diagnostics). APFS refuses a-+ * writable root at mountroot ("can't mount root filesystem writeable"): an APFS root mounts read-only, as on a Mac.-+ */-+ extern uintptr_t linux64_hook;-+ mp->mnt_flag = (linux64_hook && strcmp(vfsp->vfc_name, "hfs") == 0 ? 0 : MNT_RDONLY) | MNT_ROOTFS;-+ }- mp->mnt_vnodecovered = NULLVP;- //mp->mnt_stat.f_type = vfsp->vfc_typenum;- mp->mnt_flag |= vfsp->vfc_flags & MNT_VISFLAGMASK;-diff --git a/bsd/vfs/vfs_syscalls.c b/bsd/vfs/vfs_syscalls.c-index 873eb8f..a15ea6b 100644---- a/bsd/vfs/vfs_syscalls.c-+++ b/bsd/vfs/vfs_syscalls.c-@@ -8018,6 +8018,44 @@ chflags(__unused proc_t p, struct chflags_args *uap, __unused int32_t *retval)- return error;- }--+/*-+ * LINUX64: fchflagsat(fd, path, flags, atflag), system call 214 in macOS 27's libsystem_kernel: chflags relative to fd-+ * (AT_FDCWD for the working directory), not following a final symlink with AT_SYMLINK_NOFOLLOW.-+ */-+int-+fchflagsat(__unused proc_t p, struct fchflagsat_args *uap, __unused int32_t *retval)-+{-+ vnode_t vp;-+ vfs_context_t ctx = vfs_context_current();-+ int error;-+ struct nameidata nd;-+-+ if (uap->atflag & ~AT_SYMLINK_NOFOLLOW) {-+ return EINVAL;-+ }-+ AUDIT_ARG(fflags, uap->flags);-+ NDINIT(&nd, LOOKUP, OP_SETATTR, ((uap->atflag & AT_SYMLINK_NOFOLLOW) ? NOFOLLOW : FOLLOW) | AUDITVNPATH1,-+ UIO_USERSPACE, uap->path, ctx);-+ error = nameiat(&nd, uap->fd);-+ if (error) {-+ return error;-+ }-+ vp = nd.ni_vp;-+ nameidone(&nd);-+ /* chflags1 drops the vnode reference */-+ return chflags1(vp, uap->flags, ctx);-+}-+-+/*-+ * LINUX64: getumask(), system call 215 in macOS 27's libsystem_kernel: the file creation mask, unchanged.-+ */-+int-+getumask(proc_t p, __unused struct getumask_args *uap, int32_t *retval)-+{-+ *retval = p->p_fd.fd_cmask;-+ return 0;-+}-+- /*- * Change flags of a file given a file descriptor.- */-diff --git a/bsd/vm/vm_unix.c b/bsd/vm/vm_unix.c-index d8fd4af..815051f 100644---- a/bsd/vm/vm_unix.c-+++ b/bsd/vm/vm_unix.c-@@ -1917,6 +1917,29 @@ _shared_region_map_and_slide(- proc_getpid(p), p->p_comm, kr));- }--+ {-+ /* LINUX64 debug: what the process now sees where data from its own memory (fd -1) went */-+ extern uintptr_t linux64_hook;-+ for (uint32_t f = 0; linux64_hook && kr == KERN_SUCCESS && f < files_count; f++) {-+ if (sr_file_mappings[f].fd == -1 && sr_file_mappings[f].mappings_count > 0) {-+ struct shared_file_mapping_slide_np *m = &sr_file_mappings[f].mappings[0];-+ uint64_t w[4] = {0, 0, 0, 0}, src[2] = {0, 0};-+ int e1 = copyin((user_addr_t)m->sms_address, w, sizeof(w));-+ int e2 = copyin((user_addr_t)m->sms_file_offset, src, sizeof(src));-+ kprintf("linux64: shared region data mapping at 0x%llx size 0x%llx from 0x%llx: sees %d %016llx %016llx %016llx, source %d %016llx %016llx\n",-+ m->sms_address, m->sms_size, m->sms_file_offset, e1, w[0], w[1], w[2], e2, src[0], src[1]);-+ {-+ extern uint32_t pmap_find_phys(struct pmap *, uint64_t);-+ pmap_t upmap = get_task_pmap(current_task());-+ uint32_t pn = pmap_find_phys(upmap, (uint64_t)m->sms_file_offset);-+ uint64_t pa = ((uint64_t)pn << PAGE_SHIFT) | (m->sms_file_offset & PAGE_MASK);-+ kprintf("linux64: source pn 0x%x pa 0x%llx via phys %016llx %016llx; PAR after AT S1E0R: 0x%llx\n", pn, pa,-+ pn ? ml_phys_read_double_64(pa) : 0, pn ? ml_phys_read_double_64(pa + 8) : 0, ({ uint64_t par; __asm__ volatile ("at s1e0r, %1\n isb\n mrs %0, par_el1" : "=r"(par) : "r"(m->sms_file_offset)); par; }));-+ }-+ }-+ }-+ }-+- /* convert kern_return_t to errno */- switch (kr) {- case KERN_SUCCESS:-diff --git a/config/MASTER.arm64.bcm2837 b/config/MASTER.arm64.bcm2837-index 0c52cc6..87d19c7 100644---- a/config/MASTER.arm64.bcm2837-+++ b/config/MASTER.arm64.bcm2837-@@ -33,7 +33,7 @@- # BSD_RELEASE = [ BSD_BASE no_printf_str no_kprintf_str secure_kernel config_imgsrc_access ]- # BSD_DEV = [ BSD_BASE config_netboot config_imgsrc_access pgo config_vnguard rosetta BSD_EXTRAS_DEV ]- # BSD_DEBUG = [ BSD_BASE config_netboot config_imgsrc_access pgo config_vnguard rosetta BSD_EXTRAS_DEBUG ]--# FILESYS_BASE = [ devfs fifo fs_compression config_protect config_mnt_rootsnap config_triggers config_fse routefs namedstreams config_dataless_files bindfs config_ext_resolver config_firmlinks config_searchfs config_file_leases ]-+# FILESYS_BASE = [ devfs fifo fs_compression config_protect config_mnt_rootsnap config_triggers config_fse routefs namedstreams config_dataless_files bindfs config_ext_resolver config_firmlinks config_searchfs config_file_leases config_mount_prebootrecovery ]- # FILESYS_RELEASE= [ FILESYS_BASE ]- # FILESYS_DEV = [ FILESYS_BASE fdesc config_union_mounts ]- # FILESYS_DEBUG = [ FILESYS_BASE fdesc config_union_mounts ]-diff --git a/iokit/Kernel/IONVRAMCHRPHandler.cpp b/iokit/Kernel/IONVRAMCHRPHandler.cpp-index 0cc7f6e..c07d35c 100644---- a/iokit/Kernel/IONVRAMCHRPHandler.cpp-+++ b/iokit/Kernel/IONVRAMCHRPHandler.cpp-@@ -511,6 +511,10 @@ IONVRAMCHRPHandler::unserializeVariables(void)- if (currentRegion->size == 0) {- continue;- }-+ /* LINUX64 (xnulinux): no NVRAM image from a bootloader (blank store): no partition to read */-+ if (_nvramImage == nullptr || currentRegion->offset == 0xFFFFFFFF) {-+ continue;-+ }-- DEBUG_INFO("region = %d\n", currentRegion->type);- cnt = 0;-diff --git a/iokit/Kernel/IOPlatformExpert.cpp b/iokit/Kernel/IOPlatformExpert.cpp-index 76555f6..42b940f 100644---- a/iokit/Kernel/IOPlatformExpert.cpp-+++ b/iokit/Kernel/IOPlatformExpert.cpp-@@ -1403,15 +1403,18 @@ PESetGMTTimeOfDay(long secs)- PESetUTCTimeOfDay(secs, 0);- }--+extern "C" void linux64_stage_arg(unsigned long, unsigned long);-+- void- PEGetUTCTimeOfDay(clock_sec_t * secs, clock_usec_t * usecs)- {- clock_nsec_t nsecs = 0;--- *secs = 0;-- if (gIOPlatform) {-- gIOPlatform->getUTCTimeOfDay(secs, &nsecs);-- }-+ /* LINUX64: hosted, no RTC; the host's wall clock (UTC) through upcall 812 */-+ uint64_t host[2] = { 0, 0 };-+ linux64_stage_arg(812, (unsigned long)host);-+ *secs = (clock_sec_t)host[0];-+ nsecs = (clock_nsec_t)host[1];-- assert(nsecs < NSEC_PER_SEC);- *usecs = nsecs / NSEC_PER_USEC;-@@ -1540,6 +1543,114 @@ IOPlatformExpert::registerNVRAMController(IONVRAMController * caller)- publishResource("IONVRAM");- }--+extern "C" uintptr_t linux64_hook; /* LINUX64 (xnulinux) */-+#include <libkern/c++/OSKext.h>-+-+/*-+ * LINUX64 (xnulinux): a stand-in for AppleKeyStore's "AKSKernelServices" table, which AMFI requires (AKS_services()-+ * has no path without it). The entries AMFI calls are type-discriminated function pointers: 0x120 (disc 0x61fc,-+ * register for a state notification), 0x128 (0x146e, read state), 0x130 (0xd507, unregister). A hosted XNU has no-+ * keybag: the queries report unsupported, unregistering succeeds.-+ */-+#include <ptrauth.h>-+static int-+linux64_aks_unsupported(void)-+{-+ return kIOReturnUnsupported;-+}-+static int-+linux64_aks_ok(void)-+{-+ return 0;-+}-+static uintptr_t linux64_aks_table[0x40];-+-+-+/*-+ * LINUX64 (xnulinux): the stand-in IOAESAccelerator's AES operation (vtable +0x890, called by AppleImage4 with-+ * (src, dst, length, iv, direction, ...)). There is no device key to use: it copies src to dst ("encrypts" with the-+ * identity), which is all a hosted Image4 nonce store needs to stay consistent.-+ */-+extern "C" uint64_t kvtophys(vm_offset_t va);-+extern "C" void ml_phys_write_double_64(addr64_t paddr, unsigned long long data);-+static IOReturn-+linux64_aes_perform(IOService *self, IOMemoryDescriptor *src, IOMemoryDescriptor *dst, uint64_t len, void *iv, int dir,-+ void *a6, void *a7)-+{-+ (void)self; (void)iv; (void)dir; (void)a6; (void)a7;-+ if (!src || !dst || len > 65536) {-+ return kIOReturnBadArgument;-+ }-+ void *buf = IOMallocData((vm_size_t)len);-+ if (!buf) {-+ return kIOReturnNoMemory;-+ }-+ /* the descriptors come unprepared (a real engine prepares them for its DMA): wire them for the copy, each in its-+ * own direction (AppleVirtualPlatformXART encrypts in place: one in-out descriptor as both, which a read-only-+ * preparation would keep writeBytes from) */-+ IOReturn rs = src->prepare(), rd = (src == dst) ? kIOReturnSuccess : dst->prepare();-+ IOByteCount got = 0, put = 0;-+ if (rs == kIOReturnSuccess && rd == kIOReturnSuccess) {-+ got = src->readBytes(0, buf, (IOByteCount)len);-+ put = dst->writeBytes(0, buf, got);-+ }-+ if (rs == kIOReturnSuccess) {-+ src->complete();-+ }-+ if (rd == kIOReturnSuccess && src != dst) {-+ dst->complete();-+ }-+ IOFreeData(buf, (vm_size_t)len);-+ return (got == len && put == len) ? kIOReturnSuccess : kIOReturnIOError;-+}-+-+static void-+linux64_patch_aes_vtable(OSObject *aes)-+{-+ uintptr_t vt = (uintptr_t)ptrauth_auth_data(*(void **)aes, ptrauth_key_asda,-+ ptrauth_blend_discriminator(aes, 0xcda1));-+ uintptr_t entry = vt + 0x890;-+ void *fn = ptrauth_strip((void *)&linux64_aes_perform, ptrauth_key_function_pointer);-+ uint64_t signed_fn = (uint64_t)ptrauth_sign_unauthenticated(fn, ptrauth_key_asia,-+ ptrauth_blend_discriminator((void *)entry, 0x17dc));-+ uint64_t pa = kvtophys((vm_offset_t)entry);-+ if (pa) {-+ ml_phys_write_double_64((addr64_t)pa, signed_fn);-+ IOLog("LINUX64: IOAESAccelerator AES entry (vtable %p +0x890) is the hosted copy\n", (void *)vt);-+ }-+}-+-+static void-+linux64_register_stand_in(IOService *parent, IOService *s, const char *name)-+{-+ if (s && s->init()) {-+ s->setName(name);-+ if (s->attach(parent)) {-+ s->registerService();-+ IOLog("LINUX64: stand-in %s registered\n", name);-+ }-+ }-+ if (s) {-+ s->release();-+ }-+}-+static void *-+linux64_aks_services(void)-+{-+ if (!linux64_aks_table[0]) {-+ void *un = ptrauth_strip((void *)&linux64_aks_unsupported, ptrauth_key_function_pointer);-+ void *ok = ptrauth_strip((void *)&linux64_aks_ok, ptrauth_key_function_pointer);-+ for (unsigned i = 1; i < 0x40; i++) {-+ linux64_aks_table[i] = (uintptr_t)ptrauth_sign_unauthenticated(un, ptrauth_key_asia, 0);-+ }-+ linux64_aks_table[0x120 / 8] = (uintptr_t)ptrauth_sign_unauthenticated(un, ptrauth_key_asia, 0x61fc);-+ linux64_aks_table[0x128 / 8] = (uintptr_t)ptrauth_sign_unauthenticated(un, ptrauth_key_asia, 0x146e);-+ linux64_aks_table[0x130 / 8] = (uintptr_t)ptrauth_sign_unauthenticated(ok, ptrauth_key_asia, 0xd507);-+ linux64_aks_table[0] = (uintptr_t)ptrauth_sign_unauthenticated(un, ptrauth_key_asia, 0);-+ }-+ return linux64_aks_table;-+}-+- IOReturn- IOPlatformExpert::callPlatformFunction(const OSSymbol *functionName,- bool waitForFunction,-@@ -1564,7 +1675,63 @@ IOPlatformExpert::callPlatformFunction(const OSSymbol *functionName,- }-- if (waitForFunction) {-- _resources = waitForService(resourceMatching(functionName));-+ /*-+ * LINUX64 (xnulinux): with the virtual platform's software keystore in the collection (AppleVPKeyStore, as in-+ * Apple's VirtualMac), AppleKeyStore provides AKSKernelServices itself: the stand-ins below for the SEP's-+ * endpoint and the AES engine are still needed, the stand-in table is not.-+ */-+ static int linux64_real_aks = -1;-+ if (linux64_hook && linux64_real_aks < 0) {-+ OSKext *vpks = OSKext::lookupKextWithIdentifier("com.apple.driver.AppleVPKeyStore");-+ linux64_real_aks = vpks != NULL;-+ OSSafeReleaseNULL(vpks);-+ }-+ if (linux64_hook && functionName->isEqualTo("AKSKernelServices")) {-+ static bool scrd_done;-+ if (param1 && !linux64_real_aks) {-+ *(void **)param1 = linux64_aks_services();-+ }-+ if (!scrd_done) {-+ /*-+ * No SEP either: AMFI's device-state thread waits forever for the SEP's "scrd" endpoint by name (and-+ * launchd's first AMFI sysctl waits on that thread). A plain registered service of that name.-+ */-+ scrd_done = true;-+ linux64_register_stand_in(this, OSTypeAlloc(IOService), "sep-endpoint,scrd");-+ /*-+ * No AES engine either: AppleImage4's finalize waits for an IOAESAccelerator service (it only waits, then-+ * releases it). The class is IOCryptoAcceleratorFamily's: an instance of it, registered, with no driver.-+ */-+ OSObject *aes = OSMetaClass::allocClassWithName("IOAESAccelerator");-+ IOService *aess = OSDynamicCast(IOService, aes);-+ if (aess) {-+ linux64_patch_aes_vtable(aess);-+ linux64_register_stand_in(this, aess, "IOAESAccelerator");-+ } else {-+ IOLog("LINUX64: cannot make an IOAESAccelerator (%p)\n", aes);-+ OSSafeReleaseNULL(aes);-+ }-+ }-+ if (!linux64_real_aks) {-+ IOLog("LINUX64: AKSKernelServices from the hosted stand-in\n");-+ return kIOReturnSuccess;-+ }-+ }-+ if (linux64_hook && linux64_real_aks && functionName->isEqualTo("AKSKernelServices")) {-+ _resources = waitForService(resourceMatching(functionName)); /* AppleVPKeyStore publishes it */-+ } else if (linux64_hook) {-+ /*-+ * LINUX64 (xnulinux): a hosted XNU has no providers for some platform functions (AppleKeyStore's, which AMFI-+ * waits for): wait a while, then report the function unsupported instead of blocking its caller forever.-+ */-+ mach_timespec_t t = { 2, 0 };-+ _resources = waitForService(resourceMatching(functionName), &t);-+ if (_resources == NULL) {-+ IOLog("LINUX64: platform function %s has no provider; unsupported\n", functionName->getCStringNoCopy());-+ }-+ } else {-+ _resources = waitForService(resourceMatching(functionName));-+ }- } else {- _resources = getResourceService();- }-@@ -2341,6 +2508,8 @@ IOPlatformDevice::getResources( void )- * the kernel with a suitable message.- *********************************************************************/--+extern "C" uintptr_t linux64_hook; /* LINUX64 (xnulinux) */-+- class IOPanicPlatform : IOPlatformExpert {- OSDeclareDefaultStructors(IOPanicPlatform);--@@ -2361,6 +2530,19 @@ IOPanicPlatform::start(IOService * provider)- platform_name = provider->getName();- }--+ /*-+ * LINUX64 (xnulinux): hosted without the platform kexts, the generic IOPlatformExpert stands in as-+ * the platform driver, so matching and gIOPlatform users can proceed.-+ */-+ if (linux64_hook != 0) {-+ IOLog("linux64: no platform driver for \"%s\", using the generic IOPlatformExpert\n", platform_name);-+ if (!IOPlatformExpert::start(provider)) {-+ return false;-+ }-+ registerService();-+ return true;-+ }-+- panic("Unable to find driver for this platform: \"%s\".",- platform_name);--diff --git a/iokit/Kernel/IOStartIOKit.cpp b/iokit/Kernel/IOStartIOKit.cpp-index f09a1dd..a819063 100644---- a/iokit/Kernel/IOStartIOKit.cpp-+++ b/iokit/Kernel/IOStartIOKit.cpp-@@ -78,7 +78,7 @@ IOKitInitializeTime( void )- t.tv_nsec = 0;-- // RTC is not present on this target--#ifndef BCM2837-+#if 0 /* LINUX64: hosted, the calendar comes from the host's wall clock (PEGetUTCTimeOfDay); no IORTC to wait 30 s for */- IOService::waitForService(- IOService::resourceMatching("IORTC"), &t );- #endif-diff --git a/iokit/bsddev/IOKitBSDInit.cpp b/iokit/bsddev/IOKitBSDInit.cpp-index ae82fc8..3fd837c 100644---- a/iokit/bsddev/IOKitBSDInit.cpp-+++ b/iokit/bsddev/IOKitBSDInit.cpp-@@ -65,6 +65,7 @@ extern "C" {-- extern dev_t mdevadd(int devid, uint64_t base, unsigned int size, int phys);- extern dev_t mdevlookup(int devid);-+extern dev_t mdevadd_host(void);- extern void mdevremoveall(void);- extern int mdevgetrange(int devid, uint64_t *base, uint64_t *size);- extern void di_root_ramfile(IORegistryEntry * entry);-@@ -859,6 +860,9 @@ IOFindBSDRoot( char * rootName, unsigned int rootNameSize,- }- regEntry->release(); /* Toss the entry */- }-+ if (mdevlookup(0) < 0) {-+ (void)mdevadd_host(); /* LINUX64 (xnulinux): no RAM disk, maybe a host-file disk */-+ }- }-- //-diff --git a/libkern/amfi/amfi.c b/libkern/amfi/amfi.c-index 58df36b..76d1a20 100644---- a/libkern/amfi/amfi.c-+++ b/libkern/amfi/amfi.c-@@ -12,6 +12,8 @@ amfi_interface_register(const amfi_t *mfi)- panic("AppleMobileFileIntegrity interface already set");- }- amfi = mfi;-+ extern void linux64_trust_cache_late_init(void); /* LINUX64 (xnulinux) */-+ linux64_trust_cache_late_init();- }-- void-diff --git a/libkern/crypto/corecrypto_rand.c b/libkern/crypto/corecrypto_rand.c-index d46815b..ccd2d84 100644---- a/libkern/crypto/corecrypto_rand.c-+++ b/libkern/crypto/corecrypto_rand.c-@@ -28,8 +28,42 @@-- #include <libkern/crypto/crypto_internal.h>- #include <corecrypto/ccrng.h>-+#include <string.h>- #include <libkern/crypto/rand.h>--+/*-+ * LINUX64 (xnulinux) PoC: without the corecrypto kext, g_crypto_funcs stays NULL. Until the hosted-+ * kernel has a crypto provider, fall back to a non-cryptographic xorshift generator seeded from-+ * early_random(). NOT FOR PRODUCTION.-+ */-+extern uint64_t early_random(void);-+static uint64_t linux64_rng_state[2];-+static uint64_t-+linux64_xorshift(uint64_t *st)-+{-+ if (st[0] == 0 && st[1] == 0) {-+ st[0] = early_random() | 1;-+ st[1] = early_random();-+ }-+ uint64_t s1 = st[0], s0 = st[1];-+ st[0] = s0;-+ s1 ^= s1 << 23;-+ st[1] = s1 ^ s0 ^ (s1 >> 17) ^ (s0 >> 26);-+ return st[1] + s0;-+}-+static void-+linux64_fill(uint64_t *st, void *out, size_t len)-+{-+ uint8_t *p = out;-+ while (len) {-+ uint64_t v = linux64_xorshift(st);-+ size_t n = len < sizeof(v) ? len : sizeof(v);-+ memcpy(p, &v, n);-+ p += n;-+ len -= n;-+ }-+}-+- int- cc_rand_generate(void *out, size_t outlen)- {-@@ -41,6 +75,9 @@ cc_rand_generate(void *out, size_t outlen)- if (rng_state != NULL) {- error = ccrng_generate(rng_state, outlen, out);- }-+ } else {-+ linux64_fill(linux64_rng_state, out, outlen);-+ error = 0;- }-- return error;-@@ -58,6 +95,10 @@ crypto_random_generate(- void *random,- size_t random_size)- {-+ if (!g_crypto_funcs) {-+ linux64_fill((uint64_t *)ctx, random, random_size);-+ return;-+ }- g_crypto_funcs->random_generate_fn(ctx, random, random_size);- }--@@ -67,12 +108,19 @@ crypto_random_uniform(- uint64_t bound,- uint64_t *random)- {-+ if (!g_crypto_funcs) {-+ *random = bound ? linux64_xorshift((uint64_t *)ctx) % bound : 0;-+ return;-+ }- g_crypto_funcs->random_uniform_fn(ctx, bound, random);- }-- size_t- crypto_random_kmem_ctx_size(void)- {-+ if (!g_crypto_funcs) {-+ return 2 * sizeof(uint64_t);-+ }- return g_crypto_funcs->random_kmem_ctx_size_fn();- }--@@ -80,5 +128,11 @@ void- crypto_random_kmem_init(- crypto_random_ctx_t ctx)- {-+ if (!g_crypto_funcs) {-+ uint64_t *st = (uint64_t *)ctx;-+ st[0] = early_random() | 1;-+ st[1] = early_random();-+ return;-+ }- g_crypto_funcs->random_kmem_init_fn(ctx);- }-diff --git a/libkern/img4/interface.c b/libkern/img4/interface.c-index 3863334..2fff0c8 100644---- a/libkern/img4/interface.c-+++ b/libkern/img4/interface.c-@@ -15,4 +15,6 @@ img4_interface_register(const img4_interface_t *i4)- panic("img4 interface already set");- }- img4if = i4;-+ extern void linux64_trust_cache_late_init(void); /* LINUX64 (xnulinux): whichever of img4/AMFI registers last */-+ linux64_trust_cache_late_init();- }-diff --git a/osfmk/arm/arm_init.c b/osfmk/arm/arm_init.c-index ac1713e..45b4d94 100644---- a/osfmk/arm/arm_init.c-+++ b/osfmk/arm/arm_init.c-@@ -228,6 +228,17 @@ extern vm_offset_t segLOWESTKC, segHIGHESTKC, segLOWESTROKC, segHIGHESTROKC;- extern vm_offset_t segLOWESTAuxKC, segHIGHESTAuxKC, segLOWESTROAuxKC, segHIGHESTROAuxKC;- extern vm_offset_t segLOWESTRXAuxKC, segHIGHESTRXAuxKC, segHIGHESTNLEAuxKC;--+/* LINUX64 (xnulinux): set by xnu.ko; see linux64_stage(). */-+uintptr_t linux64_hook;-+/* LINUX64: the current thread pointer (TPIDR_EL1 on Apple/BCM2837 boards). Single CPU for now. */-+unsigned long linux64_tpidr;-+/* LINUX64: the slide xnu.ko applied. */-+uintptr_t linux64_slide;-+/* LINUX64: XNU's virtual interrupt-enable state (hardware IRQs stay masked while hosted). */-+unsigned int linux64_vint;-+/* LINUX64: debug counters, read by xnu.ko's monitor thread on another CPU while XNU runs. */-+unsigned long linux64_dbg[16];-+- static void- arm_slide_rebase_and_sign_image(void)- {-@@ -285,10 +296,14 @@ arm_slide_rebase_and_sign_image(void)- * using hardcoded kernel link address- */- slide = (uintptr_t)k_mh - VM_KERNEL_LINK_ADDRESS;-+ if (linux64_hook) {-+ /* LINUX64: xnu.ko loaded, slid (load commands too) and signed the image already. */-+ slide = linux64_slide;-+ }-- /* rebase and sign jops */- static_kernelcache = &__thread_starts_sect_end[0] != &__thread_starts_sect_start[0];-- if (static_kernelcache) {-+ if (static_kernelcache && !linux64_hook) {- rebase_threaded_starts( &__thread_starts_sect_start[0],- &__thread_starts_sect_end[0],- (uintptr_t)k_mh, (uintptr_t)k_mh - slide, slide);-@@ -341,6 +356,60 @@ arm_auxkc_init(void *mh, void *base)- #endif /* defined(HAS_APPLE_PAC) */- }--+/*-+ * LINUX64 (xnulinux): when XNU is hosted inside Linux by xnu.ko, xnu.ko sets-+ * linux64_hook before calling arm_init. Each stage calls into the host, which-+ * may resume XNU or end the run. The call is a plain blr: the hook is host-+ * code, not an XNU function pointer.-+ */-+extern uintptr_t linux64_hook;-+-+static inline void-+linux64_stage(unsigned long stage)-+{-+ linux64_dbg[6] = stage;-+ if (linux64_hook) {-+ register unsigned long x0 __asm__("x0") = stage;-+ __asm__ volatile ("blr %1"-+ : "+r"(x0)-+ : "r"(linux64_hook)-+ : "x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9", "x10", "x11",-+ "x12", "x13", "x14", "x15", "x16", "x17", "x30", "cc", "memory");-+ }-+}-+-+void linux64_stage_ext(unsigned long stage);-+void-+linux64_stage_ext(unsigned long stage)-+{-+ linux64_stage(stage);-+}-+-+/* A stage that hands the host one argument (x1). */-+void linux64_stage_arg(unsigned long stage, unsigned long arg);-+void-+linux64_stage_arg(unsigned long stage, unsigned long arg)-+{-+ linux64_dbg[6] = stage;-+ if (linux64_hook) {-+ register unsigned long x0 __asm__("x0") = stage;-+ register unsigned long x1 __asm__("x1") = arg;-+ __asm__ volatile ("blr %2"-+ : "+r"(x0), "+r"(x1)-+ : "r"(linux64_hook)-+ : "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9", "x10", "x11",-+ "x12", "x13", "x14", "x15", "x16", "x17", "x30", "cc", "memory");-+ }-+}-+-+/* LINUX64: a failed assert() while hosted (see kern/assert.h); the host may end the run. */-+void-+linux64_assert_report(const char *file, int line, const char *expr)-+{-+ struct { const char *file; long line; const char *expr; } a = { file, line, expr };-+ linux64_stage_arg(997, (unsigned long)&a);-+}-+- /*- * Routine: arm_init- * Function: Runs on the boot CPU, once, on entry from iBoot.-@@ -361,6 +430,7 @@ arm_init(- port_crumb = 100;- arm_slide_rebase_and_sign_image();- port_crumb = 101;-+ linux64_stage(101);-- arm_static_if_init(args);- port_crumb = 102;-@@ -382,6 +452,7 @@ arm_init(-- PE_init_platform(FALSE, args); /* Get platform expert set up */- boot_progress_init();-+ linux64_stage(110);-- #if __arm64__- configure_timer_apple_regs();-@@ -475,6 +546,7 @@ arm_init(- #endif-- ml_parse_cpu_topology();-+ linux64_stage(120);--- boot_cpu_id = ml_get_boot_cpu_number();-@@ -511,15 +583,19 @@ arm_init(-- kernel_debug_string_early("kernel_startup_bootstrap");- kernel_startup_bootstrap();-+ linux64_stage(130);-- /*- * Initialize the timer callout world- */- timer_call_init();-+ linux64_stage(140);-- cpu_init();-+ linux64_stage(150);-- processor_bootstrap();-+ linux64_stage(160);-- if (PE_parse_boot_argn("maxmem", &maxmem, sizeof(maxmem))) {- xmaxmem = (uint64_t) maxmem * (1024 * 1024);-@@ -544,7 +620,9 @@ arm_init(- }- #endif /* SCHED_HYGIENE_DEBUG */--+ linux64_stage(170);- nanoseconds_to_absolutetime(XCALL_ACK_TIMEOUT_NS, &xcall_ack_timeout_abstime);-+ linux64_stage(175);-- #if HAS_BP_RET- PE_parse_boot_argn("bpret", &bp_ret, sizeof(bp_ret));-@@ -581,10 +659,12 @@ arm_init(- panic("%s: Unable to find 'dram-size' entry in the 'chosen' DT node", __FUNCTION__);- }--+ linux64_stage(180);- gDramBase = *dram_base;- gDramSize = *dram_size;- pmap_first_pnum = (ppnum_t)atop(gDramBase);--+ linux64_stage(199);- boot_progress_stage("arm_vm_init enter");- port_crumb = 1;- arm_vm_init(xmaxmem, args);-@@ -607,6 +687,7 @@ arm_init(- port_crumb = 5;- kernel_startup_initialize_upto(STARTUP_SUB_KPRINTF);- kprintf("kprintf initialized\n");-+ linux64_stage(300);-- serialmode = 0;- if (PE_parse_boot_argn("serial", &serialmode, sizeof(serialmode))) {-@@ -648,10 +729,12 @@ arm_init(- }- PE_create_console();- port_crumb = 6;-+ linux64_stage(360);-- /* setup console output */- PE_init_printf(FALSE);- port_crumb = 7;-+ linux64_stage(370);-- #if __arm64__- #if DEBUG-@@ -661,9 +744,11 @@ arm_init(-- cpu_machine_idle_init(TRUE);- port_crumb = 8;-+ linux64_stage(380);-- PE_init_platform(TRUE, &BootCpuData);- port_crumb = 9;-+ linux64_stage(390);-- /* Initialize the debug infrastructure system-wide and on the local core. */- pe_arm_debug_init_early(&BootCpuData);-@@ -676,6 +761,7 @@ arm_init(-- ml_map_cpu_pio();- port_crumb = 10;-+ linux64_stage(400);-- #if APPLE_ARM64_ARCH_FAMILY- configure_late_apple_regs(true);-@@ -685,6 +771,7 @@ arm_init(-- cpu_timebase_init(TRUE);- port_crumb = 11;-+ linux64_stage(410);-- #if KPERF- /* kptimer_curcpu_up() must be called after cpu_timebase_init */-@@ -693,6 +780,7 @@ arm_init(-- PE_init_cpu();- port_crumb = 12;-+ linux64_stage(420);- #if __arm64__- apt_msg_init();- apt_msg_init_cpu();-@@ -717,6 +805,7 @@ arm_init(- */- __stack_chk_guard &= ~(0xFFULL << 8);- port_crumb = 13;-+ linux64_stage(490);- machine_startup(args);- }--diff --git a/osfmk/arm/cpu_data.h b/osfmk/arm/cpu_data.h-index 743117b..9dc298b 100644---- a/osfmk/arm/cpu_data.h-+++ b/osfmk/arm/cpu_data.h-@@ -61,8 +61,9 @@ current_thread_fast(void)- *- * and ignores the "attribute const", so do it the "dumb" way.- */-- unsigned long result;-- __asm__ ("mrs %0, TPIDR_EL1" : "=r" (result));-+ /* LINUX64 (xnulinux): TPIDR_EL1 belongs to Linux; the thread pointer lives in memory. */-+ extern unsigned long linux64_tpidr;-+ unsigned long result = linux64_tpidr;- return __unsafe_forge_single(thread_t, result);- #else- // TPIDRPRW-@@ -100,8 +101,8 @@ current_thread_volatile(void)- * The mrc used for arm32 should be treated as volatile however.- */- #if defined(__arm64__)-- unsigned long result;-- __asm__ volatile ("mrs %0, TPIDR_EL1" : "=r" (result));-+ extern unsigned long linux64_tpidr;-+ unsigned long result = *(volatile unsigned long *)&linux64_tpidr;- return __unsafe_forge_single(thread_t, result);- #else- // TPIDRPRW-@@ -114,7 +115,16 @@ current_thread_volatile(void)- static inline vm_offset_t- exception_stack_pointer(void)- {-- vm_offset_t result = 0;-+ vm_offset_t result = 0, spsel;-+ /*-+ * LINUX64 (xnulinux): hosted XNU runs on Linux's SP_EL1 stack, and SP_EL0 is-+ * Linux's `current`; never flip SPSel. When already on SP_EL1, sp is the answer.-+ */-+ __asm__ volatile ("mrs %0, SPSel" : "=r" (spsel));-+ if (spsel & 1) {-+ __asm__ volatile ("mov %0, sp" : "=r" (result));-+ return result;-+ }- __asm__ volatile (- "msr SPSel, #1 \n"- "mov %0, sp \n"-diff --git a/osfmk/arm/machine_routines_common.c b/osfmk/arm/machine_routines_common.c-index b65f76c..b0692dd 100644---- a/osfmk/arm/machine_routines_common.c-+++ b/osfmk/arm/machine_routines_common.c-@@ -1094,6 +1094,49 @@ ml_set_interrupts_enabled_with_debug(boolean_t enable, boolean_t __unused debug)-- thread = current_thread();--+ {-+ /*-+ * LINUX64 (xnulinux): XNU runs on its own kernel stacks, where Linux cannot take an interrupt-+ * (its entry code treats a foreign stack as overflow). Keep IRQs masked in hardware and track-+ * XNU's view in linux64_vint; timer "interrupts" are delivered from cpu_idle.-+ */-+ extern uintptr_t linux64_hook;-+ extern unsigned int linux64_vint;-+ if (linux64_hook) {-+ boolean_t was = linux64_vint ? TRUE : FALSE;-+ if (enable && !was) {-+ /*-+ * Kernel code that runs long without going to user space or idle never sees a host interrupt-+ * (hardware IRQs stay masked in XNU's kernel), which stalls Linux (RCU) and stops XNU's own-+ * clock. Where XNU would take a pending interrupt, re-enabling interrupts, let Linux run its-+ * interrupts every 2 ms and deliver XNU's timer if it is due, as the IRQ path does.-+ */-+ static uint64_t linux64_last_kyield;-+ uint64_t now = mach_absolute_time();-+ if (now - linux64_last_kyield > 48000 && thread->machine.CpuDatap->cpu_int_state == NULL) {-+ extern void linux64_stage_arg(unsigned long, unsigned long);-+ extern void rtclock_intr(unsigned int);-+ cpu_data_t *cdp = thread->machine.CpuDatap;-+ linux64_last_kyield = now;-+ linux64_stage_arg(811, 1);-+ if (cdp->rtcPop != 0 && cdp->rtcPop != 0xFFFFFFFFFFFFFFFFULL && mach_absolute_time() >= cdp->rtcPop) {-+ cdp->cpu_decrementer = -1;-+ rtclock_intr(FALSE);-+ }-+ }-+ if (get_preemption_level() == 0) {-+ while (thread->machine.CpuDatap->cpu_pending_ast & AST_URGENT) {-+ ast_taken_kernel();-+ }-+ }-+ linux64_vint = 1;-+ } else if (!enable) {-+ linux64_vint = 0;-+ }-+ return was;-+ }-+ }-+- state = __builtin_arm_rsr("DAIF");-- if (__improbable(!(state & DAIF_DEBUGF))) {-@@ -1384,6 +1427,13 @@ ml_wait_max_cpus(void)- {- assert(lockdown_done);- lck_mtx_lock(&max_cpus_lock);-+ {-+ /* LINUX64 (xnulinux): hosted without the CPU kext that calls ml_set_max_cpus(); one CPU, known now. */-+ extern uintptr_t linux64_hook;-+ if (linux64_hook) {-+ max_cpus_initialized = MAX_CPUS_SET;-+ }-+ }- while (max_cpus_initialized != MAX_CPUS_SET) {- max_cpus_initialized = MAX_CPUS_WAIT;- lck_mtx_sleep(&max_cpus_lock, LCK_SLEEP_DEFAULT, &max_cpus_initialized, THREAD_UNINT);-diff --git a/osfmk/arm/pmap/pmap.c b/osfmk/arm/pmap/pmap.c-index 79d0bc1..43e4474 100644---- a/osfmk/arm/pmap/pmap.c-+++ b/osfmk/arm/pmap/pmap.c-@@ -327,6 +327,32 @@ const struct page_table_attr * const native_pt_attr = &pmap_pt_attr_16k;- const struct page_table_attr * const native_pt_attr = &pmap_pt_attr_4k;- #endif /* !__ARM_16K_PG__ */--+#if !__ARM_16K_PG__ && !ARM_PARAMETERIZED_PMAP-+/*-+ * LINUX64 (xnulinux): user pmaps of a 4 KiB build walk from level 0 and span the 47 bits TTBR0 runs with (T0SZ_HW), as a macOS-+ * userland expects (ThreadSanitizer's shadow, nano malloc and MACH_VM_MAX_ADDRESS all sit above the 39 bits a level-1 root reaches).-+ * The kernel pmap keeps pmap_pt_attr_4k (TTBR1, level-1 root).-+ */-+const struct page_table_attr pmap_pt_attr_4k_user = {-+ .pta_level_info = pmap_table_level_info_4k,-+ .pta_root_level = PMAP_TT_L0_LEVEL,-+ .pta_commpage_level = PMAP_TT_L1_LEVEL,-+ .pta_max_level = PMAP_TT_L3_LEVEL,-+ .pta_ops = &native_pt_ops,-+ .ap_ro = ARM_PTE_AP(AP_RORO),-+ .ap_rw = ARM_PTE_AP(AP_RWRW),-+ .ap_rona = ARM_PTE_AP(AP_RONA),-+ .ap_rwna = ARM_PTE_AP(AP_RWNA),-+ .ap_xn = ARM_PTE_PNX | ARM_PTE_NX,-+ .ap_x = ARM_PTE_PNX,-+ .pta_page_size = 4096,-+ .pta_pagezero_size = 4096,-+ .pta_page_shift = 12,-+ .pta_va_valid_mask = (1ULL << (64 - T0SZ_HW)) - 1,-+};-+const struct page_table_attr * const user_pt_attr = &pmap_pt_attr_4k_user;-+#endif /* !__ARM_16K_PG__ && !ARM_PARAMETERIZED_PMAP */-+-- #if DEVELOPMENT || DEBUG- int vm_footprint_suspend_allowed = 1;-@@ -520,7 +546,7 @@ _Static_assert((ARM64_MAX_OFFSET_DEVICE_LARGE > ARM64_MIN_MAX_ADDRESS) && (ARM64- _Static_assert((ARM64_MAX_OFFSET_DEVICE_SMALL > ARM64_MIN_MAX_ADDRESS) && (ARM64_MAX_OFFSET_DEVICE_SMALL <= MACH_VM_MAX_ADDRESS),- "Small device address space size outside allowable range");---# ifdef XNU_TARGET_OS_OSX-+# if defined(XNU_TARGET_OS_OSX) || !__ARM_16K_PG__ /* LINUX64: macOS userland gets the whole 47-bit space by default */- SECURITY_READ_ONLY_LATE(vm_map_offset_t) arm64_pmap_max_offset_default = MACH_VM_MAX_ADDRESS;- # else- SECURITY_READ_ONLY_LATE(vm_map_offset_t) arm64_pmap_max_offset_default = 0x0;-@@ -2254,6 +2280,7 @@ pmap_bootstrap(- lck_grp_init(&pmap_lck_grp, "pmap", LCK_GRP_ATTR_NULL);- lck_attr_setdefault(&pmap_lck_rw_attr);- pmap_lck_rw_attr.lck_attr_val |= LCK_ATTR_RW_NO_SLEEP;-+ { extern void linux64_stage_ext(unsigned long); linux64_stage_ext(7001); }-- #if XNU_MONITOR- #if (DEVELOPMENT || DEBUG) || CONFIG_CSR_FROM_DT-@@ -2305,8 +2332,10 @@ pmap_bootstrap(- kernel_pmap->sw_asid = 0;-- pmap_lock_init(kernel_pmap);-+ { extern void linux64_stage_ext(unsigned long); linux64_stage_ext(7002); }-- pmap_max_asids = pmap_compute_max_asids();-+ { extern void linux64_stage_ext(unsigned long); linux64_stage_ext(7003); }- #if HAS_16BIT_ASID- asid_chunk_size = MAX_HW_ASIDS;- #else-@@ -2336,6 +2365,7 @@ pmap_bootstrap(- * space for these data structures.- */- pmap_data_bootstrap();-+ { extern void linux64_stage_ext(unsigned long); linux64_stage_ext(7004); }-- /**- * Bootstrap any necessary SART data structures and values needed from the device tree.-@@ -2356,6 +2386,7 @@ pmap_bootstrap(- avail_start = round_page(avail_start + asid_table_size);-- memset((char *)phystokv(pmap_struct_start), 0, avail_start - pmap_struct_start);-+ { extern void linux64_stage_ext(unsigned long); linux64_stage_ext(7005); }-- vm_first_phys = gPhysBase;- vm_last_phys = trunc_page(avail_end);-@@ -2373,6 +2404,7 @@ pmap_bootstrap(- virtual_space_end = VM_MAX_KERNEL_ADDRESS;-- bitmap_full(&asid_bitmap[0], pmap_max_asids);-+ { extern void linux64_stage_ext(unsigned long); linux64_stage_ext(7006); }- #if !HAS_16BIT_ASID- bitmap_full(&asid_plru_bitmap[0], MAX_HW_ASIDS);- // Clear the highest-order bit, which corresponds to MAX_HW_ASIDS + 1-@@ -2983,7 +3015,8 @@ pmap_root_alloc_size(pmap_t pmap)- const pt_attr_t * const pt_attr = pmap_get_pt_attr(pmap);- unsigned int root_level = pt_attr_root_level(pt_attr);- const uint64_t index = pt_attr_va_valid_mask(pt_attr);-- return ((index >> pt_attr_ln_shift(pt_attr, root_level)) + 1) * sizeof(tt_entry_t);-+ vm_size_t size = ((index >> pt_attr_ln_shift(pt_attr, root_level)) + 1) * sizeof(tt_entry_t);-+ return (size < PMAP_ROOT_ALLOC_SIZE) ? PMAP_ROOT_ALLOC_SIZE : size; /* LINUX64: a level-0 root fills half a page */- }---@@ -3108,6 +3141,16 @@ pmap_create_options_internal(- }-- p->ttep = ml_static_vtop((vm_offset_t)p->tte);-+ if (pt_attr_root_level(pmap_get_pt_attr(p)) == PMAP_TT_L0_LEVEL) {-+ /* LINUX64: the root already is the level-0 table TTBR0 walks from */-+ p->hw_tte = p->tte;-+ p->hw_ttep = p->ttep;-+ for (i = 0; i < tte_index_max; i++) {-+ p->tte[i] = ARM_TTE_TYPE_FAULT;-+ }-+ FLUSH_PTE();-+ goto root_ready;-+ }- p->hw_tte = pmap_tt1_allocate(p, pmap_root_alloc_size(p), 0);- if (!p->hw_tte) {- pmap_tt1_deallocate(p, p->tte, pmap_root_alloc_size(p), 0);-@@ -3129,6 +3172,7 @@ pmap_create_options_internal(- p->hw_tte[0] = (p->ttep & ARM_TTE_TABLE_MASK) | ARM_TTE_TYPE_TABLE | ARM_TTE_VALID;-- FLUSH_PTE();-+root_ready:-- /*- * initialize the rest of the structure-@@ -3406,6 +3450,10 @@ pmap_destroy_internal(----+ if (pmap->hw_tte == pmap->tte) {-+ pmap->hw_tte = (tt_entry_t *) NULL; /* LINUX64: a level-0 root is both; free it once, below */-+ pmap->hw_ttep = 0;-+ }- if (pmap->tte) {- pmap_tt1_deallocate(pmap, pmap->tte, pmap_root_alloc_size(pmap), 0);- pmap->tte = (tt_entry_t *) NULL;-@@ -12980,6 +13028,8 @@ pmap_user_va_bits(pmap_t pmap __unused)- #if __ARM_MIXED_PAGE_SIZE__- uint64_t tcr_value = pmap_get_pt_attr(pmap)->pta_tcr_value;- return 64 - ((tcr_value >> TCR_T0SZ_SHIFT) & TCR_TSZ_MASK);-+#elif !__ARM_16K_PG__ && !ARM_PARAMETERIZED_PMAP-+ return 64 - T0SZ_HW; /* LINUX64: user pmaps walk from level 0 (pmap_pt_attr_4k_user) */- #else- return 64 - T0SZ_BOOT;- #endif-@@ -15385,3 +15435,31 @@ native_pmap_user_mappings(ppnum_t ppnum, void **first_pmap, uint64_t *first_va,- pvh_unlock(pai);- return count;- }-+-+/* LINUX64 debug: the leaf PTE that maps va in pmap (0 if none) */-+uint64_t linux64_pte_value(pmap_t pmap, vm_map_address_t va);-+uint64_t-+linux64_pte_value(pmap_t pmap, vm_map_address_t va)-+{-+ pt_entry_t *ptep = pmap_pte(pmap, va & ~(vm_map_address_t)PAGE_MASK);-+ return ptep ? (uint64_t)*ptep : 0;-+}-+-+/* LINUX64 debug: walk a 4K, 4-level user table from a TTBR0 value as the hardware would (the leaf, or 0) */-+uint64_t linux64_pte_walk(uint64_t ttbr, vm_map_address_t va);-+uint64_t-+linux64_pte_walk(uint64_t ttbr, vm_map_address_t va)-+{-+ uint64_t table = ttbr & 0x0000fffffffff000ULL, d = 0;-+ for (int level = 0; level <= 3; level++) {-+ if (!pa_valid(table)) {-+ return 0xdead0000ULL | (uint64_t)level;-+ }-+ d = ((volatile uint64_t *)phystokv(table))[(va >> (39 - 9 * level)) & 511];-+ if ((d & 3) != 3 || level == 3) {-+ break;-+ }-+ table = d & 0x0000fffffffff000ULL;-+ }-+ return d;-+}-diff --git a/osfmk/arm/pmap/pmap_pt_geometry.h b/osfmk/arm/pmap/pmap_pt_geometry.h-index fc64830..aaff3fb 100644---- a/osfmk/arm/pmap/pmap_pt_geometry.h-+++ b/osfmk/arm/pmap/pmap_pt_geometry.h-@@ -169,7 +169,14 @@ extern const struct page_table_ops native_pt_ops;- #else /* ARM_PARAMETERIZED_PMAP */-- /* The page table attributes are fixed (to allow for const propagation) */-+#if !__ARM_16K_PG__-+/* LINUX64 (xnulinux): user pmaps walk from level 0 over 47 bits, the kernel pmap from level 1 (pmap.c, pmap_pt_attr_4k_user) */-+extern const struct page_table_attr * const user_pt_attr;-+extern const pmap_t kernel_pmap; /* as in vm/pmap.h, which not every includer of this header has */-+#define pmap_get_pt_attr(pmap) ((pmap) == kernel_pmap ? native_pt_attr : user_pt_attr)-+#else- #define pmap_get_pt_attr(pmap) (native_pt_attr)-+#endif- #define pmap_get_pt_ops(pmap) (&native_pt_ops)-- #endif /* ARM_PARAMETERIZED_PMAP */-diff --git a/osfmk/arm/rtclock.c b/osfmk/arm/rtclock.c-index a17a07d..6136425 100644---- a/osfmk/arm/rtclock.c-+++ b/osfmk/arm/rtclock.c-@@ -327,6 +327,7 @@ rtclock_intr(__unused unsigned int is_user_context)- struct arm_saved_state * regs;- unsigned int user_mode;- uintptr_t pc;-+ { extern unsigned long linux64_dbg[16]; linux64_dbg[7]++; } /* LINUX64 debug */-- #if XNU_NATIVE_DWC3_CONSOLE- extern void unixnu_dwc3_poll(void);-diff --git a/osfmk/arm64/arm_vm_init.c b/osfmk/arm64/arm_vm_init.c-index f7f387e..c239600 100644---- a/osfmk/arm64/arm_vm_init.c-+++ b/osfmk/arm64/arm_vm_init.c-@@ -1089,7 +1089,9 @@ arm_vm_page_granular_helper(vm_offset_t start, vm_offset_t _end, vm_offset_t va,- /*- * Set the 'guarded page' flag to enable ARM BTI enforcement.- */-- if (guarded) {-+ extern uintptr_t linux64_hook;-+ /* LINUX64: Linux enables SCTLR_EL1.BT1, and this kernel is not built with BTI landing pads. */-+ if (guarded && !linux64_hook) {- ptmp |= ARM_PTE_GP;- }- #endif /* BTI_ENFORCED */-@@ -1404,16 +1406,20 @@ arm_vm_prot_init(__unused boot_args * args)- * it and apply fixups (after we're off the bootstrap translation- * tables).- */-+ { extern void linux64_stage_ext(unsigned long); linux64_stage_ext(5001); }- arm_vm_page_granular_RWNX(auxkc_base, auxKC_range->length, 0);-- noAuxKC:- /* Map coalesced kext TEXT segment RWNX for now */-+ { extern void linux64_stage_ext(unsigned long); linux64_stage_ext(5002); }- arm_vm_page_granular_RWNX(segPRELINKTEXTB, segSizePRELINKTEXT, ARM64_GRANULE_ALLOW_BLOCK); // Refined in OSKext::readPrelinkedExtensions-- /* Map coalesced kext DATA_CONST segment RWNX (could be empty) */-+ { extern void linux64_stage_ext(unsigned long); linux64_stage_ext(5003); }- arm_vm_page_granular_RWNX(segPLKDATACONSTB, segSizePLKDATACONST, ARM64_GRANULE_ALLOW_BLOCK); // Refined in OSKext::readPrelinkedExtensions-- /* Map coalesced kext TEXT_EXEC segment RX (could be empty) */-+ { extern void linux64_stage_ext(unsigned long); linux64_stage_ext(5004); }- arm_vm_page_granular_ROX(segPLKTEXTEXECB, segSizePLKTEXTEXEC, ARM64_GRANULE_ALLOW_BLOCK | ARM64_GRANULE_ALLOW_HINT, ARM64_PAGE_GUARDED); // Refined in OSKext::readPrelinkedExtensions-- /* if new segments not present, set space between PRELINK_TEXT and xnu TEXT to RWNX-@@ -1443,48 +1449,68 @@ noAuxKC:- *- * TEXT segment contains mach headers and other non-executable data. This will become RONX later.- */-+ { extern void linux64_stage_ext(unsigned long); linux64_stage_ext(5005); }- arm_vm_page_granular_RNX(segTEXTB, segSizeTEXT, ARM64_GRANULE_ALLOW_BLOCK | ARM64_GRANULE_ALLOW_HINT);-- /* Can DATACONST start out and stay RNX?- * NO, stuff in this segment gets modified during startup (viz. mac_policy_init()/mac_policy_list)- * Make RNX in prot_finalize- */-+ { extern void linux64_stage_ext(unsigned long); linux64_stage_ext(5006); }- arm_vm_page_granular_RWNX(segDATACONSTB, segSizeDATACONST, ARM64_GRANULE_ALLOW_BLOCK);--+ { extern void linux64_stage_ext(unsigned long); linux64_stage_ext(5007); }- arm_vm_page_granular_ROX(segTEXTEXECB, segSizeTEXTEXEC, ARM64_GRANULE_ALLOW_BLOCK | ARM64_GRANULE_ALLOW_HINT, ARM64_PAGE_GUARDED);-- #if XNU_MONITOR-+ { extern void linux64_stage_ext(unsigned long); linux64_stage_ext(5008); }- arm_vm_page_granular_ROX(segPPLTEXTB, segSizePPLTEXT, ARM64_GRANULE_ALLOW_BLOCK | ARM64_GRANULE_ALLOW_HINT, ARM64_PAGE_UNGUARDED);-+ { extern void linux64_stage_ext(unsigned long); linux64_stage_ext(5009); }- arm_vm_page_granular_ROX(segPPLTRAMPB, segSizePPLTRAMP, ARM64_GRANULE_ALLOW_BLOCK | ARM64_GRANULE_ALLOW_HINT, ARM64_PAGE_UNGUARDED);-+ { extern void linux64_stage_ext(unsigned long); linux64_stage_ext(5010); }- arm_vm_page_granular_RNX(segPPLDATACONSTB, segSizePPLDATACONST, ARM64_GRANULE_ALLOW_BLOCK | ARM64_GRANULE_ALLOW_HINT);- #endif-- /* DATA segment will remain RWNX */-+ { extern void linux64_stage_ext(unsigned long); linux64_stage_ext(5011); }- arm_vm_page_granular_RWNX(segDATAB, segSizeDATA, ARM64_GRANULE_ALLOW_BLOCK | ARM64_GRANULE_ALLOW_HINT);- #if XNU_MONITOR-+ { extern void linux64_stage_ext(unsigned long); linux64_stage_ext(5012); }- arm_vm_page_granular_RWNX(segPPLDATAB, segSizePPLDATA, ARM64_GRANULE_ALLOW_BLOCK | ARM64_GRANULE_ALLOW_HINT);- #endif--+ { extern void linux64_stage_ext(unsigned long); linux64_stage_ext(5013); }- arm_vm_page_granular_RWNX(segHIBDATAB, segSizeHIBDATA, ARM64_GRANULE_ALLOW_BLOCK | ARM64_GRANULE_ALLOW_HINT);--+ { extern void linux64_stage_ext(unsigned long); linux64_stage_ext(5014); }- arm_vm_page_granular_RWNX(segBOOTDATAB, segSizeBOOTDATA, 0);-+ { extern void linux64_stage_ext(unsigned long); linux64_stage_ext(5015); }- arm_vm_page_granular_RNX((vm_offset_t)&intstack_low_guard, PAGE_MAX_SIZE, 0);-+ { extern void linux64_stage_ext(unsigned long); linux64_stage_ext(5016); }- arm_vm_page_granular_RNX((vm_offset_t)&intstack_high_guard, PAGE_MAX_SIZE, 0);-+ { extern void linux64_stage_ext(unsigned long); linux64_stage_ext(5017); }- arm_vm_page_granular_RNX((vm_offset_t)&excepstack_high_guard, PAGE_MAX_SIZE, 0);--+ { extern void linux64_stage_ext(unsigned long); linux64_stage_ext(5018); }- arm_vm_page_granular_ROX(segKLDB, segSizeKLD, 0, ARM64_PAGE_GUARDED);-+ { extern void linux64_stage_ext(unsigned long); linux64_stage_ext(5019); }- arm_vm_page_granular_RNX(segKLDDATAB, segSizeKLDDATA, 0);-+ { extern void linux64_stage_ext(unsigned long); linux64_stage_ext(5020); }- arm_vm_page_granular_RWNX(segLINKB, segSizeLINK, 0);-+ { extern void linux64_stage_ext(unsigned long); linux64_stage_ext(5021); }- arm_vm_page_granular_RWNX(segPLKLINKEDITB, segSizePLKLINKEDIT, 0); // Coalesced kext LINKEDIT segment-+ { extern void linux64_stage_ext(unsigned long); linux64_stage_ext(5022); }- arm_vm_page_granular_ROX(segLASTB, segSizeLAST, ARM64_GRANULE_ALLOW_BLOCK, ARM64_PAGE_GUARDED); // __LAST may be empty, but we cannot assume this- if (segLASTDATACONSTB) {- arm_vm_page_granular_RWNX(segLASTDATACONSTB, segSizeLASTDATACONST, ARM64_GRANULE_ALLOW_BLOCK); // __LASTDATA_CONST may be empty, but we cannot assume this- }-+ { extern void linux64_stage_ext(unsigned long); linux64_stage_ext(5023); }- arm_vm_page_granular_RWNX(segPRELINKDATAB, segSizePRELINKDATA, ARM64_GRANULE_ALLOW_BLOCK | ARM64_GRANULE_ALLOW_HINT); // Prelink __DATA for kexts (RW data)-- if (segSizePLKLLVMCOV > 0) {- arm_vm_page_granular_RWNX(segPLKLLVMCOVB, segSizePLKLLVMCOV, ARM64_GRANULE_ALLOW_BLOCK | ARM64_GRANULE_ALLOW_HINT); // LLVM code coverage data- }-+ { extern void linux64_stage_ext(unsigned long); linux64_stage_ext(5024); }- arm_vm_page_granular_RWNX(segPRELINKINFOB, segSizePRELINKINFO, 0); /* PreLinkInfoDictionary */-- /* Record the bounds of the kernelcache. */-@@ -1883,6 +1909,7 @@ arm_vm_init(uint64_t memory_size, boot_args * args)-- // Slide the physical aperture to a random page-aligned location within the slide range- port_crumb = 50;-+ { extern void linux64_stage_ext(unsigned long); linux64_stage_ext(201); }- uint64_t physmap_slide = early_random() & ARM64_PHYSMAP_SLIDE_MASK & ~((uint64_t)PAGE_MASK);- assert(physmap_slide < ARM64_PHYSMAP_SLIDE_RANGE);- port_crumb = 51;-@@ -1937,6 +1964,7 @@ arm_vm_init(uint64_t memory_size, boot_args * args)- boot_tte = (tt_entry_t *)&bootstrap_pagetables;- boot_ttep = kvtophys((vm_offset_t)boot_tte);- port_crumb = 52;-+ { extern void linux64_stage_ext(unsigned long); linux64_stage_ext(202); }-- #if DEVELOPMENT || DEBUG- /* Sanity check - assert that BOOTSTRAP_TABLE_SIZE is sufficiently-large to-@@ -1972,6 +2000,7 @@ arm_vm_init(uint64_t memory_size, boot_args * args)- invalid_tte = (tt_entry_t *)alloc_ptpage(TRUE);- invalid_ttep = kvtophys((vm_offset_t)invalid_tte);- port_crumb = 53;-+ { extern void linux64_stage_ext(unsigned long); linux64_stage_ext(203); }- bzero(invalid_tte, ARM_PGBYTES);-- /*-@@ -1998,6 +2027,7 @@ arm_vm_init(uint64_t memory_size, boot_args * args)- */- init_ptpages(cpu_tte, gVirtBase, dynamic_memory_begin, TRUE, ARM_TTE_TABLE_AP(ARM_TTE_TABLE_AP_USER_NA));- port_crumb = 32;-+ { extern void linux64_stage_ext(unsigned long); linux64_stage_ext(204); }-- #if defined(ARM_LARGE_MEMORY)- /*-@@ -2117,6 +2147,7 @@ arm_vm_init(uint64_t memory_size, boot_args * args)-- vm_set_page_size();- port_crumb = 35;-+ { extern void linux64_stage_ext(unsigned long); linux64_stage_ext(205); }-- vm_kernel_base = segTEXTB;- vm_kernel_top = (vm_offset_t) &last_kernel_symbol;-@@ -2152,6 +2183,7 @@ arm_vm_init(uint64_t memory_size, boot_args * args)-- arm_vm_prot_init(args);- port_crumb = 36;-+ { extern void linux64_stage_ext(unsigned long); linux64_stage_ext(206); }-- /*- * Initialize the page tables for the low globals:-@@ -2183,6 +2215,7 @@ arm_vm_init(uint64_t memory_size, boot_args * args)- */- init_ptpages(cpu_tte, dynamic_memory_begin, VM_MAX_KERNEL_ADDRESS, TRUE, ARM_DYNAMIC_TABLE_XN | ARM_TTE_TABLE_AP(ARM_TTE_TABLE_AP_USER_NA));- port_crumb = 37;-+ { extern void linux64_stage_ext(unsigned long); linux64_stage_ext(207); }- #endif-- #if KASAN-@@ -2194,21 +2227,42 @@ arm_vm_init(uint64_t memory_size, boot_args * args)-- arm_vm_physmap_init(args);- port_crumb = 38;-- set_mmu_ttb_alternate(cpu_ttep & TTBR_BADDR_MASK);-+ { extern void linux64_stage_ext(unsigned long); linux64_stage_ext(208); }-+ {-+ extern uintptr_t linux64_hook;-+ extern void linux64_stage_arg(unsigned long, unsigned long);-+ if (linux64_hook) {-+ /*-+ * LINUX64 (xnulinux): TTBR1 is Linux's. The host installs XNU's kernel L1 entries-+ * (the kernel VA range only) into Linux's top-level L1 table; TTBR0 stays Linux's.-+ */-+ linux64_stage_arg(210, (unsigned long)cpu_tte);-+ } else {-+ set_mmu_ttb_alternate(cpu_ttep & TTBR_BADDR_MASK);-+ }-+ }- port_crumb = 39;-+ { extern void linux64_stage_ext(unsigned long); linux64_stage_ext(6001); }-- #if XNU_MONITOR- ml_enable_monitor();- #endif--- set_mmu_ttb(invalid_ttep & TTBR_BADDR_MASK);-+ {-+ extern uintptr_t linux64_hook;-+ if (!linux64_hook) {-+ set_mmu_ttb(invalid_ttep & TTBR_BADDR_MASK);-+ }-+ }-- flush_mmu_tlb();- port_crumb = 40;-+ { extern void linux64_stage_ext(unsigned long); linux64_stage_ext(6002); }- kva_active = TRUE;- // global table pointers may need to be different due to physical aperture remapping- cpu_tte = (tt_entry_t*)(phystokv(cpu_ttep));- invalid_tte = (tt_entry_t*)(phystokv(invalid_ttep));-+ { extern void linux64_stage_ext(unsigned long); linux64_stage_ext(6003); }-- // From here on out, we're off the bootstrap translation tables.--@@ -2240,6 +2294,7 @@ arm_vm_init(uint64_t memory_size, boot_args * args)-- /* Calculate the number of pages that belong to the kernelcache. */- vm_page_kernelcache_count = (unsigned int) (atop_64(arm_vm_kernelcache_phys_end - arm_vm_kernelcache_phys_start));-+ { extern void linux64_stage_ext(unsigned long); linux64_stage_ext(6004); }-- if (arm_vm_auxkc_init()) {- if (segLOWESTROAuxKC < segLOWESTRO) {-@@ -2258,6 +2313,7 @@ arm_vm_init(uint64_t memory_size, boot_args * args)- }-- sane_size = mem_size - (avail_start - gPhysBase);-+ { extern void linux64_stage_ext(unsigned long); linux64_stage_ext(6005); }- max_mem = mem_size;- vm_kernel_slid_base = segLOWESTTEXT;- // vm_kernel_slide is set by arm_init()->arm_slide_rebase_and_sign_image()-@@ -2267,13 +2323,20 @@ arm_vm_init(uint64_t memory_size, boot_args * args)- vm_kernel_etext = segTEXTEXECB + segSizeTEXTEXEC;- vm_kernel_slid_top = vm_slinkedit;- } else {-- assert(segDATACONSTB == segTEXTB + segSizeTEXT);-- assert(segTEXTEXECB == segDATACONSTB + segSizeDATACONST);-- vm_kernel_etext = segTEXTB + segSizeTEXT + segSizeDATACONST + segSizeTEXTEXEC;-+ extern uintptr_t linux64_hook;-+ if (linux64_hook) {-+ /* LINUX64: this kernel is linked with the KC segment layout (k27): segments are not adjacent. */-+ vm_kernel_etext = segTEXTEXECB + segSizeTEXTEXEC;-+ } else {-+ assert(segDATACONSTB == segTEXTB + segSizeTEXT);-+ assert(segTEXTEXECB == segDATACONSTB + segSizeDATACONST);-+ vm_kernel_etext = segTEXTB + segSizeTEXT + segSizeDATACONST + segSizeTEXTEXEC;-+ }- vm_kernel_slid_top = vm_prelink_einfo;- }-- dynamic_memory_begin = ROUND_TWIG(dynamic_memory_begin);-+ { extern void linux64_stage_ext(unsigned long); linux64_stage_ext(6006); }- #if (defined(KERNEL_INTEGRITY_CTRR) || defined(KERNEL_INTEGRITY_PV_CTRR)) && defined(CONFIG_XNUPOST)- // reserve a 32MB region without permission overrides to use later for a CTRR unit test- {-@@ -2301,8 +2364,10 @@ arm_vm_init(uint64_t memory_size, boot_args * args)- }- #endif- #endif-+ { extern void linux64_stage_ext(unsigned long); linux64_stage_ext(215); }- pmap_bootstrap(dynamic_memory_begin);- port_crumb = 41;-+ { extern void linux64_stage_ext(unsigned long); linux64_stage_ext(220); }-- disable_preemption();--@@ -2431,6 +2496,7 @@ arm_vm_init(uint64_t memory_size, boot_args * args)- patch_low_glo_static_region(args->topOfKernelData, avail_start - args->topOfKernelData);- enable_preemption();- port_crumb = 43;-+ { extern void linux64_stage_ext(unsigned long); linux64_stage_ext(230); }- }-- /*-diff --git a/osfmk/arm64/asm.h b/osfmk/arm64/asm.h-index 84deb3f..767b8f8 100644---- a/osfmk/arm64/asm.h-+++ b/osfmk/arm64/asm.h-@@ -135,7 +135,8 @@- .endmacro-- .macro READ_THREAD-- mrs $0, TPIDR_EL1-+ adrp $0, _linux64_tpidr@PAGE-+ ldr $0, [$0, _linux64_tpidr@PAGEOFF]- .endmacro-- .macro BRANCH_EXTERN-diff --git a/osfmk/arm64/cpu.c b/osfmk/arm64/cpu.c-index d10d7a1..3ba7323 100644---- a/osfmk/arm64/cpu.c-+++ b/osfmk/arm64/cpu.c-@@ -100,6 +100,7 @@ extern void __attribute__((noreturn)) arm64_prepare_for_sleep(boolean_t deep_sle- extern void __attribute__((noreturn)) arm64_prepare_for_sleep(boolean_t deep_sleep);- #endif- extern void arm64_force_wfi_clock_gate(void);-+extern void rtclock_intr(unsigned int);- #if defined(APPLETYPHOON)- // <rdar://problem/15827409>- extern void typhoon_prepare_for_wfi(void);-@@ -430,6 +431,12 @@ wfe_to_deadline_or_interrupt(uint32_t cid, uint64_t wfe_deadline, cpu_data_t *cd- * another core/cluster in a powergated state.- * Hence, optionally unmask IRQs+FIQs across WFE.- */-+ {-+ extern uintptr_t linux64_hook;-+ if (linux64_hook) {-+ unmask = false; /* LINUX64: never unmask hardware IRQs while hosted */-+ }-+ }- if (unmask) {- /* Latch SW IRQ+FIQ counter prior to unmasking- * interrupts.-@@ -506,6 +513,35 @@ cpu_idle(void)- uint64_t new_idle_timeout_ticks = 0x0ULL, lastPop;- bool idle_disallowed = false;--+ { extern unsigned long linux64_dbg[16]; linux64_dbg[2]++; } /* LINUX64 debug */-+ {-+ /*-+ * LINUX64 (xnulinux): hosted, idle goes straight to the host. idle_enable stays FALSE without the-+ * CPU kext (cpu_machine_init never runs), and no WFE/WFI or timer interrupt applies here.-+ */-+ extern uintptr_t linux64_hook;-+ extern void linux64_stage_arg(unsigned long, unsigned long);-+ if (linux64_hook) {-+ uint64_t now = mach_absolute_time();-+ uint64_t deadline = cpu_data_ptr->rtcPop;-+ if (deadline == 0 || deadline == EndOfAllTime || deadline < now) {-+ deadline = now + 24000; /* about 1 ms: re-check the run queue */-+ }-+ {-+ extern unsigned long linux64_dbg[16];-+ extern void linux64_dump_threads(void);-+ if (++linux64_dbg[3] % 150000 == 0) { /* about every two to three minutes of idle */-+ linux64_dump_threads(); /* LINUX64 debug: who is blocked, and where */-+ }-+ }-+ linux64_stage_arg(810, deadline);-+ { extern void linux64_net_idle_poll(void); linux64_net_idle_poll(); } /* frames from the host: wake en0's receive thread */-+ cpu_data_ptr->cpu_decrementer = -1;-+ rtclock_intr(FALSE);-+ ClearIdlePop(TRUE);-+ cpu_idle_exit(FALSE);-+ }-+ }- if (__improbable((!idle_enable))) {- idle_disallowed = true;- os_atomic_inc(&virt_idle_disallowed[0], relaxed);-@@ -570,7 +606,9 @@ cpu_idle(void)- }- }--- if (__improbable(cpu_proximate_timer())) {-+ extern uintptr_t linux64_hook;-+ /* LINUX64: no timer interrupt will arrive while hosted; the host idle below delivers the due timer. */-+ if (__improbable(cpu_proximate_timer()) && !linux64_hook) {- if (idle_wfe_poll && idle_proximate_timer_wfe == 1) {- /* Poll issuing WFEs until the expected- * timer FIQ arrives.-@@ -614,6 +652,29 @@ cpu_idle(void)- cpc_cpu_transition(CPC_CPU_IDLE, cpu_data_ptr);- #endif /* CONFIG_CPU_COUNTERS */--+ {-+ /*-+ * LINUX64 (xnulinux): no WFI and no timer interrupt of our own. The host sleeps (in Linux, with-+ * Linux interrupts on) until XNU's next deadline; then the timer "interrupt" is delivered here.-+ */-+ extern uintptr_t linux64_hook;-+ extern void linux64_stage_arg(unsigned long, unsigned long);-+ if (linux64_hook) {-+ uint64_t now = mach_absolute_time();-+ uint64_t deadline = cpu_data_ptr->rtcPop;-+ if (deadline == 0 || deadline == EndOfAllTime || deadline < now) {-+ deadline = now + 24000; /* about 1 ms: re-check the run queue */-+ }-+ { extern unsigned long linux64_dbg[16]; linux64_dbg[3]++; } /* LINUX64 debug */-+ linux64_stage_arg(810, deadline);-+ { extern void linux64_net_idle_poll(void); linux64_net_idle_poll(); } /* frames from the host: wake en0's receive thread */-+ cpu_data_ptr->cpu_decrementer = -1;-+ rtclock_intr(FALSE);-+ ClearIdlePop(TRUE);-+ cpu_idle_exit(FALSE);-+ }-+ }-+- if (wfi) {- #if !defined(APPLE_ARM64_ARCH_FAMILY)- platform_cache_idle_enter();-@@ -735,20 +796,27 @@ cpu_idle_exit(boolean_t from_reset)- void- cpu_init(void)- {-+ extern void linux64_stage_ext(unsigned long);-+ linux64_stage_ext(141);- cpu_data_t *cdp = getCpuDatap();- arm_cpu_info_t *cpu_info_p;--+ linux64_stage_ext(142);- assert(exception_stack_pointer() != 0);-+ linux64_stage_ext(143);-- if (cdp->cpu_type != CPU_TYPE_ARM64) {- cdp->cpu_type = CPU_TYPE_ARM64;-- timer_call_queue_init(&cdp->rtclock_timer.queue);-+ linux64_stage_ext(144);- cdp->rtclock_timer.deadline = EndOfAllTime;-- if (cdp == &BootCpuData) {- do_cpuid();-+ linux64_stage_ext(145);- do_mvfpid();-+ linux64_stage_ext(146);- } else {- /*- * We initialize non-boot CPUs here; the boot CPU is-@@ -758,9 +826,11 @@ cpu_init(void)- }-- do_cacheid();-+ linux64_stage_ext(147);-- /* ARM_SMP: Assuming identical cpu */- do_debugid();-+ linux64_stage_ext(148);-- cpu_info_p = cpuid_info();--@@ -780,6 +850,7 @@ cpu_init(void)- }-- cdp->cpu_threadtype = CPU_THREADTYPE_NONE;-+ linux64_stage_ext(149);- #if CONFIG_CPU_COUNTERS- cpc_cpu_transition(CPC_CPU_EARLY_INIT, cdp);- #endif /* CONFIG_CPU_COUNTERS */-diff --git a/osfmk/arm64/cswitch.s b/osfmk/arm64/cswitch.s-index a191eb3..062cd5f 100644---- a/osfmk/arm64/cswitch.s-+++ b/osfmk/arm64/cswitch.s-@@ -185,7 +185,8 @@- * arg2 - Scratch register- */- .macro set_thread_registers-- msr TPIDR_EL1, $0 // Write new thread pointer to TPIDR_EL1-+ adrp $1, _linux64_tpidr@PAGE // LINUX64: thread pointer lives in memory, not TPIDR_EL1-+ str $0, [$1, _linux64_tpidr@PAGEOFF]- ldr $1, [$0, ACT_CPUDATAP]- str $0, [$1, CPU_ACTIVE_THREAD]--@@ -333,7 +334,8 @@ LEXT(machine_load_context)-- LEXT(Call_continuation)- ARM64_PROLOG-- mrs x4, TPIDR_EL1 // Get the current thread pointer-+ adrp x4, _linux64_tpidr@PAGE-+ ldr x4, [x4, _linux64_tpidr@PAGEOFF] // Get the current thread pointer-- /* ARM64_TODO arm loads the kstack top instead of arg4. What should we use? */- LOAD_KERN_STACK_TOP dst=x5, src=x4, tmp=x6-@@ -359,7 +361,8 @@ LEXT(Call_continuation)- #else- blr x20 // Branch to the continuation- #endif-- mrs x0, TPIDR_EL1 // Get the current thread pointer-+ adrp x0, _linux64_tpidr@PAGE-+ ldr x0, [x0, _linux64_tpidr@PAGEOFF] // Get the current thread pointer- b EXT(thread_terminate) // Kill the thread---@@ -394,7 +397,8 @@ Lswitch_threads:-- LEXT(Shutdown_context)- ARM64_PROLOG-- mrs x10, TPIDR_EL1 // Get thread pointer-+ adrp x10, _linux64_tpidr@PAGE-+ ldr x10, [x10, _linux64_tpidr@PAGEOFF] // Get thread pointer- LOAD_KERN_STACK_TOP dst=x11, src=x10, tmp=x12 // Get the top of the kernel stack- save_general_registers x11, 12- msr DAIFSet, #(DAIFSC_STANDARD_DISABLE) // Disable interrupts-@@ -412,7 +416,8 @@ LEXT(Shutdown_context)-- LEXT(Idle_context)- ARM64_PROLOG-- mrs x0, TPIDR_EL1 // Get thread pointer-+ adrp x0, _linux64_tpidr@PAGE-+ ldr x0, [x0, _linux64_tpidr@PAGEOFF] // Get thread pointer- LOAD_KERN_STACK_TOP dst=x1, src=x0, tmp=x2 // Get the top of the kernel stack- save_general_registers x1, 2- LOAD_INT_STACK_THREAD dst=x2, src=x0, tmp=x1-@@ -429,7 +434,8 @@ LEXT(Idle_context)-- LEXT(Idle_load_context)- ARM64_PROLOG-- mrs x0, TPIDR_EL1 // Get thread pointer-+ adrp x0, _linux64_tpidr@PAGE-+ ldr x0, [x0, _linux64_tpidr@PAGEOFF] // Get thread pointer- LOAD_KERN_STACK_TOP dst=x1, src=x0, tmp=x2 // Get the top of the kernel stack- load_general_registers x1, 2- set_process_dependent_keys_and_sync_context x0, x1, x2, x3, w4-@@ -444,3 +450,199 @@ LEXT(machine_set_current_thread)--- /* vim: set ts=4: */-+-+/*-+ * LINUX64 (xnulinux): user space while hosted. linux64_el0_run(ss) enters EL0 with the user state in ss-+ * (IRQs stay masked at EL0), on this CPU, with VBAR_EL1 pointing at linux64_el0_vectors and SP_EL0 holding the-+ * user sp; Linux's vectors and its `current` (SP_EL0) are kept in linux64_el0_save. An exception from EL0 builds a-+ * register frame on the thread's kernel stack, puts Linux's VBAR and SP_EL0 back and calls-+ * linux64_el0_exception(frame) (sleh.c), which hands it to sleh_synchronous and returns to user space again.-+ */-+ .data-+ .align 3-+ .globl EXT(linux64_el0_save)-+LEXT(linux64_el0_save)-+ .quad 0, 0, 0, 0 // Linux's SP_EL0 (current), VBAR_EL1, x18 (its shadow call stack), SCTLR_EL1-+-+ .text-+ .align 2-+ .globl EXT(linux64_el0_run)-+LEXT(linux64_el0_run)-+ ARM64_PROLOG-+ adrp x9, EXT(linux64_el0_save)@page-+ add x9, x9, EXT(linux64_el0_save)@pageoff-+ mrs x10, SP_EL0-+ str x10, [x9, #0]-+ mrs x10, VBAR_EL1-+ str x10, [x9, #8]-+ str x18, [x9, #16]-+ mrs x10, SCTLR_EL1-+ str x10, [x9, #24]-+ adrp x10, EXT(linux64_el0_vectors)@page-+ add x10, x10, EXT(linux64_el0_vectors)@pageoff-+ msr VBAR_EL1, x10-+ ldr x10, [x0, SS64_SP]-+ msr SP_EL0, x10-+ ldr x10, [x0, SS64_PC]-+ msr ELR_EL1, x10-+ ldr w10, [x0, SS64_CPSR]-+ orr w10, w10, #0x40 // FIQ stays masked at EL0 while hosted; a (Linux) IRQ preempts user code-+ msr SPSR_EL1, x10-+ // the user's NEON/FP state (arm_context_t ns, right after ss): upcalls may let Linux schedule, which reuses the registers-+ add x9, x0, NS64_Q0-+ ldp q0, q1, [x9, #0]-+ ldp q2, q3, [x9, #32]-+ ldp q4, q5, [x9, #64]-+ ldp q6, q7, [x9, #96]-+ ldp q8, q9, [x9, #128]-+ ldp q10, q11, [x9, #160]-+ ldp q12, q13, [x9, #192]-+ ldp q14, q15, [x9, #224]-+ ldp q16, q17, [x9, #256]-+ ldp q18, q19, [x9, #288]-+ ldp q20, q21, [x9, #320]-+ ldp q22, q23, [x9, #352]-+ ldp q24, q25, [x9, #384]-+ ldp q26, q27, [x9, #416]-+ ldp q28, q29, [x9, #448]-+ ldp q30, q31, [x9, #480]-+ ldr w10, [x9, #512]-+ msr FPSR, x10-+ ldr w10, [x9, #516]-+ msr FPCR, x10-+ // the next exception from EL0 starts from the top of this thread's kernel stack-+ adrp x11, _linux64_tpidr@PAGE-+ ldr x11, [x11, _linux64_tpidr@PAGEOFF]-+ LOAD_KERN_STACK_TOP dst=x12, src=x11, tmp=x13-+ mov sp, x12-+ /*-+ * x1: JOP off for this thread (arm64, not arm64e): EnIA (31) and EnDA (27) off at EL0. Only now, after the last-+ * kernel pointer authentication above (LOAD_KERN_STACK_TOP authenticates; with EnDA off it would trap to brk).-+ */-+ cbz x1, 1f-+ mrs x10, SCTLR_EL1-+ mov x11, #((1 << 31) | (1 << 27))-+ bic x10, x10, x11-+ msr SCTLR_EL1, x10-+1:-+ isb-+ add x30, x0, SS64_X0-+ ldp x2, x3, [x30, #16]-+ ldp x4, x5, [x30, #32]-+ ldp x6, x7, [x30, #48]-+ ldp x8, x9, [x30, #64]-+ ldp x10, x11, [x30, #80]-+ ldp x12, x13, [x30, #96]-+ ldp x14, x15, [x30, #112]-+ ldp x16, x17, [x30, #128]-+ ldp x18, x19, [x30, #144]-+ ldp x20, x21, [x30, #160]-+ ldp x22, x23, [x30, #176]-+ ldp x24, x25, [x30, #192]-+ ldp x26, x27, [x30, #208]-+ ldp x28, x29, [x30, #224]-+ ldp x0, x1, [x30, #0]-+ ldr x30, [x30, #240]-+ eret-+-+ .text-+ .align 11-+ .globl EXT(linux64_el0_vectors)-+LEXT(linux64_el0_vectors)-+ .rept 8 // current EL (SP0, SPx): not expected while at EL0-+ b Llinux64_el0_bad-+ .align 7-+ .endr-+ b Llinux64_el0_entry // lower EL, AArch64: sync-+ .align 7-+ b Llinux64_el0_irq // IRQ: the host's interrupt arrived while user code ran-+ .align 7-+ .rept 2 // FIQ, SError-+ b Llinux64_el0_entry-+ .align 7-+ .endr-+ .rept 4 // lower EL, AArch32-+ b .-+ .align 7-+ .endr-+-+Llinux64_el0_bad: // note it for the monitor (linux64_dbg[14] = ESR) and stop here-+ adrp x9, _linux64_dbg@PAGE-+ add x9, x9, _linux64_dbg@PAGEOFF-+ mrs x10, ESR_EL1-+ str x10, [x9, #112]-+ b .-+-+Llinux64_el0_irq: // as an exception, with ESR = ~0 (LINUX64_EL0_ESR_IRQ: no ESR has bits 63:32 set)-+ sub sp, sp, #(36 * 8 + 528)-+ stp x0, x1, [sp, #0]-+ mov x1, #1-+ b Llinux64_el0_common-+Llinux64_el0_entry:-+ sub sp, sp, #(36 * 8 + 528)-+ stp x0, x1, [sp, #0]-+ mov x1, #0-+Llinux64_el0_common:-+ stp x2, x3, [sp, #16]-+ stp x4, x5, [sp, #32]-+ stp x6, x7, [sp, #48]-+ stp x8, x9, [sp, #64]-+ stp x10, x11, [sp, #80]-+ stp x12, x13, [sp, #96]-+ stp x14, x15, [sp, #112]-+ stp x16, x17, [sp, #128]-+ stp x18, x19, [sp, #144]-+ stp x20, x21, [sp, #160]-+ stp x22, x23, [sp, #176]-+ stp x24, x25, [sp, #192]-+ stp x26, x27, [sp, #208]-+ stp x28, x29, [sp, #224]-+ str x30, [sp, #240]-+ mrs x0, SP_EL0-+ str x0, [sp, #248]-+ mrs x0, ELR_EL1-+ str x0, [sp, #256]-+ mrs x0, SPSR_EL1-+ str x0, [sp, #264]-+ mrs x0, ESR_EL1-+ cbz x1, 1f-+ mov x0, #-1-+1:-+ str x0, [sp, #272]-+ mrs x0, FAR_EL1-+ str x0, [sp, #280]-+ add x9, sp, #288 // the user's NEON/FP registers (linux64_el0_exception keeps them in uNeon)-+ stp q0, q1, [x9, #0]-+ stp q2, q3, [x9, #32]-+ stp q4, q5, [x9, #64]-+ stp q6, q7, [x9, #96]-+ stp q8, q9, [x9, #128]-+ stp q10, q11, [x9, #160]-+ stp q12, q13, [x9, #192]-+ stp q14, q15, [x9, #224]-+ stp q16, q17, [x9, #256]-+ stp q18, q19, [x9, #288]-+ stp q20, q21, [x9, #320]-+ stp q22, q23, [x9, #352]-+ stp q24, q25, [x9, #384]-+ stp q26, q27, [x9, #416]-+ stp q28, q29, [x9, #448]-+ stp q30, q31, [x9, #480]-+ mrs x10, FPSR-+ str w10, [x9, #512]-+ mrs x10, FPCR-+ str w10, [x9, #516]-+ adrp x9, EXT(linux64_el0_save)@page-+ add x9, x9, EXT(linux64_el0_save)@pageoff-+ ldr x10, [x9, #0]-+ msr SP_EL0, x10-+ ldr x10, [x9, #8]-+ msr VBAR_EL1, x10-+ ldr x18, [x9, #16] // the host's x18 again (user code owns x18 at EL0)-+ ldr x10, [x9, #24] // SCTLR_EL1 as the kernels expect it (EnIA/EnDA back on)-+ msr SCTLR_EL1, x10-+ isb-+ mov x0, sp-+ mov x29, xzr-+ bl EXT(linux64_el0_exception)-+ b .-diff --git a/osfmk/arm64/exception_asm.h b/osfmk/arm64/exception_asm.h-index b0772a7..ea5e679 100644---- a/osfmk/arm64/exception_asm.h-+++ b/osfmk/arm64/exception_asm.h-@@ -299,7 +299,8 @@ Lspill_registers_skip_elr_far_\@:- * SP0 is expected to already be selected. Clobbers x1 and tmp.- */- .macro SWITCH_TO_INT_STACK tmp-- mrs x1, TPIDR_EL1-+ adrp x1, _linux64_tpidr@PAGE-+ ldr x1, [x1, _linux64_tpidr@PAGEOFF]- LOAD_INT_STACK_THREAD dst=x1, src=x1, tmp=\tmp- mov sp, x1 // Set the stack pointer to the interrupt stack- .endmacro-diff --git a/osfmk/arm64/locore.s b/osfmk/arm64/locore.s-index 13d2819..d71ba86 100644---- a/osfmk/arm64/locore.s-+++ b/osfmk/arm64/locore.s-@@ -144,7 +144,8 @@-- #endif /* DEVELOPMENT || DEBUG */- #if CONFIG_XNUPOST-- mrs x0, TPIDR_EL1-+ adrp x0, _linux64_tpidr@PAGE-+ ldr x0, [x0, _linux64_tpidr@PAGEOFF]- /*- * If hitting this with a null TPIDR, it's likely that this was an unexpected- * exception in early boot rather than an expected one as a part of a test.-@@ -257,7 +258,8 @@ Lbegin_panic_lockdown_continue_\@:- * Find the kernelcache table for the exception vectors by accessing- * the per-CPU data.- */-- mrs x18, TPIDR_EL1-+ adrp x18, _linux64_tpidr@PAGE-+ ldr x18, [x18, _linux64_tpidr@PAGEOFF]- ldr x18, [x18, ACT_CPUDATAP]- ldr x18, [x18, CPU_EXC_VECTORS]--@@ -354,7 +356,8 @@ Lbegin_panic_lockdown_continue_\@:- str x1, [x0, #24] // spsr- mrs x1, SP_EL0- str x1, [x0, #32] // sp-- mrs x1, TPIDR_EL1-+ adrp x1, _linux64_tpidr@PAGE-+ ldr x1, [x1, _linux64_tpidr@PAGEOFF]- str x1, [x0, #40] // tpidr (thread pointer)-- /* Get timestamp */-@@ -396,7 +399,8 @@ Lbegin_panic_lockdown_continue_\@:- cmp x1, x2 // If we have a data abort, we need to- b.ne Lvalid_stack_\@ // ...validate the stack pointer- mrs x0, SP_EL0 // Get SP_EL0-- mrs x1, TPIDR_EL1 // Get thread pointer-+ adrp x1, _linux64_tpidr@PAGE-+ ldr x1, [x1, _linux64_tpidr@PAGEOFF] // Get thread pointer- /*- * Check for either a NULL TPIDR or a NULL kernel stack, both of which- * are expected in early boot, but will cause recursive faults if not-@@ -490,7 +494,8 @@ Lvalid_stack_\@:- * Clobbers NZCV.- */- .macro CHECK_EXCEPTION_STACK invalid_stack_label-- mrs x18, TPIDR_EL1 // Get thread pointer-+ adrp x18, _linux64_tpidr@PAGE-+ ldr x18, [x18, _linux64_tpidr@PAGEOFF] // Get thread pointer- /*- * The thread pointer might be invalid during early boot.- * Return zero in x18 to indicate that we failed to execute the check.-@@ -631,7 +636,8 @@ Lel0_serror_vector_64:- // SWITCH_TO_INT_STACK requires a clobberable tmp register, but at this- // point in the exception vector we can't spare the extra GPR. Instead note- // that EL1_SP0_VECTOR ends with x0 == sp and use this to unclobber x0.-- mrs x1, TPIDR_EL1-+ adrp x1, _linux64_tpidr@PAGE-+ ldr x1, [x1, _linux64_tpidr@PAGEOFF]- LOAD_INT_STACK_THREAD dst=x1, src=x1, tmp=x0- mov x0, sp- mov sp, x1-@@ -701,7 +707,8 @@ Lkernel_stack_valid:- * Slow path: check/map redzone.- * Skip redzone mapping if preemption is disabled (e.g. possibly in SPTM context)- */-- mrs x0, TPIDR_EL1-+ adrp x0, _linux64_tpidr@PAGE-+ ldr x0, [x0, _linux64_tpidr@PAGEOFF]- ldr w0, [x0, ACT_PREEMPT_CNT]- cbnz w0, Lel1_sp0_redzone_done_\@ // Preemption disabled, skip redzone--@@ -822,7 +829,8 @@ Lel1_sp1_synchronous_vector_continue:- *- * Ensure that we actually performed the check on a legitmate value now.- */-- mrs x0, TPIDR_EL1-+ adrp x0, _linux64_tpidr@PAGE-+ ldr x0, [x0, _linux64_tpidr@PAGEOFF]- LOAD_EXCEP_STACK_THREAD dst=x0, src=x0, tmp=x1- cmp x0, x18- /* If we aren't equal, something is very wrong and we should lockdown. */-@@ -875,7 +883,8 @@ LEXT(el1_sp1_synchronous_vector_long_spill_failed)- /* Macro returns x0=1 if it performed a simulated lockdown */- cbz x0, 0f- /* This was a test; return to fault handler so they can fixup the system. */-- mrs x0, TPIDR_EL1-+ adrp x0, _linux64_tpidr@PAGE-+ ldr x0, [x0, _linux64_tpidr@PAGEOFF]- ldr x16, [x0, TH_EXPECTED_FAULT_HANDLER]- #if __has_feature(ptrauth_calls)- movk x17, #TH_EXPECTED_FAULT_HANDLER_DIVERSIFIER-@@ -944,7 +953,8 @@ el1_sp1_serror_vector_long:- #if __ARM_KERNEL_PROTECT__- mov x18, #0 // Zero x18 to avoid leaking data to user SS- #endif-- mrs x0, TPIDR_EL1 // Load the thread register-+ adrp x0, _linux64_tpidr@PAGE-+ ldr x0, [x0, _linux64_tpidr@PAGEOFF] // Load the thread register- LOAD_USER_PCB dst=x0, src=x0, tmp=x1 // Load the user context pointer- mrs x1, SP_EL0 // Load the user stack pointer- str x1, [x0, SS64_SP] // Store the user stack pointer in the user PCB-@@ -953,7 +963,8 @@ el1_sp1_serror_vector_long:- msr SPSel, #0 // Switch to SP0- stp x0, x1, [sp, SS64_X0] // Save x0, x1 to the user PCB- stp x2, x3, [sp, SS64_X2] // Save x2, x3 to the user PCB-- mrs x1, TPIDR_EL1 // Load the thread register-+ adrp x1, _linux64_tpidr@PAGE-+ ldr x1, [x1, _linux64_tpidr@PAGEOFF] // Load the thread register----@@ -1321,7 +1332,8 @@ Lblocked_user_sync_exception:- * sp - Interrupt stack for the current CPU- */- .macro BEGIN_INTERRUPT_HANDLER-- mrs x22, TPIDR_EL1-+ adrp x22, _linux64_tpidr@PAGE-+ ldr x22, [x22, _linux64_tpidr@PAGEOFF]- ldr x23, [x22, ACT_CPUDATAP] // Get current cpu- /* Update IRQ count; CPU_STAT_IRQ.* is required to be accurate for the WFE idle sequence */- ldr w1, [x23, CPU_STAT_IRQ]-@@ -1529,7 +1541,8 @@ LEXT(fleh_check_map_redzone)- PUSH_FRAME-- /* Check if we have a valid thread */-- mrs x1, TPIDR_EL1-+ adrp x1, _linux64_tpidr@PAGE-+ ldr x1, [x1, _linux64_tpidr@PAGEOFF]- cbz x1, Lfleh_check_map_redzone_skip-- /* Get kernel stack bottom */-@@ -1671,7 +1684,8 @@ Lfleh_synchronous_sp1_skip_panic_lockdown:- * still on init_thread) and we try to panic(), we'll end up in an infinite- * nested exception, so just stop here instead to preserve the call stack.- */-- mrs x9, TPIDR_EL1-+ adrp x9, _linux64_tpidr@PAGE-+ ldr x9, [x9, _linux64_tpidr@PAGEOFF]- cbz x9, 0f- ldr x9, [x9, TH_KSTACKPTR]- cbz x9, 0f-@@ -1742,7 +1756,8 @@ LEXT(xnu_return_to_gl2)- * If thread->txm_thread_stack is set, we need to tell SPTM dispatch to- * resume the TXM thread in x0.- */-- mrs x8, TPIDR_EL1-+ adrp x8, _linux64_tpidr@PAGE-+ ldr x8, [x8, _linux64_tpidr@PAGEOFF]- ldr x8, [x8, TH_TXM_THREAD_STACK]- cbz x8, 1f- mov x0, x8-@@ -1756,7 +1771,8 @@ LEXT(xnu_return_to_gl2)- * we need to tell SPTM dispatch to resume the SK thread.- */- 1:-- mrs x8, TPIDR_EL1-+ adrp x8, _linux64_tpidr@PAGE-+ ldr x8, [x8, _linux64_tpidr@PAGEOFF]- ldr x9, [x8, TH_EXCLAVES_INTSTATE]- and x9, x9, TH_EXCLAVES_EXECUTION- cbz x9, 1f-@@ -1783,7 +1799,8 @@ LEXT(return_to_kernel)- UNWIND_PROLOGUE- RETURN_TO_KERNEL_UNWIND- tbnz w0, #DAIF_IRQF_SHIFT, exception_return // Skip AST check if IRQ disabled-- mrs x3, TPIDR_EL1 // Load thread pointer-+ adrp x3, _linux64_tpidr@PAGE-+ ldr x3, [x3, _linux64_tpidr@PAGEOFF] // Load thread pointer- ldr w1, [x3, ACT_PREEMPT_CNT] // Load preemption count- msr DAIFSet, #DAIFSC_ALL // Disable exceptions- cbnz x1, exception_return_unint_tpidr_x3 // If preemption disabled, skip AST check-@@ -1802,6 +1819,12 @@ LEXT(return_to_kernel)- .globl EXT(thread_bootstrap_return)- LEXT(thread_bootstrap_return)- ARM64_PROLOG-+ // LINUX64 (xnulinux): hosted, a new user thread's first return goes through C (user space is not hosted yet)-+ adrp x9, _linux64_hook@PAGE-+ ldr x9, [x9, _linux64_hook@PAGEOFF]-+ cbz x9, 1f-+ b EXT(linux64_thread_bootstrap_return)-+1:- #if CONFIG_DTRACE- bl EXT(dtrace_thread_bootstrap)- #endif-@@ -1816,7 +1839,14 @@ LEXT(thread_bootstrap_return)- .globl EXT(arm64_thread_exception_return)- LEXT(arm64_thread_exception_return)- ARM64_PROLOG-- mrs x0, TPIDR_EL1-+ // LINUX64 (xnulinux): hosted, a return to user space goes through C (user space is not hosted yet)-+ adrp x9, _linux64_hook@PAGE-+ ldr x9, [x9, _linux64_hook@PAGEOFF]-+ cbz x9, 1f-+ b EXT(linux64_thread_bootstrap_return)-+1:-+ adrp x0, _linux64_tpidr@PAGE-+ ldr x0, [x0, _linux64_tpidr@PAGEOFF]- LOAD_USER_PCB dst=x21, src=x0, tmp=x28- mov x28, xzr--@@ -1835,7 +1865,8 @@ check_user_asts:- bl EXT(__asan_handle_no_return)- POP_FRAME_WITHOUT_LR- #endif /* KASAN_TBI */-- mrs x3, TPIDR_EL1 // Load thread pointer-+ adrp x3, _linux64_tpidr@PAGE-+ ldr x3, [x3, _linux64_tpidr@PAGEOFF] // Load thread pointer-- movn w2, #0- str w2, [x3, TH_IOTIER_OVERRIDE] // Reset IO tier override to -1 before returning to user-@@ -1927,7 +1958,8 @@ no_asts:- PUSH_FRAME- bl EXT(arm_debug_set) // Establish thread debug state in live regs- POP_FRAME_WITHOUT_LR-- mrs x3, TPIDR_EL1 // Reload thread pointer-+ adrp x3, _linux64_tpidr@PAGE-+ ldr x3, [x3, _linux64_tpidr@PAGEOFF] // Reload thread pointer- ldr x4, [x3, ACT_CPUDATAP] // Reload CPU data pointer- L_skip_user_set_debug_state:--@@ -1937,7 +1969,8 @@ L_skip_user_set_debug_state:- exception_return:- msr DAIFSet, #DAIFSC_ALL // Disable exceptions- exception_return_unint:-- mrs x3, TPIDR_EL1 // Load thread pointer-+ adrp x3, _linux64_tpidr@PAGE-+ ldr x3, [x3, _linux64_tpidr@PAGEOFF] // Load thread pointer- exception_return_unint_tpidr_x3:- mov sp, x21 // Reload the pcb pointer--@@ -2006,7 +2039,9 @@ Lexception_return_restore_registers:- // SPSR_EL1.M != EL0: no SME state to restore- bne Lno_sme_saved_state--- mrs x3, TPIDR_EL1-+ adrp x3, _linux64_tpidr@PAGE-+-+ ldr x3, [x3, _linux64_tpidr@PAGEOFF]- add x3, x3, ACT_UMATRIX_HDR- ldr x2, [x3]- cbz x2, Lno_sme_saved_state-@@ -2071,7 +2106,8 @@ Lno_gcr_mask_el0_reset:- #endif /* HAS_MTE */- // If sync_on_cswitch and ERET is not a CSE, issue an ISB now. Unconditionally clear the- // sync_on_cswitch flag.-- mrs x1, TPIDR_EL1-+ adrp x1, _linux64_tpidr@PAGE-+ ldr x1, [x1, _linux64_tpidr@PAGEOFF]- ldr x1, [x1, ACT_CPUDATAP]-- // Redefined for backporting.-@@ -2095,7 +2131,8 @@ Lno_gcr_mask_el0_reset:- mrs x2, SPSR_EL1- tst x2, #(PSR64_MODE_EL_MASK)- b.ne 1f-- mrs x2, TPIDR_EL1-+ adrp x2, _linux64_tpidr@PAGE-+ ldr x2, [x2, _linux64_tpidr@PAGEOFF]- ldr w2, [x2, TH_ARM_MACHINE_FLAGS]- tbz w2, #ARM_MACHINE_THREAD_DISABLE_USER_JOP_SHIFT, 1f- mrs x2, SCTLR_EL1-@@ -2184,7 +2221,8 @@ user_take_ast:- .text- .align 2- preempt_underflow:-- mrs x0, TPIDR_EL1-+ adrp x0, _linux64_tpidr@PAGE-+ ldr x0, [x0, _linux64_tpidr@PAGEOFF]- str x0, [sp, #-16]! // We'll print thread pointer- adr x0, L_underflow_str // Format string- CALL_EXTERN panic // Game over-@@ -2197,7 +2235,8 @@ L_underflow_str:- .text- .align 2- preempt_count_notzero:-- mrs x0, TPIDR_EL1-+ adrp x0, _linux64_tpidr@PAGE-+ ldr x0, [x0, _linux64_tpidr@PAGEOFF]- str x0, [sp, #-16]! // We'll print thread pointer- ldr w0, [x0, ACT_PREEMPT_CNT]- str w0, [sp, #8]-@@ -2457,7 +2496,8 @@ ppl_exit:- add x15, x15, x10, lsl #32-- /* Load the preemption count. */-- mrs x10, TPIDR_EL1-+ adrp x10, _linux64_tpidr@PAGE-+ ldr x10, [x10, _linux64_tpidr@PAGEOFF]- ldr w12, [x10, ACT_PREEMPT_CNT]-- /* Detect underflow */-@@ -2493,7 +2533,8 @@ Lno_preempt_underflow:- mov w12, #0-- /* Restore the thread pointer into x10. */-- mrs x10, TPIDR_EL1-+ adrp x10, _linux64_tpidr@PAGE-+ ldr x10, [x10, _linux64_tpidr@PAGEOFF]-- Lskip_collect_measurement:- #endif /* SCHED_HYGIENE_DEBUG */-@@ -2743,7 +2784,8 @@ LEXT(_sptm_pre_entry_hook)- stp x6, x7, [sp, #0x30]-- /* Increase the preemption count. */-- mrs x9, TPIDR_EL1-+ adrp x9, _linux64_tpidr@PAGE-+ ldr x9, [x9, _linux64_tpidr@PAGEOFF]- cbz x9, Lskip_preemption_check_sptmhook- ldr w10, [x9, ACT_PREEMPT_CNT]- add w10, w10, #1-@@ -2803,7 +2845,8 @@ LEXT(_sptm_post_exit_hook)--- /* Load the preemption count. */-- mrs x0, TPIDR_EL1-+ adrp x0, _linux64_tpidr@PAGE-+ ldr x0, [x0, _linux64_tpidr@PAGEOFF]- cbz x0, Lsptm_skip_ast_taken_sptmhook- ldr w12, [x0, ACT_PREEMPT_CNT]--@@ -2834,7 +2877,8 @@ Lno_preempt_underflow_sptmhook:- mov w12, #0-- /* Restore x0 as the thread pointer */-- mrs x0, TPIDR_EL1-+ adrp x0, _linux64_tpidr@PAGE-+ ldr x0, [x0, _linux64_tpidr@PAGEOFF]-- Lskip_collect_measurement_sptmhook:- #endif /* SCHED_HYGIENE_DEBUG */-@@ -2916,7 +2960,9 @@ LEXT(panic_lockdown_record_debug_data)- mov x1, sp- str x1, [x0, #PANIC_LOCKDOWN_INITIATOR_STATE_INITIATOR_SP]--- mrs x1, TPIDR_EL1-+ adrp x1, _linux64_tpidr@PAGE-+-+ ldr x1, [x1, _linux64_tpidr@PAGEOFF]- str x1, [x0, #PANIC_LOCKDOWN_INITIATOR_STATE_INITIATOR_TPIDR]-- mrs x1, MPIDR_EL1-diff --git a/osfmk/arm64/machine_routines.c b/osfmk/arm64/machine_routines.c-index f456377..1cafc2c 100644---- a/osfmk/arm64/machine_routines.c-+++ b/osfmk/arm64/machine_routines.c-@@ -385,6 +385,7 @@ wfe_process_recommendation(void)- void- machine_idle(void)- {-+ { extern unsigned long linux64_dbg[16]; linux64_dbg[1]++; } /* LINUX64 debug */- /* Interrupts are expected to be masked on entry or re-entry via- * Idle_load_context()- */-@@ -400,6 +401,15 @@ machine_idle(void)- */- Idle_context();- }-+ {-+ /* LINUX64 (xnulinux): hosted, hardware IRQs stay masked; only the virtual flag changes. */-+ extern uintptr_t linux64_hook;-+ extern unsigned int linux64_vint;-+ if (linux64_hook) {-+ linux64_vint = 1;-+ return;-+ }-+ }- __builtin_arm_wsr("DAIFClr", DAIFSC_STANDARD_DISABLE);- }--@@ -441,6 +451,14 @@ ml_get_interrupts_enabled(void)- {- uint64_t value;--+ {-+ /* LINUX64: interrupts are virtual while hosted (see ml_set_interrupts_enabled_with_debug). */-+ extern uintptr_t linux64_hook;-+ extern unsigned int linux64_vint;-+ if (linux64_hook) {-+ return linux64_vint ? TRUE : FALSE;-+ }-+ }- MRS(value, "DAIF");- if ((value & DAIF_STANDARD_DISABLE) == DAIF_STANDARD_DISABLE) {- return FALSE;-@@ -585,8 +603,12 @@ machine_lockdown(void)- #else- #endif--+ extern void linux64_stage_ext(unsigned long stage);-+ linux64_stage_ext(8101);- arm_vm_prot_finalize(PE_state.bootArgs);-+ linux64_stage_ext(8102);- ml_release_deferred_pages();-+ linux64_stage_ext(8103);-- #if CONFIG_KERNEL_INTEGRITY- #if KERNEL_INTEGRITY_WT-@@ -2529,6 +2551,13 @@ ml_set_decrementer(uint32_t dec_value)- }- }--+ {-+ /* LINUX64 (xnulinux): the generic timer is Linux's; cpu_idle hands the deadline to the host. */-+ extern uintptr_t linux64_hook;-+ if (linux64_hook) {-+ return;-+ }-+ }- if (cdp->cpu_set_decrementer_func) {- cdp->cpu_set_decrementer_func((uint32_t)counter_value);- } else {-diff --git a/osfmk/arm64/machine_routines_asm.s b/osfmk/arm64/machine_routines_asm.s-index 96650a0..8986f4f 100644---- a/osfmk/arm64/machine_routines_asm.s-+++ b/osfmk/arm64/machine_routines_asm.s-@@ -95,7 +95,8 @@ Lcre_start_\@:--- .macro LOAD_CPU_JOP_KEY dst, tmp-- mrs \tmp, TPIDR_EL1-+ adrp \tmp, _linux64_tpidr@PAGE-+ ldr \tmp, [\tmp, _linux64_tpidr@PAGEOFF]- ldr \tmp, [\tmp, ACT_CPUDATAP]- ldr \dst, [\tmp, CPU_JOP_KEY]- .endmacro-@@ -1748,6 +1749,11 @@ LEXT(arm64_force_wfi_clock_gate)- LEXT(arm64_replace_bootstack)- ARM64_STACK_PROLOG- PUSH_FRAME-+ // LINUX64 (xnulinux): hosted, SP_EL1 is Linux's kernel stack and SP_EL0 is Linux's `current`;-+ // XNU must not touch either. Its exception stacks are unused while hosted.-+ adrp x9, _linux64_hook@PAGE-+ ldr x9, [x9, _linux64_hook@PAGEOFF]-+ cbnz x9, Lreplace_bootstack_hosted- // Set the exception stack pointer- ldr x0, [x0, CPU_EXCEPSTACK_TOP]- mrs x4, DAIF // Load current DAIF; use x4 as pinst may trash x1-x3-@@ -1763,6 +1769,7 @@ LEXT(arm64_replace_bootstack)- mov sp, x0- msr SPSel, #0- msr DAIF, x4 // Restore interrupt state-+Lreplace_bootstack_hosted:- POP_FRAME- ARM64_STACK_EPILOG EXT(arm64_replace_bootstack)--diff --git a/osfmk/arm64/pac_asm.h b/osfmk/arm64/pac_asm.h-index d211433..dc247da 100644---- a/osfmk/arm64/pac_asm.h-+++ b/osfmk/arm64/pac_asm.h-@@ -216,7 +216,8 @@- * Expects interrupts to be disabled.- */- .macro PACGA_IRG_RESEED x, y, z-- mrs \x, TPIDR_EL1-+ adrp \x, _linux64_tpidr@PAGE-+ ldr \x, [\x, _linux64_tpidr@PAGEOFF]- ldr \x, [\x, ACT_CPUDATAP]-- // No need for atomic - These are per CPU and interrupts are disabled-diff --git a/osfmk/arm64/sleh.c b/osfmk/arm64/sleh.c-index d8f1b19..cc88f40 100644---- a/osfmk/arm64/sleh.c-+++ b/osfmk/arm64/sleh.c-@@ -78,6 +78,7 @@- #if CONFIG_TELEMETRY- #include <kern/telemetry.h>- #include <kern/trap_telemetry.h>-+#include <kern/recount.h>- #endif-- #include <prng/entropy.h>-@@ -3646,3 +3647,229 @@ sleh_panic_lockdown_should_initiate_el1_sp0_sync(uint64_t esr, uint64_t elr,- }- __SECURITY_STACK_DISALLOWED_POP- #endif /* CONFIG_SPTM */-+-+/*-+ * LINUX64 (xnulinux): a data or instruction abort on an XNU kernel address, taken in Linux's vectors and forwarded by-+ * the host (xnu.ko through FKI). Does what handle_kernel_abort does for a kernel-map fault: the pmap fast path for-+ * permission/access-flag faults, then vm_fault. Returns KERN_SUCCESS when the access can be retried.-+ */-+kern_return_t linux64_kernel_fault(uint64_t far, uint64_t esr);-+kern_return_t-+linux64_kernel_fault(uint64_t far, uint64_t esr)-+{-+ uint32_t ec = (uint32_t)((esr >> 26) & 0x3f);-+ fault_status_t fault_code = (fault_status_t)(esr & 0x3f);-+ vm_prot_t fault_type = VM_PROT_READ;-+ kern_return_t result = KERN_FAILURE;-+-+ if (ec == 0x21) { /* instruction abort, current EL */-+ fault_type = VM_PROT_READ | VM_PROT_EXECUTE;-+ } else if (ec == 0x25) { /* data abort, current EL */-+ if (esr & (1u << 6)) { /* WnR */-+ fault_type = VM_PROT_READ | VM_PROT_WRITE;-+ }-+ } else {-+ return KERN_FAILURE;-+ }-+ if (!is_vm_fault(fault_code)) {-+ return KERN_FAILURE;-+ }-+ /* a kernel address faults on the kernel map; a user one (copyio) on the current thread's map */-+ vm_map_t map = kernel_map;-+ if (!VM_KERNEL_ADDRESS(far)) {-+ thread_t thread = current_thread();-+ if (thread == THREAD_NULL || thread->map == VM_MAP_NULL || thread->map == kernel_map) {-+ return KERN_FAILURE;-+ }-+ map = thread->map;-+ }-+ kern_return_t ffr = KERN_FAILURE;-+ if (!is_translation_fault(fault_code)) {-+ ffr = arm_fast_fault(map->pmap, far, fault_type, (fault_code == FSC_ACCESS_FLAG_FAULT_L3), FALSE);-+ }-+ kern_return_t kr = ffr == KERN_SUCCESS ? KERN_SUCCESS :-+ vm_fault(map, far, fault_type, FALSE, VM_KERN_MEMORY_NONE, THREAD_UNINT, NULL, 0);-+ if (ffr == KERN_SUCCESS) {-+ return KERN_SUCCESS;-+ }-+ if (map != kernel_map) {-+ /* LINUX64 debug: where did the user fault land? */-+ static int reported;-+ if (reported++ < 4) {-+ kprintf("linux64 ufault far 0x%llx esr 0x%llx kr %d map %p pmap %p ttep 0x%llx asid %u phys 0x%llx cur_ttbr0 0x%llx pagesize %llu\n",-+ far, esr, kr, map, map->pmap, (uint64_t)map->pmap->ttep, (unsigned)map->pmap->hw_asid,-+ (uint64_t)pmap_find_phys(map->pmap, far) << PAGE_SHIFT, __builtin_arm_rsr64("TTBR0_EL1"),-+ (uint64_t)vm_map_page_size(map));-+ }-+ }-+ return kr;-+}-+-+/*-+ * LINUX64 (xnulinux): a kernel fault vm_fault could not resolve, taken inside a copyin/copyout routine: the pc its-+ * copyio recovery entry returns through (the routine then returns an error; x0 = EFAULT), 0 when pc has none.-+ */-+uint64_t linux64_kernel_fault_recover(uint64_t pc, uint64_t far, uint64_t esr);-+uint64_t-+linux64_kernel_fault_recover(uint64_t pc, uint64_t far, uint64_t esr)-+{-+ struct copyio_recovery_entry *e = find_copyio_recovery_entry(pc);-+ thread_t thread = current_thread();-+-+ if (e == NULL) {-+ return 0;-+ }-+ if (thread != THREAD_NULL) {-+ thread->machine.recover_esr = esr;-+ thread->machine.recover_far = far;-+ }-+ return (uint64_t)copyio_recover_table + (uint64_t)e->cre_recovery;-+}-+-+/*-+ * LINUX64 (xnulinux): the first return of a new user thread (thread_bootstrap_return) while hosted. The pending ASTs-+ * run as on the way to user space (for the first BSD thread: bsdinit_task, which execs launchd); then the host is told-+ * where user space would start. Entering EL0 is M3.-+ */-+void linux64_thread_bootstrap_return(void) __attribute__((noreturn));-+/* LINUX64 debug: boot-arg linux64_trace=1 logs every EL0 exception, system call return and path (execve paths always) */-+static int linux64_trace_level = -1;-+static inline int-+linux64_tracing(void)-+{-+ if (__improbable(linux64_trace_level < 0)) {-+ int v = 0;-+ if (!PE_parse_boot_argn("linux64_trace", &v, sizeof(v))) {-+ v = 0;-+ }-+ linux64_trace_level = v;-+ }-+ return linux64_trace_level;-+}-+-+static thread_t linux64_svc_thread; /* LINUX64 debug: the thread whose system call is in flight, and its number */-+static long long linux64_svc_num;-+-+void-+linux64_thread_bootstrap_return(void)-+{-+ extern void linux64_stage_arg(unsigned long, unsigned long);-+ thread_t thread = current_thread();-+-+ extern void linux64_el0_run(arm_saved_state_t *, uint64_t) __attribute__((noreturn));-+ static int reported;-+-+ (void)ml_set_interrupts_enabled(FALSE);-+ ast_taken_user();-+ if (linux64_svc_thread == thread && linux64_tracing()) { /* LINUX64 debug: what the system call returned (C set: x0 is errno) */-+ linux64_svc_thread = NULL;-+ extern int proc_selfpid(void);-+ kprintf("linux64: [%d] svc %lld -> x0 0x%llx x1 0x%llx%s\n", proc_selfpid(), linux64_svc_num, get_saved_state_reg(thread->machine.upcb, 0),-+ get_saved_state_reg(thread->machine.upcb, 1), (get_saved_state_cpsr(thread->machine.upcb) & PSR64_C) ? " (error)" : "");-+ }-+ if (reported++ == 0) {-+ linux64_stage_arg(9100, get_saved_state_pc(thread->machine.upcb));-+ }-+ /*-+ * An arm64 (not arm64e) process runs the arm64e system libraries with JOP off: Apple hardware disables the user-+ * IA/DA keys for it; hosted, user code runs with SCTLR_EL1.EnIA/EnDA cleared (linux64_el0_run puts them back on-+ * the next exception), or a blraaz on one of its unsigned function pointers fails (EXC_ARM_PAC_FAIL).-+ */-+#if PRECISE_USER_KERNEL_TIME-+ recount_enter_user(); /* user time vs system time, as locore's return to user space does */-+#endif-+ linux64_el0_run(thread->machine.upcb, (thread->machine.arm_machine_flags & ARM_MACHINE_THREAD_DISABLE_USER_JOP) != 0);-+}-+-+/* LINUX64: the registers linux64_el0_vectors saved for an exception taken at EL0 (cswitch.s) */-+struct linux64_el0_frame {-+ uint64_t x[31];-+ uint64_t sp, pc, cpsr, esr, far;-+ uint64_t neon[64]; /* q0..q31 */-+ uint32_t fpsr, fpcr;-+ uint64_t pad;-+};-+_Static_assert(__builtin_offsetof(struct linux64_el0_frame, neon) == 288, "linux64_el0_frame layout");-+_Static_assert(sizeof(struct linux64_el0_frame) == 36 * 8 + 528, "linux64_el0_frame size");-+-+void linux64_el0_exception(struct linux64_el0_frame *f) __attribute__((noreturn));-+void-+linux64_el0_exception(struct linux64_el0_frame *f)-+{-+ thread_t thread = current_thread();-+ arm_saved_state_t *ss = thread->machine.upcb;-+ extern unsigned long linux64_dbg[16];-+-+#if PRECISE_USER_KERNEL_TIME-+ recount_leave_user(); /* interrupts are still off here, as on locore's exception entry */-+#endif-+ linux64_dbg[10]++; /* LINUX64 debug: EL0 exceptions, the last one's ESR, FAR, PC */-+ linux64_dbg[11] = f->esr;-+ linux64_dbg[12] = f->far;-+ linux64_dbg[13] = f->pc;-+ linux64_dbg[15] = 1;-+ if (linux64_tracing()) kprintf("linux64: EL0 exception esr 0x%llx far 0x%llx pc 0x%llx x16 %lld ttbr0 0x%llx ttep 0x%llx\n", f->esr, f->far, f->pc, f->x[16],-+ __builtin_arm_rsr64("TTBR0_EL1"), (uint64_t)thread->map->pmap->ttep);-+ for (unsigned i = 0; i < 29; i++) {-+ set_saved_state_reg(ss, i, f->x[i]);-+ }-+ linux64_dbg[15] = 2;-+ set_saved_state_fp(ss, f->x[29]);-+ set_saved_state_lr(ss, f->x[30]);-+ set_saved_state_sp(ss, f->sp);-+ set_saved_state_pc(ss, f->pc);-+ /* EL0 runs with IRQ/FIQ masked while hosted (no XNU interrupts at EL0 yet); XNU must see the user's own PSTATE,-+ * or its abort path takes the user fault for one from a non-interruptible context */-+ set_saved_state_cpsr(ss, (uint32_t)f->cpsr & ~(uint32_t)0x3c0);-+ {-+ arm_neon_saved_state_t *ns = thread->machine.uNeon;-+ memcpy(&ns->ns_64.v.q[0], f->neon, sizeof(f->neon));-+ ns->ns_64.fpsr = f->fpsr;-+ ns->ns_64.fpcr = f->fpcr;-+ }-+ linux64_dbg[15] = 3;-+ if (f->esr == ~0ULL) {-+ /*-+ * A host IRQ arrived while user code ran (EL0 runs with IRQs unmasked). Let Linux take it and run what it-+ * must (its tick, RCU, other tasks), then deliver XNU's timer "interrupt" if it is due, as sleh_irq-+ * would: the quantum expiry it may raise preempts this thread on the way back to user space.-+ */-+ extern void linux64_stage_arg(unsigned long, unsigned long);-+ extern void rtclock_intr(unsigned int);-+ cpu_data_t *cdp = getCpuDatap();-+ (void)ml_set_interrupts_enabled(FALSE); /* XNU's (virtual) interrupt state: off, as in sleh_irq */-+ linux64_stage_arg(811, 0);-+ if (cdp->rtcPop != EndOfAllTime && cdp->rtcPop != 0 && mach_absolute_time() >= cdp->rtcPop) {-+ cdp->cpu_int_state = ss;-+ cdp->cpu_stat.irq_ex_cnt++;-+ cdp->cpu_decrementer = -1;-+ rtclock_intr(TRUE);-+ cdp->cpu_int_state = NULL;-+ }-+ thread_exception_return();-+ }-+ if (ESR_EC(f->esr) == ESR_EC_SVC_64) {-+ long long num = (long long)f->x[16];-+ linux64_svc_thread = thread;-+ linux64_svc_num = num;-+ if (linux64_tracing() && num == 202 && f->x[1] > 0 && f->x[1] <= 8) { /* sysctl: the MIB and this thread's kernel stack */-+ int mib[8] = {0};-+ if (copyin((user_addr_t)f->x[0], mib, f->x[1] * sizeof(int)) == 0) {-+ kprintf("linux64: svc 202 mib %d.%d.%d.%d (len %llu) kstack 0x%llx\n", mib[0], mib[1], mib[2], mib[3], f->x[1],-+ (uint64_t)thread->kernel_stack);-+ }-+ }-+ if (num == 59 || num == 244 || (linux64_tracing() && (num == 5 || num == 398 || num == 463 || num == 33 || num == 338 || num == 340 || num == 466 || num == 469))) {-+ char path[128];-+ size_t len = 0;-+ uint64_t ua = (num == 463 || num == 466 || num == 469 || num == 244) ? f->x[1] : f->x[0];-+ if (copyinstr((user_addr_t)ua, path, sizeof(path), &len) == 0) {-+ extern int proc_selfpid(void);-+ kprintf("linux64: [%d] svc %lld path \"%s\"\n", proc_selfpid(), num, path);-+ }-+ }-+ }-+ sleh_synchronous(thread->machine.contextData, f->esr, (vm_offset_t)f->far, false);-+ linux64_dbg[15] = 4;-+ thread_exception_return();-+}-diff --git a/osfmk/arm64/status.c b/osfmk/arm64/status.c-index c615764..72ec4a7 100644---- a/osfmk/arm64/status.c-+++ b/osfmk/arm64/status.c-@@ -2103,16 +2103,17 @@ machine_thread_state_initialize(thread_t thread)- "mov x3, #0" "\n"- "mov x4, #0" "\n"- "mov x5, #0" "\n"-+ "mrs x10, SPSel" "\n"- "msr SPSel, #1" "\n"- VERIFY_USER_THREAD_STATE_INSTR "\n"- "mov x6, lr" "\n"- "bl _ml_sign_thread_state" "\n"-- "msr SPSel, #0" "\n"-+ "msr SPSel, x10" "\n"- "mov lr, x6" "\n"- :- : [iss] "r"(thread->machine.upcb), [usr] "r"(thread->machine.upcb->ss_64.cpsr),- VERIFY_USER_THREAD_STATE_INPUTS-- : "x0", "x1", "x2", "x3", "x4", "x5", "x6", "x17"-+ : "x0", "x1", "x2", "x3", "x4", "x5", "x6", "x10", "x17"- );- ml_pac_safe_interrupts_restore(intr);- }-diff --git a/osfmk/console/serial_console.c b/osfmk/console/serial_console.c-index 11d9eb4..92f42d3 100644---- a/osfmk/console/serial_console.c-+++ b/osfmk/console/serial_console.c-@@ -532,6 +532,19 @@ console_resume()- void- console_write(char *str, int size)- {-+ {-+ /* LINUX64 (xnulinux): hosted XNU's console (/dev/console, km) goes to the host (stage 996: bytes, length). */-+ extern uintptr_t linux64_hook;-+ if (linux64_hook && str && size > 0) {-+ register unsigned long x0 __asm__("x0") = 996;-+ register unsigned long x1 __asm__("x1") = (unsigned long)str;-+ register unsigned long x2 __asm__("x2") = (unsigned long)size;-+ __asm__ volatile ("blr %3" : "+r"(x0), "+r"(x1), "+r"(x2) : "r"(linux64_hook)-+ : "x3", "x4", "x5", "x6", "x7", "x8", "x9", "x10", "x11", "x12", "x13",-+ "x14", "x15", "x16", "x17", "x30", "cc", "memory");-+ return;-+ }-+ }- if (disableConsoleOutput) {- return;- }-diff --git a/osfmk/console/serial_general.c b/osfmk/console/serial_general.c-index b1ca47a..406a431 100644---- a/osfmk/console/serial_general.c-+++ b/osfmk/console/serial_general.c-@@ -48,13 +48,40 @@ SECURITY_READ_ONLY_LATE(unsigned int) serialmode;- * characters that have been typed.- */--+/*-+ * LINUX64 (xnulinux): a hosted XNU's console input comes from the host (stage 993: up to len bytes into buf, the count-+ * in result), polled by the serial keyboard thread like a UART.-+ */-+extern uintptr_t linux64_hook;-+struct linux64_cons_req { void *buf; uint64_t len; long result; };-+static int-+linux64_cons_getc(void)-+{-+ static char buf[64];-+ static int n, i;-+-+ if (i < n) {-+ return (unsigned char)buf[i++];-+ }-+ struct linux64_cons_req q = { .buf = buf, .len = sizeof(buf), .result = 0 };-+ register unsigned long x0 __asm__("x0") = 993;-+ register unsigned long x1 __asm__("x1") = (unsigned long)&q;-+ register unsigned long x2 __asm__("x2") = 0;-+ __asm__ volatile ("blr %3" : "+r"(x0), "+r"(x1), "+r"(x2) : "r"(linux64_hook)-+ : "x3", "x4", "x5", "x6", "x7", "x8", "x9", "x10", "x11", "x12", "x13",-+ "x14", "x15", "x16", "x17", "x30", "cc", "memory");-+ n = q.result > 0 ? (int)q.result : 0;-+ i = 0;-+ return n ? (unsigned char)buf[i++] : -1;-+}-+- void- serial_keyboard_init(void)- {- kern_return_t result;- thread_t thread;--- if (!(serialmode & SERIALMODE_INPUT)) { /* Leave if we do not want a serial console */-+ if (!(serialmode & SERIALMODE_INPUT) && !linux64_hook) { /* Leave if we do not want a serial console */- return;- }--@@ -82,7 +109,7 @@ serial_keyboard_poll(void)- uint64_t next;-- while (1) {-- chr = _serial_getc(false); /* Get a character if there is one */-+ chr = linux64_hook ? linux64_cons_getc() : _serial_getc(false); /* Get a character if there is one */- if (chr < 0) { /* The serial buffer is empty */- break;- }-diff --git a/osfmk/kern/assert.h b/osfmk/kern/assert.h-index 4224c9d..4a1fe94 100644---- a/osfmk/kern/assert.h-+++ b/osfmk/kern/assert.h-@@ -193,9 +193,28 @@ STATIC_IF_KEY_DECLARE_TRUE(mach_assert);- #define mach_assert_enabled_expr(ex) \- (mach_assert_enabled() || __builtin_constant_p(!(ex)))--+#if defined(XNU_KERNEL_PRIVATE) && defined(__arm64__)-+/*-+ * LINUX64 (xnulinux): hosted inside Linux there is no XNU exception vector for the assert brk, so a-+ * failed assert() is reported to the host, which decides whether XNU continues or the run ends.-+ */-+#ifdef __cplusplus-+extern "C" {-+#endif-+extern unsigned long linux64_hook;-+extern void linux64_assert_report(const char *file, int line, const char *expr);-+#ifdef __cplusplus-+}-+#endif-+#define assert(ex) \-+ (mach_assert_enabled_expr(ex) && !(ex) \-+ ? (linux64_hook ? linux64_assert_report(__FILE_NAME__, __LINE__, #ex) \-+ : (void)mach_assert_abort(#ex)) : (void)0)-+#else- #define assert(ex) \- (mach_assert_enabled_expr(ex) && !(ex) \- ? (void)mach_assert_abort(#ex) : (void)0)-+#endif-- #define assertf(ex, fmt, args...) ({ \- if (mach_assert_enabled_expr(ex) && __builtin_expect(!(ex), 0L)) { \-diff --git a/osfmk/kern/backtrace.c b/osfmk/kern/backtrace.c-index 77044be..2c195af 100644---- a/osfmk/kern/backtrace.c-+++ b/osfmk/kern/backtrace.c-@@ -48,7 +48,7 @@- #include <arm64/mte.h>- #endif // HAS_MTE---#if __x86_64__-+#if __x86_64__ || __arm64__ /* LINUX64: hosted, a kernel stack also has frames in Linux's text, beyond 32 bits of stext */- static void- _backtrace_packed_out_of_reach(void)- {-@@ -58,7 +58,7 @@ _backtrace_packed_out_of_reach(void)- //- // This is an Intel only issue.- }--#endif // __x86_64__-+#endif // __x86_64__ || __arm64__-- // Pack an address according to a particular packing format.- static size_t-@@ -74,7 +74,7 @@ _backtrace_pack_addr(backtrace_pack_t packing, uint8_t *dst, size_t dst_size,- case BTP_KERN_OFFSET_32:;- uintptr_t addr_delta = addr - vm_kernel_stext;- int32_t addr_packed = (int32_t)addr_delta;--#if __x86_64__-+#if __x86_64__ || __arm64__- if ((uintptr_t)(int32_t)addr_delta != addr_delta) {- addr = (vm_offset_t)&_backtrace_packed_out_of_reach;- addr_delta = addr - vm_kernel_stext;-diff --git a/osfmk/kern/debug.c b/osfmk/kern/debug.c-index 0eae1f6..7ae37e9 100644---- a/osfmk/kern/debug.c-+++ b/osfmk/kern/debug.c-@@ -754,7 +754,21 @@ DebuggerTrapWithState(debugger_op db_op, const char *db_message, const char *db_- * The rest of the cores are halted by IPI if possible; if that- * fails it will fall back to dbgwrap.- */-+ {-+ /*-+ * LINUX64 (xnulinux): the hosted kernel's exceptions are taken by Linux, which does not hand XNU this trap-+ * (an uncategorized exception), so a stackshot (spindump, tailspin, sysdiagnose) ended the whole run. The-+ * stackshot needs no trap frame (handle_debugger_trap takes it with do_stackshot(NULL)) and there is one CPU:-+ * call the handler here, as the trap would (kdp_trap -> handle_debugger_trap).-+ */-+ extern uintptr_t linux64_hook;-+ if (linux64_hook && db_op == DBOP_STACKSHOT) {-+ handle_debugger_trap(0, 0, 0, NULL); /* the exception number only matters for breakpoints */-+ goto trapped;-+ }-+ }- TRAP_DEBUGGER;-+trapped:-- ret = CPUDEBUGGERRET;--@@ -1253,6 +1267,32 @@ panic_trap_to_debugger(const char *panic_format_str, va_list *panic_args, unsign- {- #pragma clang diagnostic pop--+#if defined(__arm64__)-+ {-+ /* LINUX64 (xnulinux): report the panic to the host (see arm_init.c). */-+ extern uintptr_t linux64_hook;-+ if (linux64_hook) {-+ /* the formatted message when there are arguments (the format string alone otherwise) */-+ static char linux64_panic_buf[512];-+ const char *msg = panic_format_str;-+ if (panic_args != NULL && panic_format_str != NULL) {-+ extern int vsnprintf(char *, size_t, const char *, va_list);-+ va_list ap;-+ va_copy(ap, *panic_args);-+ vsnprintf(linux64_panic_buf, sizeof(linux64_panic_buf), panic_format_str, ap);-+ va_end(ap);-+ msg = linux64_panic_buf;-+ }-+ register unsigned long x0 __asm__("x0") = 999;-+ register unsigned long x1 __asm__("x1") = (unsigned long)msg;-+ register unsigned long x2 __asm__("x2") = panic_caller;-+ __asm__ volatile ("blr %3" : "+r"(x0), "+r"(x1), "+r"(x2) : "r"(linux64_hook)-+ : "x3", "x4", "x5", "x6", "x7", "x8", "x9", "x10", "x11", "x12", "x13",-+ "x14", "x15", "x16", "x17", "x30", "cc", "memory");-+ }-+ }-+#endif-+- #if defined(__x86_64__) && (DEVELOPMENT || DEBUG)- read_lbr();- #endif-diff --git a/osfmk/kern/kext_alloc.c b/osfmk/kern/kext_alloc.c-index 119c6c7..0ad3136 100644---- a/osfmk/kern/kext_alloc.c-+++ b/osfmk/kern/kext_alloc.c-@@ -218,6 +218,19 @@ check_reachable:- }- #endif--+ {-+ /*-+ * LINUX64 (xnulinux): hosted XNU has no page-fault path of its own yet (Linux takes the abort), so kext-+ * memory is wired up front instead of faulted in on first touch.-+ */-+ extern uintptr_t linux64_hook;-+ if (linux64_hook) {-+ kern_return_t wr = vm_map_wire_kernel(g_kext_map, addr, addr + size, VM_PROT_DEFAULT, VM_KERN_MEMORY_KEXT, FALSE);-+ if (wr != KERN_SUCCESS) {-+ printf("linux64: kext_alloc wire failed %d\n", wr);-+ }-+ }-+ }- /* Check that the memory is reachable by kernel text */- if ((addr + size) > kext_alloc_max) {- kext_free((vm_offset_t)addr, size);-diff --git a/osfmk/kern/link_compat.c b/osfmk/kern/link_compat.c-index e494eab..fc40514 100644---- a/osfmk/kern/link_compat.c-+++ b/osfmk/kern/link_compat.c-@@ -65,3 +65,21 @@ native_verified_block_manifest_sha384(unsigned int device, const char *uuid, uin- }-- #endif-+-+/*-+ * LINUX64 (xnulinux): macOS 27 kernel functions that 27.2's RTBuddy kext imports and xnu-12377 does not have.-+ * The hosted kernel has no coprocessors; both are no-ops.-+ */-+int os_log_coprocessor_with_handle(void);-+int-+os_log_coprocessor_with_handle(void)-+{-+ return 0;-+}-+-+int os_metric_coprocessor(void);-+int-+os_metric_coprocessor(void)-+{-+ return 0;-+}-diff --git a/osfmk/kern/printf.c b/osfmk/kern/printf.c-index 2fc6931..dd59ae6 100644---- a/osfmk/kern/printf.c-+++ b/osfmk/kern/printf.c-@@ -876,6 +876,26 @@ __printflike(1, 0)- static int- vprintf_internal(const char *fmt, va_list ap_in, void *caller)- {-+ {-+ /* LINUX64 (xnulinux): hosted XNU prints through the host (dmesg), like kprintf. */-+ extern uintptr_t linux64_hook;-+ if (linux64_hook && fmt) {-+ extern int vsnprintf(char *, size_t, const char *, va_list);-+ char buf[256];-+ va_list ap;-+ va_copy(ap, ap_in);-+ vsnprintf(buf, sizeof(buf), fmt, ap);-+ va_end(ap);-+ register unsigned long x0 __asm__("x0") = 998;-+ register unsigned long x1 __asm__("x1") = (unsigned long)buf;-+ register unsigned long x2 __asm__("x2") = 0;-+ __asm__ volatile ("blr %3" : "+r"(x0), "+r"(x1), "+r"(x2) : "r"(linux64_hook)-+ : "x3", "x4", "x5", "x6", "x7", "x8", "x9", "x10", "x11", "x12", "x13",-+ "x14", "x15", "x16", "x17", "x30", "cc", "memory");-+ (void)caller;-+ return 0;-+ }-+ }- if (fmt) {- struct console_printbuf_state info_data;--diff --git a/osfmk/kern/sched_prim.c b/osfmk/kern/sched_prim.c-index b2aae03..e7bd92d 100644---- a/osfmk/kern/sched_prim.c-+++ b/osfmk/kern/sched_prim.c-@@ -3010,6 +3010,7 @@ thread_invoke(-- thread_continue_t continuation = self->continuation;- void *parameter = self->parameter;-+ { extern unsigned long linux64_dbg[16]; linux64_dbg[4]++; linux64_dbg[9] = (unsigned long)thread; } /* LINUX64 debug */-- struct recount_snap snap = { 0 };- recount_snapshot(&snap);-@@ -6452,6 +6453,7 @@ processor_idle(- recount_processor_idle(&processor->pr_recount, &snap);-- while (1) {-+ { extern unsigned long linux64_dbg[16]; linux64_dbg[0]++; } /* LINUX64 debug: idle loop */- /*- * Ensure that updates to my processor and pset state,- * made by the IPI source processor before sending the IPI,-@@ -9984,3 +9986,45 @@ sysctl_clutch_thread_group_cpu_time_for_thread(__unused thread_t thread,- #endif /* !SCHED_TEST_HARNESS */-- #endif /* DEVELOPMENT || DEBUG */-+-+/*-+ * LINUX64 (xnulinux) debug: print every thread's state, wait event, continuation and a few saved frames.-+ * Called from the hosted idle path (single CPU, interrupts off), so the list is walked without its lock.-+ */-+void linux64_dump_threads(void);-+void-+linux64_dump_threads(void)-+{-+ thread_t t;-+ int n = 0;-+ extern int proc_pid(struct proc *);-+ queue_iterate(&threads, t, thread_t, threads) {-+ if (++n > 400) {-+ break;-+ }-+ void *bp = get_bsdthreadtask_info(t);-+ if (bp == NULL || proc_pid((struct proc *)bp) == 0) {-+ /* the kernel's own threads: only those blocked with a saved stack (not parked on a continuation) */-+ if (t->continuation != NULL || t->kernel_stack == 0) {-+ continue;-+ }-+ kprintf("linux64 proc 0 kernel_task\n");-+ } else {-+ kprintf("linux64 proc %d %s\n", proc_pid((struct proc *)bp), proc_name_address((struct proc *)bp));-+ }-+ struct arm_kernel_saved_state *ss = (struct arm_kernel_saved_state *)(void *)t->machine.kstackptr;-+ uint64_t lr = 0, fp = 0;-+ if (ss != NULL && t->kernel_stack != 0) {-+ lr = ss->lr | 0xffffff8000000000ULL;-+ fp = ss->fp;-+ }-+ kprintf("linux64 thread %p tid %llu state 0x%x pri %d wait %p cont %p lr 0x%llx\n",-+ t, t->thread_id, t->state, t->sched_pri, (void *)t->wait_event, (void *)t->continuation, lr);-+ for (int f = 0; f < 14 && fp != 0 && t->kernel_stack != 0 &&-+ fp >= t->kernel_stack && fp < t->kernel_stack + kernel_stack_size; f++) {-+ uint64_t *frame = (uint64_t *)fp;-+ kprintf("linux64 frame 0x%llx\n", frame[1] | 0xffffff8000000000ULL);-+ fp = frame[0];-+ }-+ }-+}-diff --git a/osfmk/kern/stack.c b/osfmk/kern/stack.c-index 1111ccf..7a3c00b 100644---- a/osfmk/kern/stack.c-+++ b/osfmk/kern/stack.c-@@ -185,6 +185,24 @@ STARTUP(TUNABLES, STARTUP_RANK_MIDDLE, stack_init);- * block.- */--+/*-+ * LINUX64 (xnulinux): an exception taken on an XNU kernel stack enters Linux's vectors, whose overflow check wants-+ * bit THREAD_SHIFT (14) of sp clear, as on Linux's 2*THREAD_SIZE-aligned stacks. Hosted, each stack starts on a-+ * 32 KiB boundary: the allocation is 32 KiB aligned and the stack sits 32 KiB above its start (guard pages first,-+ * then unused wired pages, then the stack, then the upper guard page).-+ */-+extern uintptr_t linux64_hook;-+static inline vm_offset_t-+linux64_stack_lead(void)-+{-+ return linux64_hook ? 0x8000 : ptoa(2);-+}-+static inline vm_offset_t-+linux64_stack_mask(void)-+{-+ return linux64_hook ? (stack_addr_mask | 0x7fff) : stack_addr_mask;-+}-+- static vm_offset_t- stack_alloc_internal(void)- {-@@ -218,7 +236,7 @@ stack_alloc_internal(void)- */-- kernel_memory_allocate(kernel_map, &stack,-- kernel_stack_size + ptoa(3), stack_addr_mask,-+ kernel_stack_size + linux64_stack_lead() + ptoa(1), linux64_stack_mask(),- flags, VM_KERN_MEMORY_STACK);-- /*-@@ -226,7 +244,7 @@ stack_alloc_internal(void)- * guard pages. Skip past them to get the actual stack base address.- */--- stack += ptoa(2);-+ stack += linux64_stack_lead();- }- return stack;- }-@@ -389,8 +407,8 @@ stack_collect(void)- stack = (vm_offset_t)vm_map_trunc_page(- stack,- VM_MAP_PAGE_MASK(kernel_map));-- stack -= ptoa(2);-- kmem_free(kernel_map, stack, kernel_stack_size + ptoa(3),-+ stack -= linux64_stack_lead();-+ kmem_free(kernel_map, stack, kernel_stack_size + linux64_stack_lead() + ptoa(1),- KMF_GUARD_FIRST | KMF_GUARD_LAST | KMF_GUARD_STACK);- stack = 0;--diff --git a/osfmk/kern/startup.c b/osfmk/kern/startup.c-index a004862..8d4f8a1 100644---- a/osfmk/kern/startup.c-+++ b/osfmk/kern/startup.c-@@ -910,6 +910,7 @@ kernel_bootstrap_thread(void)- #ifdef IOKIT- kernel_bootstrap_log("PE_lockdown_iokit");- PE_lockdown_iokit();-+ { extern void linux64_stage_ext(unsigned long); linux64_stage_ext(8201); } /* LINUX64 */- #endif- /*- * max_cpus must be nailed down by the time PE_lockdown_iokit() finishes,-@@ -926,6 +927,7 @@ kernel_bootstrap_thread(void)- * Start the user bootstrap.- */- #ifdef MACH_BSD-+ { extern void linux64_stage_ext(unsigned long); linux64_stage_ext(8202); } /* LINUX64 */- bsd_init();- #endif--diff --git a/osfmk/mach/arm/thread_status.h b/osfmk/mach/arm/thread_status.h-index 99971b0..efc6ab8 100644---- a/osfmk/mach/arm/thread_status.h-+++ b/osfmk/mach/arm/thread_status.h-@@ -522,6 +522,7 @@ extern void ml_check_signed_state(const arm_saved_state_t *, uint64_t, uint32_t,- asm volatile ( \- "mov x9, lr" "\n" \- "mov x0, %[iss]" "\n" \-+ "mrs x10, SPSel" "\n" \- "msr SPSel, #1" "\n" \- "ldp x4, x5, [x0, %[SS64_X16]]" "\n" \- "ldr x7, [x0, %[SS64_PC]]" "\n" \-@@ -535,7 +536,7 @@ extern void ml_check_signed_state(const arm_saved_state_t *, uint64_t, uint32_t,- _instr "\n" \- "bl _ml_sign_thread_state" "\n" \- "0:" "\n" \-- "msr SPSel, #0" "\n" \-+ "msr SPSel, x10" "\n" \- "mov lr, x9" "\n" \- : \- : [iss] "r"(_iss), \-@@ -544,7 +545,7 @@ extern void ml_check_signed_state(const arm_saved_state_t *, uint64_t, uint32_t,- [SS64_CPSR] "i"(ss64_offsetof(cpsr)), \- [SS64_LR] "i"(ss64_offsetof(lr)),##__VA_ARGS__ \- : "x0", "x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", \-- "x9", "x16", "x17" \-+ "x9", "x10", "x16", "x17" \- ); \- ml_pac_safe_interrupts_restore(_intr); \- } while (0)-diff --git a/osfmk/mach/arm/vm_param.h b/osfmk/mach/arm/vm_param.h-index bb62cdd..9bea611 100644---- a/osfmk/mach/arm/vm_param.h-+++ b/osfmk/mach/arm/vm_param.h-@@ -149,6 +149,11 @@ extern int PAGE_SHIFT_CONST;- #undef MACH_VM_MAX_ADDRESS_RAW- #define MACH_VM_MAX_ADDRESS_RAW 0x00007FFFFE000000ULL- #endif /* defined(XNU_PLATFORM_iPhoneOS) && EXTENDED_USER_VA_SUPPORT */-+#if !__ARM_16K_PG__ && !defined(XNU_PLATFORM_MacOSX)-+/* LINUX64 (xnulinux): 4 KiB user pmaps span 47 bits (pmap_pt_attr_4k_user), the macOS layout its userland expects */-+#undef MACH_VM_MAX_ADDRESS_RAW-+#define MACH_VM_MAX_ADDRESS_RAW 0x00007FFFFE000000ULL-+#endif- /* threshold for allocations to be placed in the large file range */- #define VM_LARGE_FILE_THRESHOLD (1ULL << 30)- #define MACH_VM_JUMBO_ADDRESS ((mach_vm_offset_t) 0x0000000FC0000000ULL)-@@ -294,7 +299,7 @@ extern int PAGE_SHIFT_CONST;-- #if XNU_KERNEL_PRIVATE- #define VM_KERNEL_STRIP_MASK (-1ULL << (64 - T1SZ_BOOT))--#define VM_USER_STRIP_MASK (-1ULL >> (T0SZ_BOOT))-+#define VM_USER_STRIP_MASK (-1ULL >> (T0SZ_HW)) /* LINUX64: user addresses span the width TTBR0 runs with */- #define _VM_KERNEL_STRIP_PTR(_va) ({((_va) & 1ULL << 55) ? ((_va) | VM_KERNEL_STRIP_MASK) : ((_va) & VM_USER_STRIP_MASK);})- #else /* XNU_KERNEL_PRIVATE */--diff --git a/osfmk/prng/prng_random.c b/osfmk/prng/prng_random.c-index 44b993c..d21911d 100644---- a/osfmk/prng/prng_random.c-+++ b/osfmk/prng/prng_random.c-@@ -368,13 +368,46 @@ random_cpu_init(int cpu)- panic("random_cpu_init: kernel prng has not been installed");- }--- prng_funcs.initgen(prng_ctx, cpu);-+ if (prng_funcs.initgen != NULL) {-+ prng_funcs.initgen(prng_ctx, cpu);-+ }-+}-+-+/*-+ * LINUX64 (xnulinux) PoC: without the corecrypto kext nobody calls register_and_init_prng(), so-+ * prng_funcs stays zeroed. Until the hosted kernel has a PRNG provider, read_random() falls back to-+ * a non-cryptographic xorshift generator seeded from early_random(). NOT FOR PRODUCTION.-+ */-+static uint64_t linux64_prng_state[2];-+static void-+linux64_prng_fill(uint8_t *p, size_t len)-+{-+ uint64_t *st = linux64_prng_state;-+ if (st[0] == 0 && st[1] == 0) {-+ st[0] = early_random() | 1;-+ st[1] = early_random();-+ }-+ while (len) {-+ uint64_t s1 = st[0], s0 = st[1];-+ st[0] = s0;-+ s1 ^= s1 << 23;-+ st[1] = s1 ^ s0 ^ (s1 >> 17) ^ (s0 >> 26);-+ uint64_t v = st[1] + s0;-+ size_t n = len < sizeof(v) ? len : sizeof(v);-+ memcpy(p, &v, n);-+ p += n;-+ len -= n;-+ }- }-- /* export good random numbers to the rest of the kernel */- __mockable void- read_random(void * buffer, u_int numbytes)- {-+ if (prng_funcs.generate == NULL) {-+ linux64_prng_fill(buffer, numbytes);-+ return;-+ }- prng_funcs.refresh(prng_ctx);- read_random_generate(buffer, numbytes);- }-@@ -433,7 +466,9 @@ write_random(void * buffer, u_int numbytes)- memcpy(seed, buffer, numbytes);- }--- prng_funcs.reseed(prng_ctx, sizeof(seed), seed);-+ if (prng_funcs.reseed != NULL) {-+ prng_funcs.reseed(prng_ctx, sizeof(seed), seed);-+ }- cc_clear(sizeof(seed), seed);-- return 0;-diff --git a/pexpert/arm/pe_init.c b/pexpert/arm/pe_init.c-index b7134a6..384bacf 100644---- a/pexpert/arm/pe_init.c-+++ b/pexpert/arm/pe_init.c-@@ -292,8 +292,10 @@ PE_init_iokit(void)- uint32_t populate_registry_time_value = 0;-- PE_init_printf(TRUE);-+ { extern void linux64_stage_ext(unsigned long); linux64_stage_ext(7900); }-- printf("iBoot version: %s\n", iBoot_version);-+ { extern void linux64_stage_ext(unsigned long); linux64_stage_ext(7901); }- #if defined(TARGET_OS_OSX) && defined(__arm64__)- printf("iBoot Stage 2 version: %s\n", iBoot_Stage_2_version);- #endif /* defined(TARGET_OS_OSX) && defined(__arm64__) */-@@ -316,6 +318,7 @@ PE_init_iokit(void)- }-- pe_prepare_images();-+ { extern void linux64_stage_ext(unsigned long); linux64_stage_ext(7903); }-- scale = PE_state.video.v_scale;- flip = 1;-@@ -410,12 +413,15 @@ PE_init_iokit(void)- #endif- }--+ { extern void linux64_stage_ext(unsigned long); linux64_stage_ext(8001); }- InitIOKit(PE_state.deviceTreeHead);-+ { extern void linux64_stage_ext(unsigned long); linux64_stage_ext(8002); }- #if defined(XNU_SOURCE_CORECRYPTO14) && XNU_SOURCE_CORECRYPTO14- extern void source_corecrypto14_bootstrap(void);- source_corecrypto14_bootstrap();- #endif- ConfigureIOKit();-+ { extern void linux64_stage_ext(unsigned long); linux64_stage_ext(8003); }- }-- void-@@ -433,8 +439,11 @@ PE_lockdown_iokit(void)- * against a kernel which has not yet enabled the full set of available- * hardware protections.- */-+ extern void linux64_stage_ext(unsigned long);- zalloc_iokit_lockdown();-+ linux64_stage_ext(8211); /* LINUX64 */- StartIOKitMatching();-+ linux64_stage_ext(8212); /* LINUX64 */- }-- void-diff --git a/pexpert/arm/pe_kprintf.c b/pexpert/arm/pe_kprintf.c-index fea9411..af15540 100644---- a/pexpert/arm/pe_kprintf.c-+++ b/pexpert/arm/pe_kprintf.c-@@ -107,6 +107,26 @@ kprintf(const char *fmt, ...)- boolean_t state;- void *caller = __builtin_return_address(0);--+ {-+ /* LINUX64 (xnulinux): hosted XNU prints through the host (dmesg). */-+ extern uintptr_t linux64_hook;-+ if (linux64_hook) {-+ extern int vsnprintf(char *, size_t, const char *, va_list);-+ char buf[256];-+ va_start(listp, fmt);-+ vsnprintf(buf, sizeof(buf), fmt, listp);-+ va_end(listp);-+ register unsigned long x0 __asm__("x0") = 998;-+ register unsigned long x1 __asm__("x1") = (unsigned long)buf;-+ register unsigned long x2 __asm__("x2") = 0;-+ __asm__ volatile ("blr %3" : "+r"(x0), "+r"(x1), "+r"(x2) : "r"(linux64_hook)-+ : "x3", "x4", "x5", "x6", "x7", "x8", "x9", "x10", "x11", "x12", "x13",-+ "x14", "x15", "x16", "x17", "x30", "cc", "memory");-+ (void)caller;-+ return;-+ }-+ }-+- if (!disable_serial_output && !disable_kprintf_output) {- va_start(listp, fmt);- va_copy(listp2, listp);diff --git a/xnu-patches/0002-linux64-host-devices.patch b/xnu-patches/0002-linux64-host-devices.patchnew file mode 100644index 0000000..17a6f3d--- /dev/null+++ b/xnu-patches/0002-linux64-host-devices.patch@@ -0,0 +1,633 @@+The host's devices for the hosted system's drivers (kexts/): network, input, keystore, system disk and host calls+(bsd/kern/linux64_host.c), the wall clock (IOPlatformExpert), a host-file md disk (memdev), no bootloader NVRAM, and the+stand-ins for Apple's AppleKeyStore and IOAESAccelerator services AMFI and AppleImage4 need.++diff --git a/bsd/conf/files b/bsd/conf/files+index 7a2a873..710273d 100644+--- a/bsd/conf/files++++ b/bsd/conf/files+@@ -177,6 +177,7 @@ bsd/net/ether_if_module.c optional ether bound-checks+ bsd/net/ether_inet_pr_module.c optional ether inet bound-checks+ bsd/net/ether_inet6_pr_module.c optional ether inet bound-checks+ bsd/net/if_loop.c optional loop bound-checks++bsd/kern/linux64_host.c standard+ bsd/net/if_mib.c optional networking bound-checks+ bsd/net/if_vlan.c optional vlan bound-checks+ bsd/net/if_fake.c optional if_fake bound-checks+diff --git a/bsd/dev/memdev.c b/bsd/dev/memdev.c+index d24535d..386e6ad 100644+--- a/bsd/dev/memdev.c++++ b/bsd/dev/memdev.c+@@ -76,6 +76,7 @@+ */++ #include <sys/param.h>++#include <linux64/linux64.h>+ #include <sys/kernel.h>+ #include <sys/mount.h>+ #include <sys/namei.h>+@@ -95,6 +96,7 @@+ #include <vm/vm_pager_xnu.h>+ #include <mach/memory_object_types.h>+ #include <kern/debug.h>++#include <kern/kalloc.h>++ #include <miscfs/devfs/devfs.h>++@@ -172,6 +174,7 @@ struct mdev {+ #define mdInited 0x01 /* This device defined */+ #define mdRO 0x02 /* This device is read-only */+ #define mdPhys 0x04 /* This device is in physical memory */++#define mdHost 0x08 /* LINUX64 (xnulinux): backed by a host file, I/O through the host */++ int mdevBMajor = -1;+ int mdevCMajor = -1;+@@ -180,6 +183,38 @@ static int mdevioctl(dev_t dev, u_long cmd, caddr_t data, int flag, struct+ dev_t mdevadd(int devid, uint64_t base, unsigned int size, int phys);+ dev_t mdevlookup(int devid);+ void mdevremoveall(void);++dev_t mdevadd_host(void);++++/*++ * LINUX64 (xnulinux): a hosted XNU's disk backed by a host file. Stage 995 returns its size in bytes (0: none),++ * stage 994 moves bytes between it and a wired kernel buffer (returns the count or -errno).++ */++struct mdev_host_req { uint64_t write, off, len; void *buf; long result; }; /* the hook itself must return 0 */++++static long++mdev_host_call(unsigned long stage, unsigned long arg)++{++ register unsigned long x0 __asm__("x0") = stage;++ register unsigned long x1 __asm__("x1") = arg;++ register unsigned long x2 __asm__("x2") = 0;++ __asm__ volatile ("blr %3" : "+r"(x0), "+r"(x1), "+r"(x2) : "r"(linux64_hook)++ : "x3", "x4", "x5", "x6", "x7", "x8", "x9", "x10", "x11", "x12", "x13",++ "x14", "x15", "x16", "x17", "x30", "cc", "memory");++ return (long)x0;++}++++static int++mdev_host_io(int write, uint64_t off, void *buf, uint64_t len)++{++ struct mdev_host_req q = { .write = (uint64_t)write, .off = off, .len = len, .buf = buf, .result = -EIO };++ long r;++ mdev_host_call(994, (unsigned long)&q);++ r = q.result;++ if (r < 0) {++ return (int)-r;++ }++ return (uint64_t)r == len ? 0 : EIO;++}+ int mdevgetrange(int devid, uint64_t *base, uint64_t *size);++ static int+@@ -228,6 +263,32 @@ mdevrw(dev_t dev, struct uio *uio, __unused int ioflag)+ if (uio_resid(uio) < 0) {+ return EINVAL;+ }++ if (mdev[devid].mdFlags & mdHost) { /* LINUX64 (xnulinux): host-file disk, through a bounce buffer */++ uint64_t end = (uint64_t)mdev[devid].mdSize << 12;++ int write = (uio_rw(uio) == UIO_WRITE);++ char *bounce = kalloc_data(65536, Z_WAITOK);++ status = bounce ? 0 : ENOMEM;++ while (!status && uio_resid(uio) > 0 && (uint64_t)uio->uio_offset < end) {++ uint64_t off = (uint64_t)uio->uio_offset;++ count = (int)MIN((uint64_t)uio_resid(uio), MIN(65536ULL, end - off));++ if (write) {++ status = uiomove(bounce, count, uio);++ if (!status) {++ status = mdev_host_io(1, off, bounce, count);++ }++ } else {++ status = mdev_host_io(0, off, bounce, count);++ if (!status) {++ status = uiomove(bounce, count, uio);++ }++ }++ }++ if (bounce) {++ kfree_data(bounce, 65536);++ }++ return status;++ }+++ mdata = ((addr64_t)mdev[devid].mdBase << 12) + uio->uio_offset; /* Point to the area in "file" */++ saveflag = uio->uio_segflg; /* Remember what the request is */+@@ -242,10 +303,10 @@ mdevrw(dev_t dev, struct uio *uio, __unused int ioflag)+ }+ }++- if (uio->uio_offset > (mdev[devid].mdSize << 12)) {++ if (uio->uio_offset > ((uint64_t)mdev[devid].mdSize << 12)) {+ count = 0;+ } else {+- count = imin(uio_resid(uio), (mdev[devid].mdSize << 12) - uio->uio_offset);++ count = imin(uio_resid(uio), ((uint64_t)mdev[devid].mdSize << 12) - uio->uio_offset);+ }++ status = uiomove64(mdata, count, uio); /* Move the data */+@@ -280,16 +341,16 @@ mdevstrategy(struct buf *bp)+ * we just return with resid == count.+ */++- if (blkoff >= (mdev[devid].mdSize << 12)) { /* Are they trying to read/write at/after end? */+- if (blkoff != (mdev[devid].mdSize << 12)) { /* Are we trying to read after EOF? */++ if (blkoff >= ((uint64_t)mdev[devid].mdSize << 12)) { /* Are they trying to read/write at/after end? */++ if (blkoff != ((uint64_t)mdev[devid].mdSize << 12)) { /* Are we trying to read after EOF? */+ buf_seterror(bp, EINVAL); /* Yeah, this is an error */+ }+ buf_biodone(bp); /* Return */+ return;+ }++- if ((blkoff + buf_count(bp)) > (mdev[devid].mdSize << 12)) { /* Will this read go past end? */+- buf_setcount(bp, (uint32_t)((mdev[devid].mdSize << 12) - blkoff)); /* Yes, trim to max */++ if ((blkoff + buf_count(bp)) > ((uint64_t)mdev[devid].mdSize << 12)) { /* Will this read go past end? */++ buf_setcount(bp, (uint32_t)(((uint64_t)mdev[devid].mdSize << 12) - blkoff)); /* Yes, trim to max */+ }+ /*+ * make sure the buffer's data area is+@@ -299,6 +360,18 @@ mdevstrategy(struct buf *bp)+ panic("ramstrategy: buf_map failed");+ }+++ if (mdev[devid].mdFlags & mdHost) { /* LINUX64 (xnulinux): host-file disk */++ int err = mdev_host_io(!(buf_flags(bp) & B_READ), blkoff, (void *)vaddr, buf_count(bp));++ buf_unmap(bp);++ if (err) {++ buf_seterror(bp, err);++ } else {++ buf_setresid(bp, 0);++ }++ buf_biodone(bp);++ return;++ }+++ fvaddr = (mdev[devid].mdBase << 12) + blkoff; /* Point to offset into ram disk */++ if (buf_flags(bp) & B_READ) { /* Is this a read? */+@@ -434,7 +507,7 @@ mdevioctl(dev_t dev, u_long cmd, caddr_t data, __unused int flag,+ if (!(mdev[devid].mdFlags & mdInited)) {+ return ENXIO;+ }+- *o = ((mdev[devid].mdSize << 12) + mdev[devid].mdSecsize - 1) / mdev[devid].mdSecsize;++ *o = (((uint64_t)mdev[devid].mdSize << 12) + mdev[devid].mdSecsize - 1) / mdev[devid].mdSecsize;+ break;++ /*+@@ -708,6 +781,37 @@ mdevadd(int devid, uint64_t base, unsigned int size, int phys)+ }++++/* LINUX64 (xnulinux): add the host-file disk (if the host has one) as the first free md unit. */++dev_t++mdevadd_host(void)++{++ uint64_t size = 0;++ long bytes;++ dev_t dev;++ int i;++++ if (!linux64_hook) {++ return -1;++ }++ mdev_host_call(995, (unsigned long)&size);++ bytes = (long)size;++ if (bytes < 4096) {++ return -1;++ }++ /* a page-number range no RAM disk can overlap: the host disk has no memory behind it */++ dev = mdevadd(-1, 1ULL << 40, (unsigned int)((uint64_t)bytes >> 12), 0);++ if (dev == (dev_t)-1) {++ return dev;++ }++ for (i = 0; i < NB_MAX_MDEVICES; i++) {++ if ((mdev[i].mdFlags & mdInited) && mdev[i].mdBDev == dev) {++ mdev[i].mdFlags |= mdHost;++ }++ }++ printf("LINUX64: md%x is the host disk (%ld bytes)\n", minor(dev), bytes);++ return dev;++}+++ dev_t+ mdevlookup(int devid)+ {+@@ -760,7 +864,7 @@ mdevgetrange(int devid, uint64_t *base, uint64_t *size)+ }++ *base = mdev[devid].mdBase << 12;+- *size = mdev[devid].mdSize << 12;++ *size = (uint64_t)mdev[devid].mdSize << 12;++ /* make sure (base, size) is a valid range and will not overflow */+ assert(*size < (UINT64_MAX - *base));+diff --git a/bsd/kern/linux64_host.c b/bsd/kern/linux64_host.c+new file mode 100644+index 0000000..00cb495+--- /dev/null++++ b/bsd/kern/linux64_host.c+@@ -0,0 +1,124 @@++/*++ * Copyright (c) 2026 xnulinux contributors. All rights reserved.++ *++ * @APPLE_OSREFERENCE_LICENSE_HEADER_START@++ * This file contains Original Code and/or Modifications of Original Code as defined in and that are subject to the Apple++ * Public Source License Version 2.0 (the 'License'). You may not use this file except in compliance with the License.++ * @APPLE_OSREFERENCE_LICENSE_HEADER_END@++ */++/*++ * LINUX64 (xnulinux): the host's devices for the hosted system's drivers (kexts/), as kernel functions they import.++ * Each is one call into the host (linux64/linux64_abi.h); off the host they do nothing.++ *++ * XnuEthernet linux64_net_send, linux64_net_recv frames through the Linux netdev xnu0 (Linux routes and NATs)++ * XnuInput linux64_input_read evdev records from the host++ * XnuEAN linux64_store_rw the keystore file++ * XnuDisk linux64_disk_size, linux64_disk_rw the system disk++ * XnuDrm linux64_hostcall messages to a Linux service (the GPU bridge, xnudrmd)++ */++#include <sys/param.h>++#include <sys/systm.h>++#include <net/ethernet.h>++#include <linux64/linux64.h>++++#define L64_FRAME_MAX (ETHER_MAX_LEN + 64)++#define L64_ENXIO 6 /* Linux's ENXIO: the host has no such device */++++/* One frame to the host: its length when sent, 0 when not. */++long linux64_net_send(const void *frame, unsigned long length);++long++linux64_net_send(const void *frame, unsigned long length)++{++ struct linux64_buf_req q = { .buf = (void *)(uintptr_t)frame, .len = length, .result = 0 };++++ if (linux64_hook == 0 || length < ETHER_HDR_LEN || length > L64_FRAME_MAX) {++ return 0;++ }++ linux64_call(LINUX64_CALL_NET_SEND, &q);++ return q.result > 0 ? (long)length : 0;++}++++/* The next frame from the host into buffer: its length, 0 when none waits. */++long linux64_net_recv(void *buffer, unsigned long size);++long++linux64_net_recv(void *buffer, unsigned long size)++{++ struct linux64_buf_req q = { .buf = buffer, .len = size, .result = 0 };++++ if (linux64_hook == 0) {++ return 0;++ }++ linux64_call(LINUX64_CALL_NET_RECV, &q);++ return q.result > 0 ? q.result : 0;++}++++/* Whole struct linux64_input_event records into buffer: their bytes, 0 when none wait. */++long linux64_input_read(void *buffer, unsigned long size);++long++linux64_input_read(void *buffer, unsigned long size)++{++ struct linux64_buf_req q = { .buf = buffer, .len = size, .result = 0 };++++ if (linux64_hook == 0) {++ return 0;++ }++ linux64_call(LINUX64_CALL_INPUT_READ, &q);++ return q.result > 0 ? q.result : 0;++}++++static long++linux64_rw(enum linux64_call call, int write, void *buffer, unsigned long length, unsigned long offset)++{++ struct linux64_rw_req q = { .write = (uint64_t)write, .off = offset, .len = length, .buf = buffer, .result = -L64_ENXIO };++++ if (linux64_hook == 0) {++ return -L64_ENXIO;++ }++ linux64_call(call, &q);++ return q.result;++}++++/* The keystore file: `length` bytes at `offset`; bytes moved, or a negative errno. */++long linux64_store_rw(int write, void *buffer, unsigned long length, unsigned long offset);++long++linux64_store_rw(int write, void *buffer, unsigned long length, unsigned long offset)++{++ return linux64_rw(LINUX64_CALL_KEYSTORE_RW, write, buffer, length, offset);++}++++/* The system disk: its size in bytes (0: none), and `length` bytes at `offset` (bytes moved, or a negative errno). */++uint64_t linux64_disk_size(void);++uint64_t++linux64_disk_size(void)++{++ uint64_t size = 0;++++ if (linux64_hook != 0) {++ linux64_call(LINUX64_CALL_DISK_SIZE, &size);++ }++ return size;++}++++long linux64_disk_rw(int write, void *buffer, unsigned long length, unsigned long offset);++long++linux64_disk_rw(int write, void *buffer, unsigned long length, unsigned long offset)++{++ return linux64_rw(LINUX64_CALL_DISK_RW, write, buffer, length, offset);++}++++/*++ * A host call: len bytes at req to a Linux service, its reply into reply (at most max bytes). The reply's length, or a++ * negative errno. The CPU waits in the call.++ */++long linux64_hostcall(const void *req, unsigned long len, void *reply, unsigned long max);++long++linux64_hostcall(const void *req, unsigned long len, void *reply, unsigned long max)++{++ struct linux64_hostcall_req q = { .req = req, .len = len, .reply = reply, .max = max, .result = -L64_ENXIO };++++ if (linux64_hook == 0) {++ return -L64_ENXIO;++ }++ linux64_call(LINUX64_CALL_HOSTCALL, &q);++ return q.result;++}+diff --git a/iokit/Kernel/IONVRAMCHRPHandler.cpp b/iokit/Kernel/IONVRAMCHRPHandler.cpp+index 0cc7f6e..c07d35c 100644+--- a/iokit/Kernel/IONVRAMCHRPHandler.cpp++++ b/iokit/Kernel/IONVRAMCHRPHandler.cpp+@@ -511,6 +511,10 @@ IONVRAMCHRPHandler::unserializeVariables(void)+ if (currentRegion->size == 0) {+ continue;+ }++ /* LINUX64 (xnulinux): no NVRAM image from a bootloader (blank store): no partition to read */++ if (_nvramImage == nullptr || currentRegion->offset == 0xFFFFFFFF) {++ continue;++ }++ DEBUG_INFO("region = %d\n", currentRegion->type);+ cnt = 0;+diff --git a/iokit/Kernel/IOPlatformExpert.cpp b/iokit/Kernel/IOPlatformExpert.cpp+index 76555f6..10d3001 100644+--- a/iokit/Kernel/IOPlatformExpert.cpp++++ b/iokit/Kernel/IOPlatformExpert.cpp+@@ -27,6 +27,7 @@+ */++ #include <IOKit/IOCPU.h>++#include <linux64/linux64.h>+ #include <IOKit/IOPlatformActions.h>+ #include <IOKit/IODeviceTreeSupport.h>+ #include <IOKit/IOKitDebug.h>+@@ -1403,15 +1404,17 @@ PESetGMTTimeOfDay(long secs)+ PESetUTCTimeOfDay(secs, 0);+ }++++ void+ PEGetUTCTimeOfDay(clock_sec_t * secs, clock_usec_t * usecs)+ {+ clock_nsec_t nsecs = 0;++- *secs = 0;+- if (gIOPlatform) {+- gIOPlatform->getUTCTimeOfDay(secs, &nsecs);+- }++ /* LINUX64: hosted, no RTC; the host's wall clock (UTC) through upcall 812 */++ uint64_t host[2] = { 0, 0 };++ linux64_call(LINUX64_CALL_WALLCLOCK, host);++ *secs = (clock_sec_t)host[0];++ nsecs = (clock_nsec_t)host[1];++ assert(nsecs < NSEC_PER_SEC);+ *usecs = nsecs / NSEC_PER_USEC;+@@ -1540,6 +1543,113 @@ IOPlatformExpert::registerNVRAMController(IONVRAMController * caller)+ publishResource("IONVRAM");+ }+++#include <libkern/c++/OSKext.h>++++/*++ * LINUX64 (xnulinux): a stand-in for AppleKeyStore's "AKSKernelServices" table, which AMFI requires (AKS_services()++ * has no path without it). The entries AMFI calls are type-discriminated function pointers: 0x120 (disc 0x61fc,++ * register for a state notification), 0x128 (0x146e, read state), 0x130 (0xd507, unregister). A hosted XNU has no++ * keybag: the queries report unsupported, unregistering succeeds.++ */++#include <ptrauth.h>++static int++linux64_aks_unsupported(void)++{++ return kIOReturnUnsupported;++}++static int++linux64_aks_ok(void)++{++ return 0;++}++static uintptr_t linux64_aks_table[0x40];++++++/*++ * LINUX64 (xnulinux): the stand-in IOAESAccelerator's AES operation (vtable +0x890, called by AppleImage4 with++ * (src, dst, length, iv, direction, ...)). There is no device key to use: it copies src to dst ("encrypts" with the++ * identity), which is all a hosted Image4 nonce store needs to stay consistent.++ */++extern "C" uint64_t kvtophys(vm_offset_t va);++extern "C" void ml_phys_write_double_64(addr64_t paddr, unsigned long long data);++static IOReturn++linux64_aes_perform(IOService *self, IOMemoryDescriptor *src, IOMemoryDescriptor *dst, uint64_t len, void *iv, int dir,++ void *a6, void *a7)++{++ (void)self; (void)iv; (void)dir; (void)a6; (void)a7;++ if (!src || !dst || len > 65536) {++ return kIOReturnBadArgument;++ }++ void *buf = IOMallocData((vm_size_t)len);++ if (!buf) {++ return kIOReturnNoMemory;++ }++ /* the descriptors come unprepared (a real engine prepares them for its DMA): wire them for the copy, each in its++ * own direction (AppleVirtualPlatformXART encrypts in place: one in-out descriptor as both, which a read-only++ * preparation would keep writeBytes from) */++ IOReturn rs = src->prepare(), rd = (src == dst) ? kIOReturnSuccess : dst->prepare();++ IOByteCount got = 0, put = 0;++ if (rs == kIOReturnSuccess && rd == kIOReturnSuccess) {++ got = src->readBytes(0, buf, (IOByteCount)len);++ put = dst->writeBytes(0, buf, got);++ }++ if (rs == kIOReturnSuccess) {++ src->complete();++ }++ if (rd == kIOReturnSuccess && src != dst) {++ dst->complete();++ }++ IOFreeData(buf, (vm_size_t)len);++ return (got == len && put == len) ? kIOReturnSuccess : kIOReturnIOError;++}++++static void++linux64_patch_aes_vtable(OSObject *aes)++{++ uintptr_t vt = (uintptr_t)ptrauth_auth_data(*(void **)aes, ptrauth_key_asda,++ ptrauth_blend_discriminator(aes, 0xcda1));++ uintptr_t entry = vt + 0x890;++ void *fn = ptrauth_strip((void *)&linux64_aes_perform, ptrauth_key_function_pointer);++ uint64_t signed_fn = (uint64_t)ptrauth_sign_unauthenticated(fn, ptrauth_key_asia,++ ptrauth_blend_discriminator((void *)entry, 0x17dc));++ uint64_t pa = kvtophys((vm_offset_t)entry);++ if (pa) {++ ml_phys_write_double_64((addr64_t)pa, signed_fn);++ IOLog("LINUX64: IOAESAccelerator AES entry (vtable %p +0x890) is the hosted copy\n", (void *)vt);++ }++}++++static void++linux64_register_stand_in(IOService *parent, IOService *s, const char *name)++{++ if (s && s->init()) {++ s->setName(name);++ if (s->attach(parent)) {++ s->registerService();++ IOLog("LINUX64: stand-in %s registered\n", name);++ }++ }++ if (s) {++ s->release();++ }++}++static void *++linux64_aks_services(void)++{++ if (!linux64_aks_table[0]) {++ void *un = ptrauth_strip((void *)&linux64_aks_unsupported, ptrauth_key_function_pointer);++ void *ok = ptrauth_strip((void *)&linux64_aks_ok, ptrauth_key_function_pointer);++ for (unsigned i = 1; i < 0x40; i++) {++ linux64_aks_table[i] = (uintptr_t)ptrauth_sign_unauthenticated(un, ptrauth_key_asia, 0);++ }++ linux64_aks_table[0x120 / 8] = (uintptr_t)ptrauth_sign_unauthenticated(un, ptrauth_key_asia, 0x61fc);++ linux64_aks_table[0x128 / 8] = (uintptr_t)ptrauth_sign_unauthenticated(un, ptrauth_key_asia, 0x146e);++ linux64_aks_table[0x130 / 8] = (uintptr_t)ptrauth_sign_unauthenticated(ok, ptrauth_key_asia, 0xd507);++ linux64_aks_table[0] = (uintptr_t)ptrauth_sign_unauthenticated(un, ptrauth_key_asia, 0);++ }++ return linux64_aks_table;++}+++ IOReturn+ IOPlatformExpert::callPlatformFunction(const OSSymbol *functionName,+ bool waitForFunction,+@@ -1564,7 +1674,63 @@ IOPlatformExpert::callPlatformFunction(const OSSymbol *functionName,+ }++ if (waitForFunction) {+- _resources = waitForService(resourceMatching(functionName));++ /*++ * LINUX64 (xnulinux): with the virtual platform's software keystore in the collection (AppleVPKeyStore, as in++ * Apple's VirtualMac), AppleKeyStore provides AKSKernelServices itself: the stand-ins below for the SEP's++ * endpoint and the AES engine are still needed, the stand-in table is not.++ */++ static int linux64_real_aks = -1;++ if (linux64_hook && linux64_real_aks < 0) {++ OSKext *vpks = OSKext::lookupKextWithIdentifier("com.apple.driver.AppleVPKeyStore");++ linux64_real_aks = vpks != NULL;++ OSSafeReleaseNULL(vpks);++ }++ if (linux64_hook && functionName->isEqualTo("AKSKernelServices")) {++ static bool scrd_done;++ if (param1 && !linux64_real_aks) {++ *(void **)param1 = linux64_aks_services();++ }++ if (!scrd_done) {++ /*++ * No SEP either: AMFI's device-state thread waits forever for the SEP's "scrd" endpoint by name (and++ * launchd's first AMFI sysctl waits on that thread). A plain registered service of that name.++ */++ scrd_done = true;++ linux64_register_stand_in(this, OSTypeAlloc(IOService), "sep-endpoint,scrd");++ /*++ * No AES engine either: AppleImage4's finalize waits for an IOAESAccelerator service (it only waits, then++ * releases it). The class is IOCryptoAcceleratorFamily's: an instance of it, registered, with no driver.++ */++ OSObject *aes = OSMetaClass::allocClassWithName("IOAESAccelerator");++ IOService *aess = OSDynamicCast(IOService, aes);++ if (aess) {++ linux64_patch_aes_vtable(aess);++ linux64_register_stand_in(this, aess, "IOAESAccelerator");++ } else {++ IOLog("LINUX64: cannot make an IOAESAccelerator (%p)\n", aes);++ OSSafeReleaseNULL(aes);++ }++ }++ if (!linux64_real_aks) {++ IOLog("LINUX64: AKSKernelServices from the hosted stand-in\n");++ return kIOReturnSuccess;++ }++ }++ if (linux64_hook && linux64_real_aks && functionName->isEqualTo("AKSKernelServices")) {++ _resources = waitForService(resourceMatching(functionName)); /* AppleVPKeyStore publishes it */++ } else if (linux64_hook) {++ /*++ * LINUX64 (xnulinux): a hosted XNU has no providers for some platform functions (AppleKeyStore's, which AMFI++ * waits for): wait a while, then report the function unsupported instead of blocking its caller forever.++ */++ mach_timespec_t t = { 2, 0 };++ _resources = waitForService(resourceMatching(functionName), &t);++ if (_resources == NULL) {++ IOLog("LINUX64: platform function %s has no provider; unsupported\n", functionName->getCStringNoCopy());++ }++ } else {++ _resources = waitForService(resourceMatching(functionName));++ }+ } else {+ _resources = getResourceService();+ }+@@ -2341,6 +2507,7 @@ IOPlatformDevice::getResources( void )+ * the kernel with a suitable message.+ *********************************************************************/++++ class IOPanicPlatform : IOPlatformExpert {+ OSDeclareDefaultStructors(IOPanicPlatform);++@@ -2361,6 +2528,19 @@ IOPanicPlatform::start(IOService * provider)+ platform_name = provider->getName();+ }+++ /*++ * LINUX64 (xnulinux): hosted without the platform kexts, the generic IOPlatformExpert stands in as++ * the platform driver, so matching and gIOPlatform users can proceed.++ */++ if (linux64_hook != 0) {++ IOLog("linux64: no platform driver for \"%s\", using the generic IOPlatformExpert\n", platform_name);++ if (!IOPlatformExpert::start(provider)) {++ return false;++ }++ registerService();++ return true;++ }+++ panic("Unable to find driver for this platform: \"%s\".",+ platform_name);++diff --git a/iokit/bsddev/IOKitBSDInit.cpp b/iokit/bsddev/IOKitBSDInit.cpp+index ae82fc8..3fd837c 100644+--- a/iokit/bsddev/IOKitBSDInit.cpp++++ b/iokit/bsddev/IOKitBSDInit.cpp+@@ -65,6 +65,7 @@ extern "C" {++ extern dev_t mdevadd(int devid, uint64_t base, unsigned int size, int phys);+ extern dev_t mdevlookup(int devid);++extern dev_t mdevadd_host(void);+ extern void mdevremoveall(void);+ extern int mdevgetrange(int devid, uint64_t *base, uint64_t *size);+ extern void di_root_ramfile(IORegistryEntry * entry);+@@ -859,6 +860,9 @@ IOFindBSDRoot( char * rootName, unsigned int rootNameSize,+ }+ regEntry->release(); /* Toss the entry */+ }++ if (mdevlookup(0) < 0) {++ (void)mdevadd_host(); /* LINUX64 (xnulinux): no RAM disk, maybe a host-file disk */++ }+ }++ //diff --git a/xnu-patches/0003-linux64-boot-without-iboot.patch b/xnu-patches/0003-linux64-boot-without-iboot.patchnew file mode 100644index 0000000..24367c8--- /dev/null+++ b/xnu-patches/0003-linux64-boot-without-iboot.patch@@ -0,0 +1,504 @@+Booting a Mac's own APFS system without iBoot or a SEP: trust caches loaded once AppleImage4/AMFI register, SIP+policy from the boot-arg lp-sip0, the unauthenticated-root allowance, the Preboot volume mounted for the boot cryptexes,+and the code-signing exceptions amfi_get_out_of_my_way gives locally built code.++diff --git a/bsd/kern/bsd_init.c b/bsd/kern/bsd_init.c+index 5362b32..9f46961 100644+--- a/bsd/kern/bsd_init.c++++ b/bsd/kern/bsd_init.c+@@ -1,4 +1,5 @@+ #include <kern/boot_progress.h>++#include <linux64/linux64.h>+ /*+ * Copyright (c) 2000-2021 Apple Inc. All rights reserved.+ *+@@ -1083,6 +1084,16 @@ bsd_init(void)+ }+ }+ #endif++ {++ /*++ * LINUX64 (xnulinux): a hosted APFS root is the host's own image, unsealed, with no boot manifest to++ * authenticate it against. With SIP's unauthenticated-root allowance (boot-arg lp-sip0 with 0x800, what++ * "csrutil authenticated-root disable" sets on a Mac) it mounts as it is.++ */++ if (linux64_hook && csr_check(CSR_ALLOW_UNAUTHENTICATED_ROOT) == 0) {++ require_rootauth = FALSE;++ }++ }+ if (require_rootauth) {+ /* enforce sealedness */+ int autherr = VNOP_IOCTL(rootvnode, FSIOC_KERNEL_ROOTAUTH, NULL, 0, vfs_context_kernel());+@@ -1177,6 +1188,24 @@ bsd_init(void)+ }+ #endif /* DEVFS */+++#if CONFIG_MOUNT_PREBOOTRECOVERY++ {++ /*++ * LINUX64 (xnulinux): a hosted APFS root from a Mac's own disk. On a Mac, dyld in launchd grafts the boot++ * cryptexes (the OS cryptex holds the dyld shared cache) from the ignition blob AppleImage4 builds out of iBoot's++ * boot object manifests; a hosted boot has no iBoot. The OS and App cryptexes' contents sit in the Preboot++ * volume's Cryptexes/OS and Cryptexes/App (scripts/mk-macvm-disk.sh), where dyld finds the shared cache: mount++ * the Preboot volume of the root's container at its usual place before launchd runs, as Recovery is mounted.++ */++ if (linux64_hook && rootvnode && strcmp(rootvnode->v_mount->mnt_vfsstat.f_fstypename, "apfs") == 0) {++ char prebootpath[] = "/System/Volumes/Preboot"; /* !const because of internal casting */++ int perr = kernel_mount("apfs", NULLVP, NULLVP, prebootpath, rootvnode->v_mount, 0, 0,++ KERNEL_MOUNT_PREBOOTVOL, vfs_context_kernel());++ printf("LINUX64: Preboot volume at %s: %d\n", prebootpath, perr);++ }++ }++#endif+++ #if CONFIG_BASESYSTEMROOT+ #if CONFIG_IMAGEBOOT+ if (bsdmgroot_bootable()) {+diff --git a/bsd/kern/kern_csr.c b/bsd/kern/kern_csr.c+index 604f16a..7cffe13 100644+--- a/bsd/kern/kern_csr.c++++ b/bsd/kern/kern_csr.c+@@ -226,6 +226,13 @@ csr_bootstrap(void)+ } else {+ csr_config &= ~CSR_ALLOW_UNAUTHENTICATED_ROOT;+ }++++ /* LINUX64 (xnulinux): hosted XNU has no boot policy in its device tree; the boot-arg lp-sip0 stands in for it (0x2 lets++ * rootless_check_trusted_class accept /Library/GPUBundles, where Metal finds the hosted system's plugin). */++ uint32_t hosted_sip;++ if (PE_parse_boot_argn("lp-sip0", &hosted_sip, sizeof(hosted_sip))) {++ csr_config |= hosted_sip & ~CSR_ALLOW_APPLE_INTERNAL;++ }+ }+ STARTUP(TUNABLES, STARTUP_RANK_FIRST, csr_bootstrap);++diff --git a/bsd/kern/kern_descrip.c b/bsd/kern/kern_descrip.c+index fac307f..bfc5687 100644+--- a/bsd/kern/kern_descrip.c++++ b/bsd/kern/kern_descrip.c+@@ -73,6 +73,7 @@+ */++ #include <sys/param.h>++#include <linux64/linux64.h>+ #include <sys/systm.h>+ #include <sys/filedesc.h>+ #include <sys/kernel.h>+@@ -113,11 +114,25 @@+ #include <kern/waitq.h>+ #include <kern/ipc_kobject.h>+ #include <kern/ipc_misc.h>++#include <pexpert/pexpert.h>+ #include <kern/ast.h>++ #include <vm/vm_protos.h>+ #include <mach/mach_port.h>+++/* LINUX64: hosted with the amfi_get_out_of_my_way boot-arg, code signing lets any locally built code load (kern_mman.c too) */++int linux64_amfi_off(void);++int++linux64_amfi_off(void)++{++ static int off = -1;++ if (off < 0) {++ int v = 0;++ off = PE_parse_boot_argn("amfi_get_out_of_my_way", &v, sizeof(v)) && v != 0;++ }++ return off;++}+++ #include <security/audit/audit.h>+ #if CONFIG_MACF+ #include <security/mac_framework.h>+@@ -2525,6 +2540,32 @@ sys_dup2(proc_t p, struct dup2_args *uap, int32_t *retval)+ return dup2(p, p_cred, uap->from, uap->to, retval);+ }+++/*++ * LINUX64: dup3(from, to, flags), system call 149 in macOS 27's libsystem_kernel: dup2 that fails when from == to and++ * takes O_CLOEXEC for the new descriptor.++ */++int++sys_dup3(proc_t p, struct dup3_args *uap, int32_t *retval)++{++ kauth_cred_t p_cred = current_cached_proc_cred(p);++ int error;++++ if ((uap->flags & ~O_CLOEXEC) || uap->from == uap->to) {++ return EINVAL;++ }++ error = dup2(p, p_cred, uap->from, uap->to, retval);++ if (error == 0 && (uap->flags & O_CLOEXEC)) {++ struct fileproc *fp;++++ proc_fdlock(p);++ if ((fp = fp_get_noref_locked(p, uap->to)) != NULL) {++ fp->fp_flags |= FP_CLOEXEC;++ }++ proc_fdunlock(p);++ }++ return error;++}+++ int+ dup2(proc_t p, kauth_cred_t p_cred, int old, int new, int *retval)+ {+@@ -4412,8 +4453,15 @@ dropboth:+ }++ #if CONFIG_MACF+- error = mac_file_check_library_validation(p, fg, lv.lv_file_start,+- (user_long_t)lv.lv_error_message, lv.lv_error_message_size);++ /*++ * LINUX64: hosted with amfi_get_out_of_my_way, a process may load any library, as it may run any binary:++ * AMFI otherwise rejects the locally built (ad-hoc, linker-signed) Python extension modules a locally built++ * python dlopens ("mapping process and mapped file (non-platform) have different Team IDs").++ */++ if (!linux64_amfi_off()) {++ error = mac_file_check_library_validation(p, fg, lv.lv_file_start,++ (user_long_t)lv.lv_error_message, lv.lv_error_message_size);++ }+ #endif++ break;+diff --git a/bsd/kern/kern_exec.c b/bsd/kern/kern_exec.c+index 2bf34ab..3777cc5 100644+--- a/bsd/kern/kern_exec.c++++ b/bsd/kern/kern_exec.c+@@ -1,4 +1,5 @@+ #include <kern/boot_progress.h>++#include <linux64/linux64.h>+ /*+ * Copyright (c) 2000-2020 Apple Inc. All rights reserved.+ *+@@ -2888,6 +2889,7 @@ badtoolate:+ if (bootarg_execfailurereports) {+ set_proc_name(imgp, current_proc());+ }++ { if (exec_failure_reason) kprintf("linux64: exec kill (badtoolate) \"%s\" reason ns %u code 0x%llx\n", current_proc()->p_name, exec_failure_reason->osr_namespace, (unsigned long long)exec_failure_reason->osr_code); }+ psignal_with_reason(current_proc(), SIGKILL, exec_failure_reason);+ exec_failure_reason = OS_REASON_NULL;++@@ -5701,6 +5703,7 @@ bad:+ }++ if (exec_failure_reason && !spawn_no_exec) {++ { if (exec_failure_reason) kprintf("linux64: exec kill (exec end) \"%s\" reason ns %u code 0x%llx\n", current_proc()->p_name, exec_failure_reason->osr_namespace, (unsigned long long)exec_failure_reason->osr_code); }+ psignal_with_reason(p, SIGKILL, exec_failure_reason);+ exec_failure_reason = NULL;+ }+@@ -8304,6 +8307,13 @@ load_init_program(proc_t p)+ boot_progress_stage("root check enter");+ int cache_error = native_owner_cache_prepare(p, (user_addr_t)scratch_addr, &init_envp);+ boot_progress_stage("root check returned");++ {++ /* LINUX64 (xnulinux): a hosted test root (no macOS OS volume, no boot manifest) skips the owner root check */++ if (cache_error && linux64_hook) {++ printf("linux64: owner root check failed (%d); continuing on a test root\n", cache_error);++ cache_error = 0;++ }++ }+ if (cache_error) panic("offline owner root check failed: %d", cache_error);+ #endif+ #if defined(XNU_BOOT_PROGRESS) && XNU_BOOT_PROGRESS+@@ -8741,6 +8751,7 @@ proc_process_signature(proc_t p, os_reason_t *signature_failure_reason)++ if (kr != KERN_SUCCESS) {+ error = EINVAL;++ kprintf("linux64: exec refused \"%s\": machine_task_process_signature: %s\n", p->p_name, error_msg ? error_msg : "(no message)");++ if (error_msg != NULL) {+ uint32_t error_msg_len = (uint32_t)strlen(error_msg) + 1;+@@ -8843,6 +8854,23 @@ process_signature(proc_t p, struct image_params *imgp)+ * which is unexpected but security framework does not+ * approve of exec, kill and return immediately.+ */++ if (imgp->ip_mac_return != 0) {++ /*++ * LINUX64 (xnulinux): under amfi_get_out_of_my_way AMFI's other verdicts on code are already skipped (F_CHECK_LV, exec++ * mmap); its execve hook still refuses some of Apple's own daemons ("dyld signature cannot be verified": system_installd,++ * MobileSoftwareUpdate services), so the same mode lets those execs go on.++ */++ if (linux64_amfi_off()) {++ kprintf("linux64: exec \"%s\": MAC policy verdict %d ignored (amfi_get_out_of_my_way)\n",++ imgp->ip_vp ? imgp->ip_vp->v_name : "?", imgp->ip_mac_return);++ imgp->ip_mac_return = 0;++ if (imgp->ip_cs_error != OS_REASON_NULL) {++ /* the same hook files its refusal as a code-signing exit reason too */++ os_reason_free(imgp->ip_cs_error);++ imgp->ip_cs_error = OS_REASON_NULL;++ }++ }++ }+ if (imgp->ip_mac_return != 0) {+ boot_progress_process_stage(proc_getpid(p),p->p_name,"exec MAC policy REFUSED");+ KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,+@@ -8850,6 +8878,7 @@ process_signature(proc_t p, struct image_params *imgp)+ signature_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_SECURITY_POLICY);+ error = imgp->ip_mac_return;+ unexpected_failure = TRUE;++ kprintf("linux64: exec refused \"%s\": MAC policy (ip_mac_return %d)\n", imgp->ip_vp ? imgp->ip_vp->v_name : "?", error);+ goto done;+ }++@@ -8857,6 +8886,8 @@ process_signature(proc_t p, struct image_params *imgp)+ signature_failure_reason = imgp->ip_cs_error;+ imgp->ip_cs_error = OS_REASON_NULL;+ error = EACCES;++ kprintf("linux64: exec refused \"%s\": code signature error (ns %u code 0x%llx)\n", imgp->ip_vp ? imgp->ip_vp->v_name : "?",++ signature_failure_reason->osr_namespace, (unsigned long long)signature_failure_reason->osr_code);+ goto done;+ }++@@ -8864,6 +8895,7 @@ process_signature(proc_t p, struct image_params *imgp)+ os_reason_t launch_constraint_reason;+ if ((error = mac_proc_check_launch_constraints(p, imgp, &launch_constraint_reason)) != 0) {+ signature_failure_reason = launch_constraint_reason;++ kprintf("linux64: exec refused \"%s\": launch constraints (error %d)\n", imgp->ip_vp ? imgp->ip_vp->v_name : "?", error);+ goto done;+ }++@@ -9059,6 +9091,7 @@ done:+ proc_csflags_set(p, CS_KILLED);+ }+ /* make very sure execution fails */++ { if (signature_failure_reason) kprintf("linux64: exec kill (signature) \"%s\" reason ns %u code 0x%llx\n", current_proc()->p_name, signature_failure_reason->osr_namespace, (unsigned long long)signature_failure_reason->osr_code); }+ if (vfexec || spawn) {+ assert(signature_failure_reason != OS_REASON_NULL);+ psignal_vfork_with_reason(p, proc_task(p), imgp->ip_new_thread,+diff --git a/bsd/kern/kern_mman.c b/bsd/kern/kern_mman.c+index 32d27c9..ec691bb 100644+--- a/bsd/kern/kern_mman.c++++ b/bsd/kern/kern_mman.c+@@ -78,6 +78,7 @@+ */++ #include <sys/param.h>++#include <linux64/linux64.h>+ #include <sys/systm.h>+ #include <sys/filedesc.h>+ #include <sys/proc_internal.h>+@@ -487,7 +488,12 @@ mmap(proc_t p, struct mmap_args *uap, user_addr_t *retval)+ /*+ * Entitlement check.+ */+- error = mac_proc_check_map_anon(p, current_cached_proc_cred(p),++ /*++ * LINUX64 (xnulinux): under amfi_get_out_of_my_way a JIT mapping is let through without the JIT entitlement, as++ * AMFI's other verdicts on code are (F_CHECK_LV, executable mmap): the CPU Metal device (Mesa's llvmpipe) compiles++ * shaders to machine code in every Metal client, WindowServer included, which is hardened and not JIT-entitled.++ */++ error = ((flags & MAP_JIT) && linux64_amfi_off()) ? 0 : mac_proc_check_map_anon(p, current_cached_proc_cred(p),+ user_addr, user_size, prot, flags, &maxprot);+ if (error) {+ return EINVAL;+@@ -669,7 +675,8 @@ mmap(proc_t p, struct mmap_args *uap, user_addr_t *retval)++ handle = (void *)vp;+ #if CONFIG_MACF+- error = mac_file_check_mmap(vfs_context_ucred(ctx),++ /* LINUX64: with amfi_get_out_of_my_way, executable mappings of locally built (ad-hoc signed) libraries too */++ error = linux64_amfi_off() ? 0 : mac_file_check_mmap(vfs_context_ucred(ctx),+ fp->fp_glob, prot, flags, file_pos, &maxprot);+ if (error) {+ (void)vnode_put(vp);+diff --git a/bsd/kern/kern_trustcache.c b/bsd/kern/kern_trustcache.c+index 4b1e8a9..076bc9c 100644+--- a/bsd/kern/kern_trustcache.c++++ b/bsd/kern/kern_trustcache.c+@@ -21,6 +21,7 @@+ */++ #include <os/atomic_private.h>++#include <linux64/linux64.h>+ #include <os/overflow.h>+ #include <pexpert/pexpert.h>+ #include <pexpert/device_tree.h>+@@ -78,6 +79,29 @@ SYSCTL_UINT(+ 0, "number of loadable trust caches loaded"+ );+++/* LINUX64 (xnulinux) */++static bool linux64_trust_cache_skipped = false;++++/*++ * LINUX64 (xnulinux): the runtime is skipped at boot until the AppleImage4 and AMFI kexts register their interfaces++ * (they start with the kernel collection); once both are there, set it up and load the static trust cache the host++ * passes (chosen/memory-map/TrustCache), so AMFI validates the OS's platform binaries as on a booted Mac.++ */++void linux64_trust_cache_late_init(void);++void++linux64_trust_cache_late_init(void)++{++ if (!linux64_trust_cache_skipped || img4if == NULL || amfi == NULL) {++ return;++ }++ linux64_trust_cache_skipped = false;++ trust_cache_runtime_init();++ if (!linux64_trust_cache_skipped) {++ load_static_trust_cache();++ printf("linux64: trust cache runtime set up late; static trust caches: %u\n", num_static_trust_caches);++ }++}+++ #if CONFIG_SPTM+ /*+ * We have the TrustedExecutionMonitor environment available. All of our artifacts+@@ -124,6 +148,16 @@ get_trust_cache_info(void)+ void+ trust_cache_runtime_init(void)+ {++ /*++ * LINUX64 (xnulinux): hosted without the AppleImage4/AMFI kexts that register img4if/amfi.++ * Skip the trust cache runtime until they are loaded (the kernel collection's kexts).++ */++ if (linux64_hook != 0 && (img4if == NULL || amfi == NULL)) {++ linux64_trust_cache_skipped = true;++ printf("linux64: no image4/AMFI interface, trust cache runtime skipped\n");++ return;++ }+++ /* Image4 interface needs to be available */+ if (img4if == NULL) {+ panic("image4 interface not available");+@@ -402,6 +436,16 @@ trust_cache_runtime_init(void)+ allow_engineering_caches = true;+ }+++ /*++ * LINUX64 (xnulinux): hosted without the AppleImage4/AMFI kexts that register img4if/amfi.++ * Skip the trust cache runtime until they are loaded (the kernel collection's kexts).++ */++ if (linux64_hook != 0 && (img4if == NULL || amfi == NULL)) {++ linux64_trust_cache_skipped = true;++ printf("linux64: no image4/AMFI interface, trust cache runtime skipped\n");++ return;++ }+++ /* Image4 interface needs to be available */+ if (img4if == NULL) {+ panic("image4 interface not available");+@@ -579,6 +623,16 @@ trust_cache_runtime_init(void)+ allow_legacy_caches = true;+ #endif+++ /*++ * LINUX64 (xnulinux): hosted without the AppleImage4/AMFI kexts that register img4if/amfi.++ * Skip the trust cache runtime until they are loaded (the kernel collection's kexts).++ */++ if (linux64_hook != 0 && (img4if == NULL || amfi == NULL)) {++ linux64_trust_cache_skipped = true;++ printf("linux64: no image4/AMFI interface, trust cache runtime skipped\n");++ return;++ }+++ /* Image4 interface needs to be available */+ if (img4if == NULL) {+ panic("image4 interface not available");+@@ -1175,6 +1229,10 @@ load_static_trust_cache(void)+ /* Mark this function as having been called */+ trust_cache_static_init = true;+++ if (linux64_trust_cache_skipped) {++ return;++ }+++ /* Nothing to do when the runtime isn't set */+ if (trust_cache_rt == NULL) {+ return;+diff --git a/bsd/pthread/pthread_shims.c b/bsd/pthread/pthread_shims.c+index e5e58b5..624d739 100644+--- a/bsd/pthread/pthread_shims.c++++ b/bsd/pthread/pthread_shims.c+@@ -29,6 +29,7 @@+ #define PTHREAD_INTERNAL 1++ #include <stdatomic.h>++#include <linux64/linux64.h>+ #include <kern/debug.h>+ #include <kern/mach_param.h>+ #include <kern/sched_prim.h>+@@ -316,6 +317,11 @@ void+ pthread_init(void)+ {+ if (!pthread_functions) {++ /* LINUX64 (xnulinux): pthread.kext registers late (with the collection's kexts); continue without it until then. */++ if (linux64_hook) {++ printf("linux64: pthread kext not loaded, pthread support skipped\n");++ return;++ }+ panic("pthread kernel extension not loaded (function table is NULL).");+ }+ pthread_functions->pthread_init();+@@ -324,6 +330,9 @@ pthread_init(void)+ void+ pth_proc_hashinit(proc_t p)+ {++ if (!pthread_functions) {++ return; /* LINUX64: hosted without pthread.kext */++ }+ pthread_functions->pth_proc_hashinit(p);+ }++diff --git a/bsd/vfs/vfs_subr.c b/bsd/vfs/vfs_subr.c+index 229d6a1..913adf3 100644+--- a/bsd/vfs/vfs_subr.c++++ b/bsd/vfs/vfs_subr.c+@@ -78,6 +78,7 @@+ */++ #include <sys/param.h>++#include <linux64/linux64.h>+ #include <sys/systm.h>+ #include <sys/proc_internal.h>+ #include <sys/kauth.h>+@@ -1144,7 +1145,14 @@ vfs_rootmountalloc_internal(struct vfstable *vfsp, const char *devname)++ mp->mnt_vtable = vfsp;+ mp->mnt_op = vfsp->vfc_vfsops;+- mp->mnt_flag = MNT_RDONLY | MNT_ROOTFS;++ {++ /*++ * LINUX64 (xnulinux): a hosted HFS+ root (the host-file disk) mounts read-write; nothing here runs the boot++ * tasks that would remount it (logd traps on EROFS writing /private/var/db/diagnostics). APFS refuses a++ * writable root at mountroot ("can't mount root filesystem writeable"): an APFS root mounts read-only, as on a Mac.++ */++ mp->mnt_flag = (linux64_hook && strcmp(vfsp->vfc_name, "hfs") == 0 ? 0 : MNT_RDONLY) | MNT_ROOTFS;++ }+ mp->mnt_vnodecovered = NULLVP;+ //mp->mnt_stat.f_type = vfsp->vfc_typenum;+ mp->mnt_flag |= vfsp->vfc_flags & MNT_VISFLAGMASK;+diff --git a/libkern/amfi/amfi.c b/libkern/amfi/amfi.c+index 58df36b..bcd81f2 100644+--- a/libkern/amfi/amfi.c++++ b/libkern/amfi/amfi.c+@@ -1,4 +1,5 @@+ #include <libkern/libkern.h>++#include <linux64/linux64.h>+ #include <libkern/section_keywords.h>+ #include <libkern/amfi/amfi.h>++@@ -12,6 +13,7 @@ amfi_interface_register(const amfi_t *mfi)+ panic("AppleMobileFileIntegrity interface already set");+ }+ amfi = mfi;++ linux64_trust_cache_late_init();+ }++ void+diff --git a/libkern/img4/interface.c b/libkern/img4/interface.c+index 3863334..596770a 100644+--- a/libkern/img4/interface.c++++ b/libkern/img4/interface.c+@@ -1,4 +1,5 @@+ #include <libkern/libkern.h>++#include <linux64/linux64.h>+ #include <libkern/section_keywords.h>+ #include <libkern/img4/interface.h>++@@ -15,4 +16,5 @@ img4_interface_register(const img4_interface_t *i4)+ panic("img4 interface already set");+ }+ img4if = i4;++ linux64_trust_cache_late_init();+ }diff --git a/xnu-patches/0004-linux64-macos27-userland.patch b/xnu-patches/0004-linux64-macos27-userland.patchnew file mode 100644index 0000000..512d096--- /dev/null+++ b/xnu-patches/0004-linux64-macos27-userland.patch@@ -0,0 +1,261 @@+What macOS 27's userland needs of xnu-12377: the system calls its libsystem_kernel calls (pipe2, dup3, fchflagsat,+getumask; ENOSYS without SIGSYS for the ones it probes), a vnode table and workqueue limits for a full userland on one+CPU, and a log line for fatal exceptions and missing system calls.++diff --git a/bsd/dev/arm/systemcalls.c b/bsd/dev/arm/systemcalls.c+index 5a7b717..5c12c8f 100644+--- a/bsd/dev/arm/systemcalls.c++++ b/bsd/dev/arm/systemcalls.c+@@ -132,6 +132,10 @@ unix_syscall(++ uthread->uu_flag |= UT_NOTCANCELPT;+ uthread->syscall_code = code;++ if (__improbable(callp->sy_call == (sy_call_t *)nosys)) { /* LINUX64: who calls a system call this kernel does not have */++ kprintf("linux64: nosys %d from pid %d %s pc 0x%llx lr 0x%llx\n", code, proc_pid(proc), proc->p_comm,++ (unsigned long long)get_saved_state_pc(state), (unsigned long long)get_saved_state_lr(state));++ }++ uthread->uu_rval[0] = 0;++diff --git a/bsd/dev/unix_startup.c b/bsd/dev/unix_startup.c+index ec19ee7..0bbea03 100644+--- a/bsd/dev/unix_startup.c++++ b/bsd/dev/unix_startup.c+@@ -33,6 +33,7 @@+ */++ #include <mach/mach_types.h>++#include <linux64/linux64.h>++ #include <kern/startup.h>+ #include <vm/vm_kern_xnu.h>+@@ -186,6 +187,20 @@ bsd_startupearly(void)+ }+ #endif+ }++ {++ /* LINUX64 (xnulinux): hosted, size the vnode table from the DRAM xnu.ko gave us (sane_size may not be set yet) */++ extern uint64_t max_mem;++ if (linux64_hook) {++ kprintf("linux64: desiredvnodes %d (sane_size 0x%llx max_mem 0x%llx)\n", desiredvnodes, (uint64_t)sane_size, (uint64_t)max_mem);++ /* the k27 config's CONFIG_VNODES (1024) is for a small device; a full macOS userland needs far more */++ if (desiredvnodes < (int)(max_mem / 65536) + 1024) {++ desiredvnodes = (int)(max_mem / 65536) + 1024;++ if (desiredvnodes > 263168) {++ desiredvnodes = 263168;++ }++ }++ }++ }+ vnodes_sized = 1;+ }+ }+diff --git a/bsd/kern/kern_exit.c b/bsd/kern/kern_exit.c+index 6e740c2..bfbdd29 100644+--- a/bsd/kern/kern_exit.c++++ b/bsd/kern/kern_exit.c+@@ -3792,6 +3792,9 @@ exit_with_mach_exception(++ printf("[%s: killed] exiting with signal %d, force exiting the process\n",+ proc_best_name(p), SIGKILL);++ kprintf("linux64: [%s] fatal mach exception type %d code 0x%llx subcode 0x%llx reason ns %u code 0x%llx\n",++ proc_best_name(p), (int)exception.exception_type, (unsigned long long)exception.mx_code,++ (unsigned long long)exception.mx_subcode, reason->osr_namespace, (unsigned long long)reason->osr_code);++ /* consumes reason */+ return exit_with_reason(p, W_EXITCODE(0, SIGKILL), NULL,+diff --git a/bsd/kern/sys_pipe.c b/bsd/kern/sys_pipe.c+index bd682ab..64d7fa9 100644+--- a/bsd/kern/sys_pipe.c++++ b/bsd/kern/sys_pipe.c+@@ -388,8 +388,29 @@ expand_pipespace(struct pipe *p, int target_size)+ */++ /* ARGSUSED */++static int pipe_flags(proc_t p, int32_t *retval, int flags);+++ int+ pipe(proc_t p, __unused struct pipe_args *uap, int32_t *retval)++{++ return pipe_flags(p, retval, 0);++}++++/*++ * LINUX64: pipe2(fildes, flags), system call 148 in macOS 27's libsystem_kernel (__pipe2 returns the two descriptors in++ * x0/x1 as __pipe does, then stores them). Flags: O_CLOEXEC and O_NONBLOCK, on both ends.++ */++int++pipe2(proc_t p, struct pipe2_args *uap, int32_t *retval)++{++ if (uap->flags & ~(O_CLOEXEC | O_NONBLOCK)) {++ return EINVAL;++ }++ return pipe_flags(p, retval, uap->flags);++}++++static int++pipe_flags(proc_t p, int32_t *retval, int flags)+ {+ struct fileproc *rf, *wf;+ struct pipe *rpipe, *wpipe;+@@ -409,7 +430,10 @@ pipe(proc_t p, __unused struct pipe_args *uap, int32_t *retval)+ if (error) {+ goto freepipes;+ }+- rf->f_flag = FREAD;++ rf->f_flag = FREAD | ((flags & O_NONBLOCK) ? FNONBLOCK : 0);++ if (flags & O_CLOEXEC) {++ rf->fp_flags |= FP_CLOEXEC;++ }+ rf->f_ops = &pipeops;+ fp_set_data(rf, rpipe);++@@ -418,7 +442,10 @@ pipe(proc_t p, __unused struct pipe_args *uap, int32_t *retval)+ fp_free(p, retval[0], rf);+ goto freepipes;+ }+- wf->f_flag = FWRITE;++ wf->f_flag = FWRITE | ((flags & O_NONBLOCK) ? FNONBLOCK : 0);++ if (flags & O_CLOEXEC) {++ wf->fp_flags |= FP_CLOEXEC;++ }+ wf->f_ops = &pipeops;+ fp_set_data(wf, wpipe);++diff --git a/bsd/kern/syscalls.master b/bsd/kern/syscalls.master+index c08a74c..1e26f75 100644+--- a/bsd/kern/syscalls.master++++ b/bsd/kern/syscalls.master+@@ -229,8 +229,8 @@+ 145 AUE_NULL ALL { int nosys(void); } { old setrlimit }+ 146 AUE_NULL ALL { int nosys(void); } { old killpg }+ 147 AUE_SETSID ALL { int setsid(void); }+-148 AUE_NULL ALL { int nosys(void); } { old setquota }+-149 AUE_NULL ALL { int nosys(void); } { old qquota }++148 AUE_PIPE ALL { int pipe2(user_addr_t fildes, int flags) NO_SYSCALL_STUB; } { LINUX64 macOS 27 pipe2 }++149 AUE_DUP2 ALL { int sys_dup3(u_int from, u_int to, int flags); } { LINUX64 macOS 27 dup3 }+ 150 AUE_NULL ALL { int nosys(void); } { old getsockname }+ 151 AUE_GETPGID ALL { int getpgid(pid_t pid); }+ 152 AUE_SETPRIVEXEC ALL { int setprivexec(int flag); }+@@ -309,8 +309,8 @@+ 212 AUE_NULL ALL { int nosys(void); } { old ATgetrsp }+ 213 AUE_NULL ALL { int nosys(void); } { Reserved for AppleTalk }++-214 AUE_NULL ALL { int nosys(void); }+-215 AUE_NULL ALL { int nosys(void); }++214 AUE_CHFLAGS ALL { int fchflagsat(int fd, user_addr_t path, int flags, int atflag); } { LINUX64 macOS 27 fchflagsat }++215 AUE_UMASK ALL { int getumask(void); } { LINUX64 macOS 27 getumask }++ ; System Calls 216 - 230 are reserved for calls to support HFS/HFS Plus+ ; file system semantics. Currently, we only use 215-227. The rest is+@@ -351,8 +351,8 @@+ 243 AUE_INITGROUPS ALL { int initgroups(u_int gidsetsize, gid_t *gidset, int gmuid) NO_SYSCALL_STUB; }+ 244 AUE_POSIX_SPAWN ALL { int posix_spawn(pid_t *pid, const char *path, const struct _posix_spawn_args_desc *adesc, char **argv, char **envp) NO_SYSCALL_STUB; }+ 245 AUE_FFSCTL ALL { int ffsctl(int fd, u_long cmd, caddr_t data, u_int options); }+-246 AUE_NULL ALL { int nosys(void); }+-247 AUE_NULL ALL { int nosys(void); } { old nfsclnt }++246 AUE_NULL ALL { int enosys(void); } { LINUX64 macOS 27 aio_readv ENOSYS without SIGSYS }++247 AUE_NULL ALL { int enosys(void); } { LINUX64 macOS 27 aio_writev ENOSYS without SIGSYS }++ #if NFSSERVER /* XXX */+ 248 AUE_FHOPEN ALL { int fhopen(const struct fhandle *u_fhp, int flags); }+@@ -360,7 +360,7 @@+ 248 AUE_NULL ALL { int nosys(void); }+ #endif++-249 AUE_NULL ALL { int nosys(void); }++249 AUE_NULL ALL { int enosys(void); } { LINUX64 macOS 27 fsctlat ENOSYS without SIGSYS }+ 250 AUE_MINHERIT ALL { int minherit(caddr_ut addr, size_ut len, int inherit); }+ #if SYSV_SEM+ 251 AUE_SEMSYS ALL { int semsys(u_int which, int a2, int a3, int a4, int a5) NO_SYSCALL_STUB; }+@@ -530,7 +530,7 @@+ 349 AUE_NULL ALL { int __pthread_fchdir(int fd); }+ 350 AUE_AUDIT ALL { int audit(void *record, int length); }+ 351 AUE_AUDITON ALL { int auditon(int cmd, void *data, int length); }+-352 AUE_NULL ALL { int nosys(void); }++352 AUE_NULL ALL { int enosys(void); } { LINUX64 macOS 27 guarded_ftruncate_np ENOSYS without SIGSYS }+ 353 AUE_GETAUID ALL { int getauid(au_id_t *auid); }+ 354 AUE_SETAUID ALL { int setauid(au_id_t *auid); }+ 355 AUE_NULL ALL { int nosys(void); } { old getaudit }+diff --git a/bsd/pthread/pthread_workqueue.c b/bsd/pthread/pthread_workqueue.c+index cb27db6..924caf2 100644+--- a/bsd/pthread/pthread_workqueue.c++++ b/bsd/pthread/pthread_workqueue.c+@@ -28,6 +28,7 @@+ /* Copyright (c) 1995-2018 Apple, Inc. All Rights Reserved */++ #include <sys/cdefs.h>++#include <linux64/linux64.h>++ #include <kern/assert.h>+ #include <kern/ast.h>+@@ -2117,6 +2118,20 @@ workq_open(struct proc *p, __unused struct workq_open_args *uap,+ }++ wq_max_cooperative_threads = num_cpus;++ {++ /*++ * LINUX64 (xnulinux): hosted XNU has one CPU. With a parallelism of 1 a process whose main thread waits++ * on work it queued (ld's layout: dispatch_group_wait) never got a worker admitted; allow a few++ * constrained threads per QoS bucket (the cooperative pool stays at the CPU count), as a small multi-core machine would.++ */++ if (linux64_hook) {++ for (int b = 0; b < WORKQ_NUM_QOS_BUCKETS; b++) {++ if (wq_max_parallelism[b] < 4) {++ wq_max_parallelism[b] = 4;++ }++ }++ }++ }++ wq_init_constrained_limit = 0;+ }+diff --git a/bsd/vfs/vfs_syscalls.c b/bsd/vfs/vfs_syscalls.c+index 873eb8f..a15ea6b 100644+--- a/bsd/vfs/vfs_syscalls.c++++ b/bsd/vfs/vfs_syscalls.c+@@ -8018,6 +8018,44 @@ chflags(__unused proc_t p, struct chflags_args *uap, __unused int32_t *retval)+ return error;+ }+++/*++ * LINUX64: fchflagsat(fd, path, flags, atflag), system call 214 in macOS 27's libsystem_kernel: chflags relative to fd++ * (AT_FDCWD for the working directory), not following a final symlink with AT_SYMLINK_NOFOLLOW.++ */++int++fchflagsat(__unused proc_t p, struct fchflagsat_args *uap, __unused int32_t *retval)++{++ vnode_t vp;++ vfs_context_t ctx = vfs_context_current();++ int error;++ struct nameidata nd;++++ if (uap->atflag & ~AT_SYMLINK_NOFOLLOW) {++ return EINVAL;++ }++ AUDIT_ARG(fflags, uap->flags);++ NDINIT(&nd, LOOKUP, OP_SETATTR, ((uap->atflag & AT_SYMLINK_NOFOLLOW) ? NOFOLLOW : FOLLOW) | AUDITVNPATH1,++ UIO_USERSPACE, uap->path, ctx);++ error = nameiat(&nd, uap->fd);++ if (error) {++ return error;++ }++ vp = nd.ni_vp;++ nameidone(&nd);++ /* chflags1 drops the vnode reference */++ return chflags1(vp, uap->flags, ctx);++}++++/*++ * LINUX64: getumask(), system call 215 in macOS 27's libsystem_kernel: the file creation mask, unchanged.++ */++int++getumask(proc_t p, __unused struct getumask_args *uap, int32_t *retval)++{++ *retval = p->p_fd.fd_cmask;++ return 0;++}+++ /*+ * Change flags of a file given a file descriptor.+ */diff --git a/xnu-patches/include/linux64.h b/xnu-patches/include/linux64.hnew file mode 100644index 0000000..6e7f8f8--- /dev/null+++ b/xnu-patches/include/linux64.h@@ -0,0 +1,108 @@+/*+ * Copyright (c) 2026 xnulinux contributors. All rights reserved.+ *+ * @APPLE_OSREFERENCE_LICENSE_HEADER_START@+ * This file contains Original Code and/or Modifications of Original Code as defined in and that are subject to the Apple+ * Public Source License Version 2.0 (the 'License'). You may not use this file except in compliance with the License.+ * @APPLE_OSREFERENCE_LICENSE_HEADER_END@+ */+/*+ * The LINUX64 machine layer: XNU hosted inside a Linux kernel by xnu.ko. Everything the rest of XNU uses of it.+ * Copied with linux64_abi.h into EXTERNAL_HEADERS/linux64 (on every component's include path) when the patches are+ * applied (scripts/vm-xnu-rebuild.sh).+ *+ * Hosted or not is decided at run time: linux64_hook is 0 when this kernel boots on hardware, and every hosted path+ * is behind `if (linux64_hook)`.+ */+#ifndef _LINUX64_LINUX64_H_+#define _LINUX64_LINUX64_H_++#include <linux64/linux64_abi.h>++/* Bring-up diagnostics (thread dumps from the idle loop, per-exception traces): off unless built with -DLINUX64_DEBUG=1 */+#ifndef LINUX64_DEBUG+#define LINUX64_DEBUG 0+#endif++#ifdef __cplusplus+extern "C" {+#endif++/* xnu.ko's entry point (0: not hosted), the slide it applied, the thread pointer (TPIDR_EL1 is Linux's) */+extern unsigned long linux64_hook;+extern unsigned long linux64_slide;+extern unsigned long linux64_tpidr;+/* XNU's interrupt-enable state: hardware interrupts stay masked while XNU runs; this flag is the virtual one */+extern unsigned int linux64_vint;+/* enum linux64_counter */+extern unsigned long linux64_dbg[LINUX64_NCOUNTERS];++/* A call into the host (enum linux64_call). The host's answer: 0 to go on. */+static inline unsigned long+linux64_call2(enum linux64_call call, unsigned long a1, unsigned long a2)+{+ register unsigned long x0 __asm__("x0") = (unsigned long)call;+ register unsigned long x1 __asm__("x1") = a1;+ register unsigned long x2 __asm__("x2") = a2;+ linux64_dbg[LINUX64_CTR_LAST_CALL] = (unsigned long)call;+ if (linux64_hook) {+ /* a plain blr: the hook is host code, not an XNU function pointer (no pointer authentication) */+ __asm__ volatile ("blr %3"+ : "+r"(x0), "+r"(x1), "+r"(x2)+ : "r"(linux64_hook)+ : "x3", "x4", "x5", "x6", "x7", "x8", "x9", "x10", "x11", "x12", "x13", "x14", "x15", "x16", "x17",+ "x30", "cc", "memory");+ }+ return x0;+}++static inline unsigned long+linux64_call(enum linux64_call call, const void *a1)+{+ return linux64_call2(call, (unsigned long)a1, 0);+}++/* Bytes from the host's cryptographic generator (Linux's get_random_bytes) */+static inline void+linux64_random(void *buf, unsigned long len)+{+ linux64_call2(LINUX64_CALL_RANDOM, (unsigned long)buf, len);+}++/* A uniform value in [0, bound) (0 when bound is 0), by rejection: no modulo bias */+static inline __UINT64_TYPE__+linux64_random_uniform(__UINT64_TYPE__ bound)+{+ __UINT64_TYPE__ v, limit;++ if (bound == 0) {+ return 0;+ }+ limit = -bound % bound; /* 2^64 mod bound: values below it would bias the result */+ do {+ linux64_random(&v, sizeof(v));+ } while (v < limit);+ return v % bound;+}++static inline void+linux64_count(enum linux64_counter c)+{+ linux64_dbg[c]++;+}++/* osfmk/arm/arm_init.c */+void linux64_assert_report(const char *file, int line, const char *expr);+/* bsd/kern/kern_trustcache.c, libkern/amfi/amfi.c */+void linux64_trust_cache_late_init(void);+int linux64_amfi_off(void);+/* osfmk/arm64/cswitch.s, sleh.c: user space while hosted */+void linux64_el0_run(void *saved_state, unsigned long arg) __attribute__((noreturn));+/* osfmk/kern/sched_prim.c: every thread's state and saved frames to the host log (LINUX64_DEBUG) */+void linux64_dump_threads(void);++#ifdef __cplusplus+}+#endif++#endif /* _LINUX64_LINUX64_H_ */diff --git a/xnu-patches/include/linux64_abi.h b/xnu-patches/include/linux64_abi.hnew file mode 100644index 0000000..16b21d8--- /dev/null+++ b/xnu-patches/include/linux64_abi.h@@ -0,0 +1,105 @@+/*+ * Copyright (c) 2026 xnulinux contributors. All rights reserved.+ *+ * @APPLE_OSREFERENCE_LICENSE_HEADER_START@+ * This file contains Original Code and/or Modifications of Original Code as defined in and that are subject to the Apple+ * Public Source License Version 2.0 (the 'License'). You may not use this file except in compliance with the License.+ * @APPLE_OSREFERENCE_LICENSE_HEADER_END@+ */+/*+ * The interface between a hosted XNU (the LINUX64 machine layer) and its host, xnu.ko.+ *+ * xnu.ko calls arm_init with linux64_hook set to its entry point. XNU calls into the host with `blr linux64_hook`:+ * x0 = the call (enum linux64_call), x1 and x2 = its arguments; x0 on return is 0 to go on, non-zero when the host ends+ * the run. Requests are in XNU memory (the host and XNU share the kernel address space); `result` fields are filled by+ * the host: a count, or a negative Linux errno.+ *+ * linux64_dbg[] (enum linux64_counter) is read by the host's monitor thread on another CPU while XNU runs.+ *+ * This header is shared by both sides and includes nothing: it is copied into XNU's tree (osfmk/arm64) when the+ * patches are applied, and xnu.ko includes it from here.+ */+#ifndef _LINUX64_ABI_H_+#define _LINUX64_ABI_H_++#define LINUX64_ABI_VERSION 1++enum linux64_call {+ LINUX64_CALL_KERNEL_TABLES = 210, /* boot: a1 = XNU's kernel L1 table; the host installs its kernel-range entries */+ LINUX64_CALL_IDLE = 810, /* a1 = XNU's next timer deadline (mach_absolute_time); the host runs Linux until then */+ LINUX64_CALL_PREEMPTED = 811, /* a host interrupt is pending: let Linux handle it; a1 = 1 from the kernel, 0 from EL0 */+ LINUX64_CALL_WALLCLOCK = 812, /* a1 = u64[2]: {seconds, nanoseconds} UTC */+ LINUX64_CALL_NET_SEND = 816, /* a1 = struct linux64_buf_req: one Ethernet frame */+ LINUX64_CALL_NET_RECV = 817, /* a1 = struct linux64_buf_req: one Ethernet frame, result 0 when none */+ LINUX64_CALL_INPUT_READ = 818, /* a1 = struct linux64_buf_req: whole struct linux64_input_event records */+ LINUX64_CALL_KEYSTORE_RW = 819, /* a1 = struct linux64_rw_req on the keystore file */+ LINUX64_CALL_DISK_RW = 820, /* a1 = struct linux64_rw_req on the system disk */+ LINUX64_CALL_DISK_SIZE = 821, /* a1 = u64 *: the system disk's size in bytes, 0 when there is none */+ LINUX64_CALL_RANDOM = 822, /* a1 = buffer, a2 = length: bytes from the host's cryptographic generator */+ LINUX64_CALL_HOSTCALL = 830, /* a1 = struct linux64_hostcall_req: a message to a Linux service and its reply */+ LINUX64_CALL_CONSOLE_READ = 993, /* a1 = struct linux64_buf_req: console input bytes */+ LINUX64_CALL_RAMDISK_RW = 994, /* a1 = struct linux64_rw_req on the host-file md disk */+ LINUX64_CALL_RAMDISK_SIZE = 995, /* a1 = u64 *: the host-file md disk's size, 0 when there is none */+ LINUX64_CALL_CONSOLE_WRITE = 996, /* a1 = bytes, a2 = length: /dev/console output */+ LINUX64_CALL_ASSERT = 997, /* a1 = struct linux64_assert_info: a failed assert(); non-zero return ends the run */+ LINUX64_CALL_KPRINTF = 998, /* a1 = a NUL-terminated line of kprintf/printf output */+ LINUX64_CALL_PANIC = 999, /* a1 = the panic message, a2 = the caller; the run ends */+ LINUX64_CALL_USER_ENTER = 9100, /* a1 = user pc: the first entry into user space */+};++/* A buffer: bytes to send or room to receive into. */+struct linux64_buf_req {+ void *buf;+ __UINT64_TYPE__ len;+ __INT64_TYPE__ result;+};++/* Reads or writes of a host file at an offset. */+struct linux64_rw_req {+ __UINT64_TYPE__ write; /* 0: read into buf, 1: write from buf */+ __UINT64_TYPE__ off;+ __UINT64_TYPE__ len;+ void *buf;+ __INT64_TYPE__ result;+};++/* A host call: request and reply in XNU memory. result: the reply's length or -errno. */+struct linux64_hostcall_req {+ const void *req;+ __UINT64_TYPE__ len;+ void *reply;+ __UINT64_TYPE__ max;+ __INT64_TYPE__ result;+};++struct linux64_assert_info {+ const char *file;+ long line;+ const char *expr;+};++/* An input event: Linux evdev's type, code and value. */+struct linux64_input_event {+ unsigned short type;+ unsigned short code;+ int value;+};++enum linux64_counter {+ LINUX64_CTR_IDLE_THREAD = 0, /* XNU's idle thread loops */+ LINUX64_CTR_MACHINE_IDLE = 1, /* machine_idle calls */+ LINUX64_CTR_CPU_IDLE = 2, /* cpu_idle calls */+ LINUX64_CTR_HOST_IDLE = 3, /* LINUX64_CALL_IDLE calls */+ LINUX64_CTR_SWITCHES = 4, /* thread_invoke calls */+ LINUX64_CTR_LAST_CALL = 6, /* the last enum linux64_call made */+ LINUX64_CTR_RTCLOCK = 7, /* timer interrupts delivered */+ LINUX64_CTR_THREAD = 9, /* the thread last switched to */+ LINUX64_CTR_EL0_EXC = 10, /* exceptions from user space */+ LINUX64_CTR_EL0_ESR = 11, /* the last one's ESR, FAR and PC */+ LINUX64_CTR_EL0_FAR = 12,+ LINUX64_CTR_EL0_PC = 13,+ LINUX64_CTR_BAD_ESR = 14, /* the ESR of an exception the EL0 vectors could not take */+ LINUX64_NCOUNTERS = 16,+};++#endif /* _LINUX64_ABI_H_ */