Skip to content

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

C

Hosted XNU under a busy userland: GBs of DRAM, user-mode IRQ preemption (stage 811), kernel faults resolved in XNU's context (xnu_fault_tramp), no 64-repeat give-up

Heyang Zhoub04323ae6fdf
diff --git a/xnu-ko/world.S b/xnu-ko/world.S
index d5dce23..e0e00e8 100644
--- a/xnu-ko/world.S
+++ b/xnu-ko/world.S
@@ -157,3 +157,58 @@ xnu_world_upcall: /* x0 = stage, called by XNU with blr */
ldp x29, x30, [x9, #192]
ret
.size xnu_world_upcall, . - xnu_world_upcall
+
+/*
+ * Deferred XNU kernel fault (see xnu_fault in xnu_main.c): Linux's exception returns here with the faulting context's
+ * registers, stack and PSTATE. Save them, let xnu_fault_deferred resolve the fault in XNU's context (it returns where
+ * to go and may set x0 for a copyio recovery; frame[31] is the SPSR), then eret there with every register restored.
+ */
+ .globl xnu_fault_tramp
+ .type xnu_fault_tramp, %function
+xnu_fault_tramp:
+ sub sp, sp, #256
+ stp x0, x1, [sp, #0]
+ 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]
+ /*
+ * PAN on, as a real exception entry would set it (copyio runs with PAN off; vm_fault may block, and XNU panics on
+ * a context switch with PAN off). The eret below restores the faulting context's PSTATE, PAN included.
+ */
+ .inst 0xd500419f /* msr pan, #1 */
+ mov x0, sp
+ bl xnu_fault_deferred
+ msr elr_el1, x0
+ ldr x1, [sp, #248]
+ msr spsr_el1, x1
+ ldp x0, x1, [sp, #0]
+ ldp x2, x3, [sp, #16]
+ ldp x4, x5, [sp, #32]
+ ldp x6, x7, [sp, #48]
+ ldp x8, x9, [sp, #64]
+ ldp x10, x11, [sp, #80]
+ ldp x12, x13, [sp, #96]
+ ldp x14, x15, [sp, #112]
+ ldp x16, x17, [sp, #128]
+ ldp x18, x19, [sp, #144]
+ ldp x20, x21, [sp, #160]
+ ldp x22, x23, [sp, #176]
+ ldp x24, x25, [sp, #192]
+ ldp x26, x27, [sp, #208]
+ ldp x28, x29, [sp, #224]
+ ldr x30, [sp, #240]
+ add sp, sp, #256
+ eret
+ .size xnu_fault_tramp, . - xnu_fault_tramp
diff --git a/xnu-ko/xnu_main.c b/xnu-ko/xnu_main.c
index 0c52e6d..cfa5b0d 100644
--- a/xnu-ko/xnu_main.c
+++ b/xnu-ko/xnu_main.c
@@ -154,36 +154,66 @@ static unsigned long kfaults;
#define XNU_VA_LO 0xffffffe000000000ULL
#define XNU_VA_HI 0xfffffffc00000000ULL
+/*
+ * A kernel fault XNU's vm_fault should resolve is not resolved here, inside Linux's exception handler (a kprobe: no
+ * sleeping, no rescheduling, and a nested fault in it is a missed kprobe and an oops), because vm_fault may page in
+ * from disk (a file I/O upcall that lets Linux schedule) or block the thread. The exception instead returns into
+ * xnu_fault_tramp (world.S) with every register as it was; the trampoline calls xnu_fault_deferred in XNU's own
+ * context, then returns (eret) to the faulting instruction, to the copyio recovery path, or to the abort.
+ */
+static struct { unsigned long far, esr, pc, pstate; } xnu_deferred;
+extern void xnu_fault_tramp(void);
+extern void xnu_world_fault_abort(void);
+
+unsigned long xnu_fault_deferred(unsigned long *frame);
+unsigned 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;
+
+ 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.
+ */
+ if (xnu_kfault(far, esr) == 0) {
+ if (repeats == 100000)
+ logkv("xnu: one address took 100000 kernel faults in a row (each resolved), far", far);
+ return pc;
+ }
+ /* inside copyin/copyout: the routine's recovery path returns EFAULT to its caller, as XNU's own abort handler does */
+ if (xnu_kfault_recover) {
+ unsigned long rpc = xnu_kfault_recover(pc, far, esr);
+ if (rpc) {
+ frame[0] = 14; /* EFAULT */
+ return rpc;
+ }
+ }
+ in_xnu = 0;
+ logs("xnu: XNU took a fault vm_fault cannot resolve; ending the run");
+ logkv("xnu: pc ", pc);
+ logkv("xnu: lr ", frame[30]);
+ logkv("xnu: far", far);
+ logkv("xnu: esr", esr);
+ return (unsigned long)xnu_world_fault_abort;
+}
+
static int xnu_fault(unsigned long far, unsigned long esr, void *regs)
{
if (!in_xnu)
return 1;
- if (far && ((far >= XNU_VA_LO && far < XNU_VA_HI) || far < 0x0001000000000000ULL) && xnu_kfault) {
- static unsigned long last_far, repeats;
+ unsigned long fpc = fki_regs_pc(regs);
+ if (far && ((far >= XNU_VA_LO && far < XNU_VA_HI) || far < 0x0001000000000000ULL) && xnu_kfault &&
+ fpc >= XNU_VA_LO && fpc < XNU_VA_HI) {
kfaults++;
- repeats = (far == last_far) ? repeats + 1 : 0;
- last_far = far;
- /* the same address faulting over and over: vm_fault says yes, the hardware still says no */
- if (repeats < 64 && xnu_kfault(far, esr) == 0)
- return 0;
- if (repeats >= 64) {
- unsigned long long ttbr0, tcr;
- __asm__ volatile("mrs %0, ttbr0_el1" : "=r"(ttbr0));
- __asm__ volatile("mrs %0, tcr_el1" : "=r"(tcr));
- logs("xnu: the same address keeps faulting after vm_fault resolved it");
- logkv("xnu: TTBR0", ttbr0);
- logkv("xnu: TCR ", tcr);
- /* walk it as the hardware does with this TCR (4K granule, T0SZ from TCR) */
- unsigned t0sz = tcr & 0x3f, level = t0sz > 24 ? 1 : 0;
- u64_t table = ttbr0 & 0x0000fffffffff000ULL;
- for (; level <= 3; level++) {
- unsigned shift = 39 - 9 * level;
- u64_t d = fki_phys_peek(table + ((far >> shift) & 511) * 8);
- logkv(level == 0 ? "xnu: L0" : level == 1 ? "xnu: L1" : level == 2 ? "xnu: L2" : "xnu: L3", d);
- if ((d & 3) != 3 || level == 3) break;
- table = d & 0x0000fffffffff000ULL;
- }
- }
+ xnu_deferred.far = far;
+ xnu_deferred.esr = esr;
+ xnu_deferred.pc = fpc;
+ xnu_deferred.pstate = fki_regs_pstate(regs);
+ fki_regs_set_pc(regs, (unsigned long)xnu_fault_tramp);
+ return 0;
}
/*
* An XNU fault nothing resolves (a bug, or a NULL dereference): report it and end the run instead of letting Linux
@@ -317,6 +347,10 @@ static long xnu_hook_body(unsigned long stage, unsigned long a1, unsigned long a
if (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 */
+ fki_yield();
+ return 0;
+ }
if (stage == 810) { /* 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);
@@ -656,15 +690,25 @@ static int run_m2b(void)
if (err) { logkv("xnu: contiguous allocation failed, err", (u64_t)err); return err; }
logkv("xnu: contiguous DRAM at phys", img.region.pa);
logkv("xnu: contiguous DRAM size", img.region.size);
- if ((img.region.pa & 0x1fffff) || img.region.size > (1ULL << 30)) { logs("xnu: region not 2 MiB aligned or above 1 GiB"); return -22; }
+ if (img.region.pa & 0x1fffff) { logs("xnu: region not 2 MiB aligned"); return -22; }
err = fki_contig_alloc(4096, &l2page);
if (err) return err;
unsigned long long *l2 = l2page.va;
unsigned first = (XNU_WINDOW_BASE >> 21) & 511;
- if (first + (img.region.size >> 21) > 512) { logs("xnu: image and DRAM cross a 1 GiB L1 slot (one bootstrap L2 table only)"); return -22; }
+ /*
+ * One bootstrap L2 table: map what fits in the window's 1 GiB L1 slot. XNU only touches the image, the
+ * boot data and its first bootstrap allocations before it hands us its own kernel L1 entries (stage 210),
+ * which map all of its DRAM, so DRAM beyond the slot needs no bootstrap mapping.
+ */
+ u64_t boot_map = img.region.size;
+ if (boot_map > ((u64_t)(512 - first) << 21)) boot_map = (u64_t)(512 - first) << 21;
+ if (boot_map < image_off + image_size + 0x60000 + ((rd_size + 0x3fff) & ~0x3fffULL) + (64ULL << 20)) {
+ logs("xnu: image and boot data do not fit in the bootstrap window"); return -22;
+ }
logkv("xnu: bootstrap window base", XNU_WINDOW_BASE);
- for (u64_t o = 0; o < img.region.size; o += 0x200000) {
+ logkv("xnu: bootstrap window bytes", boot_map);
+ for (u64_t o = 0; o < boot_map; o += 0x200000) {
/* 2 MiB block: normal WB (AttrIdx 0 in Linux's MAIR), inner shareable, AF, EL1 RWX, UXN */
l2[first + (o >> 21)] = (img.region.pa + o) | (1ULL << 54) | (1ULL << 10) | (3ULL << 8) | 1;
}
diff --git a/xnu-patches/0001-linux64-stage-hook.patch b/xnu-patches/0001-linux64-stage-hook.patch
index 7007fc4..e7cc8c8 100644
--- a/xnu-patches/0001-linux64-stage-hook.patch
+++ b/xnu-patches/0001-linux64-stage-hook.patch
@@ -1037,7 +1037,7 @@ index b65f76c..11b510a 100644
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..ac5b387 100644
+index 79d0bc1..654dc70 100644
--- a/osfmk/arm/pmap/pmap.c
+++ b/osfmk/arm/pmap/pmap.c
@@ -2254,6 +2254,7 @@ pmap_bootstrap(
@@ -1083,6 +1083,38 @@ index 79d0bc1..ac5b387 100644
#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
+@@ -15385,3 +15391,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/rtclock.c b/osfmk/arm/rtclock.c
index a17a07d..6136425 100644
--- a/osfmk/arm/rtclock.c
@@ -1523,7 +1555,7 @@ index d10d7a1..15e2fb4 100644
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..5c56160 100644
+index a191eb3..b48f1ef 100644
--- a/osfmk/arm64/cswitch.s
+++ b/osfmk/arm64/cswitch.s
@@ -185,7 +185,8 @@
@@ -1586,7 +1618,7 @@ index a191eb3..5c56160 100644
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,171 @@ LEXT(machine_set_current_thread)
+@@ -444,3 +450,185 @@ LEXT(machine_set_current_thread)
/* vim: set ts=4: */
@@ -1624,7 +1656,7 @@ index a191eb3..5c56160 100644
+ ldr x10, [x0, SS64_PC]
+ msr ELR_EL1, x10
+ ldr w10, [x0, SS64_CPSR]
-+ orr w10, w10, #0xc0 // IRQ and FIQ stay masked at EL0 while hosted
++ 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
@@ -1681,7 +1713,11 @@ index a191eb3..5c56160 100644
+ b Llinux64_el0_bad
+ .align 7
+ .endr
-+ .rept 4 // lower EL, AArch64: sync, IRQ, FIQ, SError
++ 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
@@ -1697,9 +1733,16 @@ index a191eb3..5c56160 100644
+ 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]
@@ -1722,6 +1765,9 @@ index a191eb3..5c56160 100644
+ 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]
@@ -2236,10 +2282,10 @@ index d211433..dc247da 100644
// 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..76cfc96 100644
+index d8f1b19..d7a33cf 100644
--- a/osfmk/arm64/sleh.c
+++ b/osfmk/arm64/sleh.c
-@@ -3646,3 +3646,196 @@ sleh_panic_lockdown_should_initiate_el1_sp0_sync(uint64_t esr, uint64_t elr,
+@@ -3646,3 +3646,218 @@ sleh_panic_lockdown_should_initiate_el1_sp0_sync(uint64_t esr, uint64_t elr,
}
__SECURITY_STACK_DISALLOWED_POP
#endif /* CONFIG_SPTM */
@@ -2279,13 +2325,15 @@ index d8f1b19..76cfc96 100644
+ }
+ map = thread->map;
+ }
++ kern_return_t ffr = KERN_FAILURE;
+ if (!is_translation_fault(fault_code)) {
-+ result = arm_fast_fault(map->pmap, far, fault_type, (fault_code == FSC_ACCESS_FLAG_FAULT_L3), FALSE);
-+ if (result == KERN_SUCCESS) {
-+ return result;
-+ }
++ 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;
+ }
-+ kern_return_t kr = vm_fault(map, far, fault_type, FALSE, VM_KERN_MEMORY_NONE, THREAD_UNINT, NULL, 0);
+ if (map != kernel_map) {
+ /* LINUX64 debug: where did the user fault land? */
+ static int reported;
@@ -2411,6 +2459,26 @@ index d8f1b19..76cfc96 100644
+ 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;