Skip to content

XNU as a loadable kernel module inside Linux (macOS personality for arm64 Linux)

C

Hosted idle sleeps until XNU's next timer; stop a hosted run without restarting the VM; incremental XNU rebuilds

Heyang Zhou0821d05f6d24
diff --git a/scripts/vm-xnu-rebuild.sh b/scripts/vm-xnu-rebuild.sh
index 9e81dd0..0024580 100755
--- a/scripts/vm-xnu-rebuild.sh
+++ b/scripts/vm-xnu-rebuild.sh
@@ -6,16 +6,22 @@ set -e -o pipefail # a failed kernel build stops here: never repackage the previ
cd ~/w/dvm
export PATH=$PATH:/usr/lib/llvm-21/bin
T=out/k27/xnu
-# back to the tree's own sources: every file the patches touched last time (.linux64-patched) or touch now
+# back to the tree's own sources: every file the patches touched last time (.linux64-patched) or touch now, then the
+# patches again. A file that comes out as it was keeps its old time, so the build recompiles only what changed (assert.h
+# and cpu_data.h are included everywhere: touching them rebuilds the whole kernel)
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/$f
-done
+FILES=$(cat $T/.linux64-patched 2>/dev/null; grep -h '^+++ b/' $P/*.patch | sed 's|^+++ b/||')
+SNAP=$(mktemp -d)
+for f in $FILES; do [ -e $T/$f ] && mkdir -p $SNAP/$(dirname $f) && cp -p $T/$f $SNAP/$f; done
+for f in $FILES; do git -C $T checkout -q -- $f 2>/dev/null || rm -f $T/$f; done
for p in $P/*.patch; do git -C $T apply $p; echo "applied $(basename $p)"; done
+for f in $FILES; do [ -e $SNAP/$f ] && cmp -s $SNAP/$f $T/$f && touch -r $SNAP/$f $T/$f; done
+rm -rf $SNAP
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 -15
+mkdir -p $T/EXTERNAL_HEADERS/linux64
+for h in $P/include/*.h; do cmp -s $h $T/EXTERNAL_HEADERS/linux64/$(basename $h) || cp $h $T/EXTERNAL_HEADERS/linux64/; done
+t=$SECONDS; JOBS=12 bash k27/build-kernel27.sh 2>&1 | tail -15; echo "kernel: $((SECONDS - t)) s"
if [ -e out/kc/kc27.bin ]; then
# the hosted system's extra Apple kexts (in kc27, not kept by default): IOSurface for actool, CoreImage and friends
for id in $(grep -v '^#' ~/w/poc/xnu-patches/kc-keep-extra.txt); do grep -qx "$id" configs/kc-keep.txt || echo "$id" >> configs/kc-keep.txt; done
@@ -47,7 +53,7 @@ if [ -e out/kc/kc27.bin ]; then
python3 scripts/build-native-kext.py $n $(dirname $j)/$n.cpp -I $NETINC --obj ${KEXT_OBJ:-k27-obj} || { echo "kext $n failed to build: left out"; continue; }
NATIVE="$NATIVE $j"
done
- K27_NO_BOOT=1 NATIVE="$NATIVE" bash k27/try.sh 0 2>&1 | tail -3
+ t=$SECONDS; K27_NO_BOOT=1 NATIVE="$NATIVE" bash k27/try.sh 0 2>&1 | tail -3; echo "collection: $((SECONDS - t)) s"
grep -iE 'error|unresolved|XnuCpuMetal' out/k27/kc-build.log | tail -8 || true
# AMFI of the collection's macOS expects the code-signature platform version of that build; the system disk's binaries
# carry their own (macOS 27.0.1: 26 where 27.2's AMFI expects 27)
diff --git a/scripts/xnulinux-boot.sh b/scripts/xnulinux-boot.sh
index 2826a3f..b5772a5 100755
--- a/scripts/xnulinux-boot.sh
+++ b/scripts/xnulinux-boot.sh
@@ -2,7 +2,7 @@
# In the VM: boot the hosted macOS. Builds fki.ko and xnu.ko against the running kernel (stops on a compile error, never
# boots stale modules), brings up the hosted system's network (xnu0) and GPU bridge (xnudrmd, when there is a render node),
# and loads xnu.ko on the disk mk-macvm-disk.sh made. Returns once XNU is running; xnu.ko stays loaded until the hosted
-# system halts (or `sudo rmmod xnu`).
+# system halts or `xnulinux-boot.sh stop` ends it.
#
# Configuration: /var/tmp/mac.conf (written by mk-macvm-disk.sh: ROOT_UUID, BOOT_UUID), then the environment:
# DISK (/var/tmp/mac.img) RAM_MB (7900) BOOTARGS CONSOLE_IN (/var/tmp/console-in) INPUT_IN (/var/tmp/xnu-input)
@@ -10,6 +10,14 @@
# IMAGE (xnu/kc.bin: the kernel collection under /lib/firmware) GPU (auto|off)
set -euo pipefail
cd "$(dirname "$0")/.."
+if [ "${1:-}" = stop ]; then # end the running hosted system (its disk synced first) and remove xnu.ko
+ lsmod | grep -q '^xnu ' || { echo "no hosted system is running"; exit 0; }
+ printf 'sync\n' >> "${CONSOLE_IN:-/var/tmp/console-in}"; sleep 3
+ echo 1 | sudo tee /sys/module/xnu/parameters/stop_run >/dev/null
+ for _ in $(seq 1 50); do pgrep -x insmod >/dev/null || break; sleep 0.2; done
+ sudo rmmod xnu && echo "hosted system stopped"
+ exit
+fi
[ -f /var/tmp/mac.conf ] && . /var/tmp/mac.conf
DISK=${DISK:-/var/tmp/mac.img}; RAM_MB=${RAM_MB:-7900}; GPU=${GPU:-auto}
CONSOLE_IN=${CONSOLE_IN:-/var/tmp/console-in}; INPUT_IN=${INPUT_IN:-/var/tmp/xnu-input}; FB_DUMP=${FB_DUMP:-/var/tmp/xnu-fb.raw}
diff --git a/xnu-ko/xnu_main.c b/xnu-ko/xnu_main.c
index 0ddc2fd..03b7a6d 100644
--- a/xnu-ko/xnu_main.c
+++ b/xnu-ko/xnu_main.c
@@ -42,6 +42,9 @@ static int quiet_line(const char *l, unsigned n)
if (!x_strncmp(l + k, "triggered unnest", 16)) return 1;
return 0;
}
+/* Writing 1 ends the run at XNU's next call into the host; insmod returns and the module can be removed */
+static int stop_run;
+module_param(stop_run, int, 0644);
static int assert_fatal; /* 1: a failed XNU assert() ends the run; 0: report it and let XNU continue */
module_param(assert_fatal, int, 0444);
@@ -338,6 +341,10 @@ long xnu_hook(unsigned long call, unsigned long a1, unsigned long a2)
}
}
in_xnu = 0;
+ if (*(volatile int *)&stop_run) { /* the host asked the run to end (scripts/xnulinux-boot.sh stop): XNU is abandoned here */
+ logs("xnu: run stopped by the host (stop_run)");
+ return 1;
+ }
long r = xnu_hook_body(call, a1, a2);
if (!r) in_xnu = 1;
return r;
@@ -483,7 +490,12 @@ static long xnu_hook_body(unsigned long call, unsigned long a1, unsigned long a2
static unsigned long idles;
idles++;
if ((idles & (idles - 1)) == 0) logkv("xnu: XNU idle, count", idles);
- fki_idle_until(a1, 20000000ULL); /* at most 20 ms per round */
+ if (!a1) /* a timer is due: only let Linux take its interrupts */
+ fki_yield();
+ else { /* sleep until XNU's next timer, at most 20 ms (XNU's devices are polled from its timers) */
+ u64_t ns = a1 < 20000000ULL ? a1 : 20000000ULL;
+ fki_idle_until(fki_counter() + ns * fki_counter_frequency() / 1000000000ULL, ns);
+ }
return idle_max && idles >= (unsigned long)idle_max;
}
if (call == LINUX64_CALL_ASSERT) { /* XNU assert() failed */
diff --git a/xnu-patches/0001-linux64-machine-layer.patch b/xnu-patches/0001-linux64-machine-layer.patch
index 1181c19..2b8864b 100644
--- a/xnu-patches/0001-linux64-machine-layer.patch
+++ b/xnu-patches/0001-linux64-machine-layer.patch
@@ -508,7 +508,7 @@ index 84deb3f..767b8f8 100644
.macro BRANCH_EXTERN
diff --git a/osfmk/arm64/cpu.c b/osfmk/arm64/cpu.c
-index d10d7a1..956867d 100644
+index d10d7a1..5124822 100644
--- a/osfmk/arm64/cpu.c
+++ b/osfmk/arm64/cpu.c
@@ -32,6 +32,7 @@
@@ -539,7 +539,7 @@ index d10d7a1..956867d 100644
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
+@@ -494,6 +501,39 @@ wfe_to_deadline_or_interrupt(uint32_t cid, uint64_t wfe_deadline, cpu_data_t *cd
return ipending || (nirqc != irqc);
}
@@ -553,10 +553,14 @@ index d10d7a1..956867d 100644
+{
+ uint64_t now = mach_absolute_time();
+ uint64_t deadline = cpu_data_ptr->rtcPop;
++ uint64_t ns = 0; /* a timer already due: no sleep, only let Linux take its interrupts */
+
+ 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 (deadline == 0 || deadline == EndOfAllTime) {
++ ns = NSEC_PER_MSEC; /* no timer armed: check the run queue again in 1 ms */
++ } else if (deadline > now) {
++ /* relative: XNU's timebase (mach_absolute_time) is offset from the host's counter */
++ absolutetime_to_nanoseconds(deadline - now, &ns);
+ }
+#if LINUX64_DEBUG
+ if (++linux64_dbg[LINUX64_CTR_HOST_IDLE] % 150000 == 0) { /* every two to three minutes of idle */
@@ -565,7 +569,7 @@ index d10d7a1..956867d 100644
+#else
+ linux64_count(LINUX64_CTR_HOST_IDLE);
+#endif
-+ linux64_call2(LINUX64_CALL_IDLE, (unsigned long)deadline, 0);
++ linux64_call2(LINUX64_CALL_IDLE, ns, 0);
+ cpu_data_ptr->cpu_decrementer = -1;
+ rtclock_intr(FALSE);
+ ClearIdlePop(TRUE);
@@ -575,7 +579,7 @@ index d10d7a1..956867d 100644
/*
* Routine: cpu_idle
* Function:
-@@ -506,6 +542,9 @@ cpu_idle(void)
+@@ -506,6 +546,9 @@ cpu_idle(void)
uint64_t new_idle_timeout_ticks = 0x0ULL, lastPop;
bool idle_disallowed = false;
diff --git a/xnu-patches/include/linux64_abi.h b/xnu-patches/include/linux64_abi.h
index 16b21d8..73e966d 100644
--- a/xnu-patches/include/linux64_abi.h
+++ b/xnu-patches/include/linux64_abi.h
@@ -22,11 +22,11 @@
#ifndef _LINUX64_ABI_H_
#define _LINUX64_ABI_H_
-#define LINUX64_ABI_VERSION 1
+#define LINUX64_ABI_VERSION 2
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_IDLE = 810, /* a1 = nanoseconds to XNU's next timer (0: one is due); the host runs Linux meanwhile */
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 */