XNU as a loadable kernel module inside Linux (macOS personality for arm64 Linux)
C
SMP: the hosted XNU on any number of CPUs (4 and 6 tested); paravirtual ticket locks
Heyang Zhou7aeedb9360d1
diff --git a/scripts/xnulinux-boot.sh b/scripts/xnulinux-boot.shindex e5b51f7..d546c8e 100755--- a/scripts/xnulinux-boot.sh+++ b/scripts/xnulinux-boot.sh@@ -41,7 +41,7 @@ CARVE="carve_base=$(cat /sys/module/fki/parameters/carve_base 2>/dev/null || echif [ "$(cat /sys/module/fki/srcversion 2>/dev/null)" != "$(modinfo -F srcversion fki-ko/fki.ko)" ]; thensudo systemctl stop xnudrmd 2>/dev/null || true # it holds fki's /dev/xnu-hostcallsudo rmmod fki 2>/dev/null || true- sudo insmod fki-ko/fki.ko $CARVE+ sudo insmod fki-ko/fki.ko $CARVE ${FKI_ARGS:-}fi[ "$(cat /sys/module/fki/parameters/carve_mb 2>/dev/null)" != 0 ] ||echo "fki has no carve-out (scripts/vm-install-fki-service.sh): the allocation from CMA may fail" >&2@@ -53,6 +53,15 @@ 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.+# Linux's device interrupts off the CPUs XNU takes (0..CPUS-1): a CPU running XNU's kernel holds Linux's interrupts+# until it next calls the host, so a disk completion routed there waits that long, and with several XNU CPUs one waiting+# for another's I/O can wait for good (as a hypervisor keeps device interrupts off its vCPUs' cores).+NCPU=$(nproc --all)+if [ "$NCPU" -gt "$CPUS" ]; then+ MASK=$(python3 -c "print(format(((1 << $NCPU) - 1) & ~((1 << $CPUS) - 1), 'x'))")+ echo "$MASK" | sudo tee /proc/irq/default_smp_affinity >/dev/null 2>&1 || true+ for f in /proc/irq/*/smp_affinity; do echo "$MASK" | sudo tee "$f" >/dev/null 2>&1 || true; done+fi# 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; dodiff --git a/xnu-ko/xnu_main.c b/xnu-ko/xnu_main.cindex c0eb9aa..627fa73 100644--- a/xnu-ko/xnu_main.c+++ b/xnu-ko/xnu_main.c@@ -268,16 +268,19 @@ unsigned long xnu_fault_deferred(unsigned long *frame) __attribute__((no_sanitizunsigned long xnu_fault_deferred(unsigned long *frame){unsigned long far = xnu_deferred.far, esr = xnu_deferred.esr, pc = xnu_deferred.pc;- static unsigned long last_far, repeats;+ /* per CPU: with one global record, two CPUs faulting at once reset each other's count, and a CPU looping on one+ * address never reached the every-64 yield below (it held its Linux CPU, and Linux with it, for good) */+ static unsigned long last_far_slot[LINUX64_CPU_SLOTS], repeats_slot[LINUX64_CPU_SLOTS];+ unsigned s0 = this_slot();+ unsigned long repeats = (far == last_far_slot[s0]) ? repeats_slot[s0] + 1 : 0;+ repeats_slot[s0] = repeats;+ last_far_slot[s0] = far;frame[31] = xnu_deferred.pstate; /* the SPSR the trampoline returns with */- repeats = (far == last_far) ? repeats + 1 : 0;- last_far = far;/** The same address faulting again is normal (libmalloc's MADV_FREE_REUSABLE clears a page's referenced and* modified state, so each reuse takes one fault). Only report it, rarely, when it looks endless.*/- unsigned s0 = this_slot();long kr = xnu_kfault(far, esr);if (this_slot() != s0) {/*@@ -435,8 +438,14 @@ static inline void acct_add(unsigned long call, u64_t ticks)/* 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);+/* each CPU's host calls so far, the last one's number, and whether it is inside one: the monitor's silent-CPU check */+static unsigned long upcalls_slot[LINUX64_CPU_SLOTS], last_call_slot[LINUX64_CPU_SLOTS];+static volatile int in_call_slot[LINUX64_CPU_SLOTS];long xnu_hook(unsigned long call, unsigned long a1, unsigned long a2){+ unsigned in_s = this_slot(); /* the thread is bound to its CPU while in the host */+ upcalls_slot[in_s]++;+ last_call_slot[in_s] = call;{/* debugging: an XNU stack Linux's overflow check would reject (bit 14 of sp set) */static int told;@@ -454,7 +463,9 @@ long xnu_hook(unsigned long call, unsigned long a1, unsigned long a2)return 1;}u64_t t0 = fki_counter();+ in_call_slot[in_s] = 1;long r = xnu_hook_body(call, a1, a2);+ in_call_slot[in_s] = 0;acct_add(call, fki_counter() - t0);if (!r) in_xnu = 1;return r;@@ -979,6 +990,35 @@ static int monitor_fn(void *arg)((volatile unsigned long *)xnu_dbg)[LINUX64_CTR_DUMP_REQ] = 1;dump_threads = 0;}+ { /* a CPU in XNU that has not called the host for 2 s holds its Linux CPU with interrupts masked */+ static unsigned long seen[XNU_MAX_CPUS], still[XNU_MAX_CPUS];+ for (int c = 0; c < cpus && xnu_dbg; c++) {+ unsigned s = LINUX64_CPU_SLOT(cpu_mpidr[c]);+ if ((c && !cpu_running[c]) || upcalls_slot[s] != seen[c]) { seen[c] = upcalls_slot[s]; still[c] = 0; continue; }+ if (++still[c] == 1) {+ struct xnu_world *w = xnu_worlds[s];+ unsigned long fp = w->xnu_regs[10];+ logkv("xnu: XNU CPU silent for 2 s (no host call), cpu", (u64_t)c);+ logkv("xnu: its last host call", last_call_slot[s]);+ logkv("xnu: still inside it (1) or back in XNU (0)", in_call_slot[s]);+ logkv("xnu: lr at that call", w->xnu_regs[11]);+ for (int f = 0; f < 16 && fp >= XNU_VA_LO && fp < XNU_VA_HI && !(fp & 7); f++) {+ logkv("xnu: frame", ((unsigned long *)fp)[1]);+ fp = ((unsigned long *)fp)[0];+ }+ }+ }+ }+ if (perf && cpus > 1) { /* each XNU CPU's host calls so far and the last one's number */+ char cb[200]; char *q = cb;+ put_str(&q, "xnu: calls");+ for (int c = 0; c < cpus; c++) {+ unsigned s = LINUX64_CPU_SLOT(cpu_mpidr[c]);+ put_str(&q, " "); q = put_dec(q, upcalls_slot[s]); put_str(&q, "/"); q = put_dec(q, last_call_slot[s]);+ }+ *q = 0;+ logs(cb);+ }if (perf)acct_report();if (!xnu_dbg || (lines >= 90 && (++ticks % 10) != 0))diff --git a/xnu-patches/0001-linux64-machine-layer.patch b/xnu-patches/0001-linux64-machine-layer.patchindex f256369..089b211 100644--- a/xnu-patches/0001-linux64-machine-layer.patch+++ b/xnu-patches/0001-linux64-machine-layer.patch@@ -304,7 +304,7 @@ index b65f76c..eac911b 100644#include <arm/cpu_internal.h>#include <arm/cpuid.h>#include <arm/cpuid_internal.h>-@@ -1094,6 +1095,52 @@ ml_set_interrupts_enabled_with_debug(boolean_t enable, boolean_t __unused debug)+@@ -1094,6 +1095,59 @@ ml_set_interrupts_enabled_with_debug(boolean_t enable, boolean_t __unused debug)thread = current_thread();@@ -332,7 +332,14 @@ index b65f76c..eac911b 100644+ if (now - linux64_last_kyield[slot] > 48000) {+ extern void rtclock_intr(unsigned int);+ linux64_last_kyield[slot] = now;-+ linux64_call2(LINUX64_CALL_PREEMPTED, 1, 0);++ /*++ * Not with preemption off (a spinlock held): Linux may reschedule this CPU's thread++ * away for as long as it likes, and every other CPU spins on the lock until XNU's++ * ticket-lock timeout panics.++ */++ if (get_preemption_level() == 0) {++ 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);@@ -357,7 +364,7 @@ index b65f76c..eac911b 100644state = __builtin_arm_rsr("DAIF");if (__improbable(!(state & DAIF_DEBUGF))) {-@@ -1366,6 +1413,58 @@ ml_early_cpu_max_number(void)+@@ -1366,6 +1420,68 @@ ml_early_cpu_max_number(void)return ml_get_max_cpu_number();}@@ -387,6 +394,16 @@ index b65f76c..eac911b 100644+ }+ linux64_last_relax[slot] = now;+ linux64_call2(LINUX64_CALL_PREEMPTED, 1, 0);++ /*++ * Spinning with XNU's interrupts enabled, a CPU takes another CPU's IPI on hardware (its FIQ): the other may be++ * waiting for exactly that (a cross-call's acknowledgment) before it lets go of what this one spins on. Take a++ * pending one here as the FIQ would, interrupts off around the handler; no AST, no context switch.++ */++ if (linux64_vint[slot] && getCpuDatap()->cpu_int_state == NULL) {++ linux64_vint[slot] = 0;++ linux64_ipi_take();++ linux64_vint[slot] = 1;++ }+}++void@@ -416,7 +433,7 @@ index b65f76c..eac911b 100644voidml_set_max_cpus(unsigned int max_cpus __unused){-@@ -1384,6 +1483,12 @@ ml_wait_max_cpus(void)+@@ -1384,6 +1500,12 @@ ml_wait_max_cpus(void){assert(lockdown_done);lck_mtx_lock(&max_cpus_lock);diff --git a/xnu-patches/0005-linux64-pv-ticket-locks.patch b/xnu-patches/0005-linux64-pv-ticket-locks.patchnew file mode 100644index 0000000..3b175fc--- /dev/null+++ b/xnu-patches/0005-linux64-pv-ticket-locks.patch@@ -0,0 +1,102 @@+From: xnulinux+Subject: [PATCH] linux64: spinning CPUs let the host in (paravirtual ticket locks, cpu_pause relax)++XNU's ticket locks (lck_spin, hw_lck_ticket) wait through hvg_hc_wait_for_kick / hvg_hc_kick_cpu when has_lock_pv+(CONFIG_PV_TICKET, osfmk/arm64/lock_ticket_pv.c), as under Apple's own hypervisor. Hosted, a CPU spinning on a lock with+every interrupt masked held its Linux CPU too: Linux CPUs waiting for it (an IPI's answer) locked up with four CPUs.+---+diff --git a/config/MASTER.arm64.bcm2837 b/config/MASTER.arm64.bcm2837+--- a/config/MASTER.arm64.bcm2837++++ b/config/MASTER.arm64.bcm2837+@@ -69,7 +69,7 @@+ # PERF_DBG_DEV = [ PERF_DBG_BASE config_dtrace lock_stats zleaks alternate_debugger config_debug_syscall_rejection config_iotrace PERF_EXTRAS_DEV config_memory_microstackshot ]+ # PERF_DBG_DEBUG = [ PERF_DBG_BASE config_dtrace lock_stats zleaks alternate_debugger config_debug_syscall_rejection config_iotrace PERF_EXTRAS_DEBUG config_memory_microstackshot ]+ # PERF_DBG_KASAN = [ PERF_DBG_BASE config_dtrace lock_stats zleaks alternate_debugger config_debug_syscall_rejection config_iotrace PERF_EXTRAS_DEV config_memory_microstackshot ]+-# PARAVIRT_BASE = [ ]++# PARAVIRT_BASE = [ config_pv_ticket ]+ # MACH_BASE = [ mach config_ecc_logging vc_progress_white importance_inheritance config_atm config_coalitions config_iosched config_library_validation config_sysdiagnose config_telemetry config_mach_bridge_recv_time config_quiesce_counter config_io_compression_stats phys_write_acct config_service_port_info PARAVIRT_BASE ]+ # MACH_RELEASE = [ MACH_BASE config_skip_precise_user_kernel_time debugger_for_zone_info ]+ # MACH_DEV = [ MACH_BASE config_io_accounting importance_trace config_task_suspend_stats ]+diff --git a/osfmk/arm64/arm64_hypercall.c b/osfmk/arm64/arm64_hypercall.c+--- a/osfmk/arm64/arm64_hypercall.c++++ b/osfmk/arm64/arm64_hypercall.c+@@ -292,12 +292,46 @@++ #else /* APPLEVIRTUALPLATFORM */++-bool+-hvg_is_hcall_available(__unused hvg_hcall_code_t hcall)++#include <arm/cpu_data_internal.h>++#include <linux64/linux64.h>++++/*++ * LINUX64 (xnulinux): the paravirtual ticket locks' wait-for-kick and kick (osfmk/arm64/lock_ticket_pv.c) on the host.++ * Each XNU CPU is a Linux thread: a CPU that cannot get a ticket lock sleeps in Linux (interrupts on, so Linux can use++ * the CPU and take its IPIs) until the holder's unlock kicks it, instead of spinning with every interrupt masked. The++ * wait is bounded (1 ms) and may end early: the caller looks at the lock again either way.++ */++static unsigned int linux64_pv_kicked[LINUX64_CPU_SLOTS];++++bool++hvg_is_hcall_available(hvg_hcall_code_t hcall)+ {+- return false;++ return linux64_hook && (hcall == HVG_HCALL_VCPU_WFK || hcall == HVG_HCALL_VCPU_KICK);++}++++void++hvg_hc_kick_cpu(unsigned int cpu_id)++{++ cpu_data_t *target = CpuDataEntries[cpu_id].cpu_data_vaddr;++++ if (target == NULL) {++ return;++ }++ os_atomic_store(&linux64_pv_kicked[LINUX64_CPU_SLOT(target->cpu_phys_id)], 1, release);++ linux64_call2(LINUX64_CALL_IPI, target->cpu_phys_id, 0); /* the host wakes that CPU; no XNU IPI is pending */+ }+++void++hvg_hc_wait_for_kick(__unused unsigned int ien)++{++ unsigned int slot = linux64_cpu_slot();++++ if (!os_atomic_xchg(&linux64_pv_kicked[slot], 0, acquire)) {++ linux64_call2(LINUX64_CALL_IDLE, 1000000, (unsigned long)&linux64_pv_kicked[slot]);++ os_atomic_store(&linux64_pv_kicked[slot], 0, relaxed);++ }++}+++ hvg_hcall_return_t+ hvg_hcall_get_mabs_offset(__attribute__((unused)) uint64_t *mabs_offset)+ {+diff --git a/osfmk/arm/machine_cpu.h b/osfmk/arm/machine_cpu.h+--- a/osfmk/arm/machine_cpu.h++++ b/osfmk/arm/machine_cpu.h+@@ -56,7 +56,14 @@++ extern void init_cpu_timebase(boolean_t enable_fiq);++-#define cpu_pause() do {} while (0) /* Not for this architecture */++/*++ * LINUX64 (xnulinux): every spin loop's pause (lock_rw, the lock spin helpers) lets the host take a spinning CPU's++ * interrupts now and then (linux64_spin_relax, ~1 ms): hosted, a CPU spins with the host's interrupts masked, and++ * Linux CPUs waiting on it (an IPI's answer) would wait as long as it spins.++ */++extern unsigned long linux64_hook;++extern void linux64_spin_relax(void);++#define cpu_pause() do { if (__builtin_expect(linux64_hook != 0, 0)) linux64_spin_relax(); } while (0)+ bool+ wfe_to_deadline_or_interrupt(uint32_t cid, uint64_t wfe_deadline, cpu_data_t *cdp, bool unmask, bool check_cluster_recommendation);+ #endif /* _ARM_MACHINE_CPU_H_ */+diff --git a/osfmk/arm/pmap/pmap.c b/osfmk/arm/pmap/pmap.c+--- a/osfmk/arm/pmap/pmap.c++++ b/osfmk/arm/pmap/pmap.c+@@ -3940,6 +3940,7 @@+ }+ if (os_atomic_load_exclusive(&cpu_data->inflight_disconnect, relaxed)) {+ __builtin_arm_wfe();++ cpu_pause(); /* LINUX64: the host takes this CPU's interrupts now and then */+ inflight_disconnect = true;+ continue;+ }