Skip to content

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

C

SMP step 2: the hosted XNU on two CPUs (kexts/XnuCPU, CPU start and IPIs through the host)

Heyang Zhou081e6b4c6f52
diff --git a/docs/smp.md b/docs/smp.md
index b0c145a..fcd76a4 100644
--- a/docs/smp.md
+++ b/docs/smp.md
@@ -8,9 +8,10 @@ decoder in the hosted system), which needs several cores. This is the plan for N
| Where | State | For N CPUs |
|---|---|---|
-| XNU, `linux64_tpidr` (`osfmk/arm/arm_init.c`, ~45 uses in `locore.s`, `cswitch.s`, `asm.h`, `cpu_data.h`, ...) | The current thread: on hardware `TPIDR_EL1`, which is Linux's per-CPU base while hosted | One slot per CPU, found from `MPIDR_EL1` (`READ_THREAD`/`WRITE_THREAD` macros, one implementation); xnu.ko checks at load that the CPUs it uses map to distinct slots |
+| XNU, the current thread (on hardware `TPIDR_EL1`, which is Linux's per-CPU base while hosted) | A global (`linux64_tpidr`) | Done: `TPIDRRO_EL0` in XNU's kernel (the user TSD is swapped in on return to user space), per CPU by nature |
+| XNU, the virtual interrupt flag, pending IPI, host-yield clock | Globals | One slot per CPU, found from `MPIDR_EL1` (`LINUX64_CPU_SLOT`); xnu.ko checks at load that its CPUs map to distinct slots. A slot read before code that can block (an urgent AST) is read again after it: the thread can resume on another CPU |
| xnu.ko, `xnu_W` (`world.S`) | The world-switch save area: Linux's and XNU's callee-saved registers, keys, TTBR0/TCR, TLS | One per CPU, found the same way in `world.S` |
-| xnu.ko, `in_xnu`, `kcount`, the console line buffer, statics in `xnu_hook_body` | Per-run state | Per CPU where it is per CPU (`in_xnu`); a spinlock where it is shared (the console buffer) |
+| xnu.ko, `in_xnu`, the deferred kernel-fault record, `kcount`, the console line buffer, statics in `xnu_hook_body` | Per-run state | Per CPU where it is per CPU (`in_xnu`, the fault record the exception handler leaves for `xnu_fault_tramp`); a spinlock where it is shared (the console buffer) |
| fki, `fki_hostcall` | One request slot | A small table of slots (xnudrmd serves them in order) or a mutex; the GPU bridge already opens one connection per process |
| The ADT (`/cpus`) | `cpu0` only | One node per CPU with its MPIDR, `cluster-type` P |
| `ml_wait_max_cpus` patch | One CPU, known at once | N |
@@ -19,16 +20,20 @@ decoder in the hosted system), which needs several cores. This is the plan for N
On a Mac, the platform's CPU kext (an `IOCPU` subclass, AppleARMCPU) calls `ml_processor_register` for each CPU and
starts them through its `PE_cpu_start` callback (it writes the core's reset vector). We keep Apple's CPU kext out
-(it drives the AIC), so `kexts/XnuCPU` takes its place: one `IOCPU` per `/cpus` node, `ml_processor_register` with
-callbacks whose start is a host call (`LINUX64_CALL_CPU_START`, a1 = the CPU's MPIDR, a2 = XNU's entry for it).
-xnu.ko then starts a kernel thread bound to that Linux CPU, which enters the XNU world (its own save area) at the
-entry XNU gave (`start_cpu` → `arm_init_cpu`).
+(it drives the AIC), so `kexts/XnuCPU` takes its place: one `IOCPU` per `/cpus` node. In XNU 12377
+`ml_processor_register` boots the processor itself (`processor_boot` → `cpu_start`), so the kext only registers; the boot
+CPU registers first (other CPUs send it IPIs as soon as they run, AppleARMSMP's order), a secondary matched before it
+waits and is registered from the boot CPU's `start`. `cpu_start` asks the host (`LINUX64_CALL_CPU_START`, a1 = the CPU's
+MPIDR, a2 = its `cpu_data`). An upcall runs with preemption off and must not sleep, so xnu.ko makes each secondary's
+kernel thread, bound to its Linux CPU, before XNU runs; the call only hands it the argument and wakes it. The thread
+enters the XNU world (its own save area) at `linux64_cpu_entry` → `arm_init_cpu` (`start_cpu`'s hardware setup is the
+host's). xnu.ko's helper threads (monitor, framebuffer) run on the first Linux CPU XNU does not use.
## Interrupts between CPUs
-`ml_cpu_signal` (an AIC register write on hardware) becomes a host call `LINUX64_CALL_IPI` (a1 = target MPIDR):
+`IOCPU::signalCPU` (an AIC register write on hardware) becomes `linux64_cpu_signal`, a host call `LINUX64_CALL_IPI` (a1 = target MPIDR):
xnu.ko marks the target pending and, if it is asleep in its idle call, wakes it; if it is running XNU code, sends it a
-Linux IPI. A CPU in XNU's kernel runs with hardware interrupts masked, so it takes a pending XNU IPI where XNU's
+Linux IPI (`smp_call_function_single_async`). A CPU in XNU's kernel runs with hardware interrupts masked, so it takes a pending XNU IPI where XNU's
virtual interrupt flag is turned back on (`ml_set_interrupts_enabled(TRUE)`, already the place where host interrupts are
let in every 2 ms), on return to user space and at idle. User code runs with host interrupts on: the Linux IPI ends
it at once (as a host interrupt does today, `LINUX64_CALL_PREEMPTED`), and the pending XNU IPI is delivered as
@@ -37,10 +42,26 @@ it at once (as a host interrupt does today, `LINUX64_CALL_PREEMPTED`), and the p
TLB maintenance needs no IPI: XNU's pmap uses broadcast `TLBI ...IS` on its own ASIDs. Each CPU still drops its local
TLB at every world switch (`TO_XNU_MM`/`TO_LINUX_MM`): Linux's and XNU's ASIDs are unrelated.
+## What follows the CPU, not the thread
+
+An XNU thread can block on one CPU and resume on another; what belongs to the Linux task under the CPU must not travel
+with it. Linux's shadow call stack pointer (x18, `CONFIG_SHADOW_CALL_STACK`) is the Linux task's: XNU's context switch
+never saves x18, so the register stays with the CPU, and `world.S` saves and restores it at world entry and exit. Two
+places used to carry it across a move and corrupted both tasks' shadow stacks (FPAC in Linux interrupt handlers,
+"corrupted shadow stack detected inside scheduler"): `xnu_fault_deferred` itself (built without the shadow stack, as
+`vm_fault` may block inside it) and `xnu_fault_tramp`'s `eret`, which restores the faulting context's registers: when the
+thread moved, its frame's x18 is replaced with the current CPU's. The monitor's `moved=` counts those resumes.
+
+A CPU spinning in XNU (`wait_for_event()`, every hardware lock's wait) may wait for a CPU the host holds; every ~1 ms of
+spinning lets the host take the spinning CPU's interrupts (`linux64_spin_relax`, nothing of XNU's runs there).
+
## Steps, each verified on a running system
1. Per-CPU state with one CPU: the thread-pointer slots, per-CPU save areas in xnu.ko, the hostcall table. Boots and
runs as today (`hw.ncpu` 1).
2. `kexts/XnuCPU`, `LINUX64_CALL_CPU_START`, `LINUX64_CALL_IPI`; two CPUs (`cpus=2`). Check: `hw.ncpu` 2, both CPUs'
idle counters move, a CPU-bound process on each CPU (`yes > /dev/null` twice) shows 200% in `top`.
+ Done: `hw.ncpu` and `hw.activecpu` 2; two `yes` plus the login's own work reach about 170% (more than one CPU can);
+ the desktop comes up; minutes of running with a hundred cross-CPU fault resumes and no fault. Kernel fault counts
+ are of one CPU's order (7.6 and 5.6 million in the first 8 minutes).
3. N CPUs (`cpus=` defaults to the Linux CPUs less one for Linux), then the workloads: build a project, 4K playback.
diff --git a/fki-ko/fki.h b/fki-ko/fki.h
index f67be16..3d6e657 100644
--- a/fki-ko/fki.h
+++ b/fki-ko/fki.h
@@ -67,9 +67,10 @@ int fki_window_l1(unsigned long va, unsigned long long **l1_va, fki_u64 *l1_pa);
void fki_window_set(unsigned long long *slot, fki_u64 desc);
/*
* Called from inside fki_enter() (preemption and IRQs off): let Linux run (IRQs and preemption on)
- * until the counter reaches deadline or max_ns pass, then return with them off again.
+ * until the counter reaches deadline or max_ns pass, or fki_kick_cpu() is called for this CPU, then return with them off
+ * again. Not at all if *wake (when given) is already nonzero: the kicker sets it before kicking.
*/
-void fki_idle_until(fki_u64 counter_deadline, fki_u64 max_ns);
+void fki_idle_until(fki_u64 counter_deadline, fki_u64 max_ns, const volatile unsigned int *wake);
/*
* Called from inside fki_enter() while the hosted kernel is busy: let Linux take its pending interrupts and
* reschedule if it must (RCU, other tasks on this CPU), then return with IRQs and preemption off again.
@@ -86,6 +87,11 @@ long fki_net_recv(void *buf, unsigned long len);
long fki_net_pending(void);
/* Keep the calling task on one CPU (the hosted kernel sees that CPU's MPIDR). */
int fki_bind_cpu(int cpu);
+/* CPUs: how many are online, and a CPU's MPIDR (from ordinary Linux context) */
+int fki_num_cpus(void);
+int fki_cpu_mpidr(int cpu, fki_u64 *mpidr);
+/* Make the foreign kernel on a CPU look at its pending work: wake its idle call, or interrupt it (interrupts may be off) */
+void fki_kick_cpu(int cpu);
/*
* A helper kernel thread bound to one CPU: fn(arg) runs until it returns or fki_thread_stop() is called;
* fn should loop on !fki_thread_should_stop() and sleep with fki_msleep().
@@ -93,6 +99,10 @@ int fki_bind_cpu(int cpu);
void *fki_thread_start(int (*fn)(void *), void *arg, int cpu, const char *name);
void fki_thread_stop(void *thread);
int fki_thread_should_stop(void);
+/* In a helper thread: sleep until *flag is non-zero or the thread is told to stop; fki_thread_wake() wakes it (callable
+ * with interrupts off, after setting the flag) */
+void fki_thread_wait(const volatile unsigned long *flag);
+void fki_thread_wake(void *thread);
void fki_msleep(unsigned int ms);
/*
* Foreign kernel faults: a kernel-mode data or instruction abort whose address or faulting pc is in [lo, hi) is offered
@@ -105,6 +115,7 @@ unsigned long fki_regs_lr(void *regs);
unsigned long fki_regs_pstate(void *regs); /* the interrupted PSTATE (SPSR) */
void fki_regs_set_pc(void *regs, unsigned long pc);
void fki_regs_set_reg(void *regs, unsigned int n, unsigned long v); /* x0..x30 */
+unsigned long fki_regs_reg(void *regs, unsigned int n); /* x0..x30 */
int fki_fault_register(unsigned long lo, unsigned long hi, int (*handler)(unsigned long far, unsigned long esr, void *regs));
void fki_fault_unregister(void);
/* Read 8 bytes of RAM by physical address (debugging: walking a foreign page table). */
diff --git a/fki-ko/fki_hostcall.c b/fki-ko/fki_hostcall.c
index 48f3595..facfb10 100644
--- a/fki-ko/fki_hostcall.c
+++ b/fki-ko/fki_hostcall.c
@@ -41,6 +41,7 @@ static int hc_state; /* 0 idle, 1 request waiting, 2 read by the service, 3 re
static long hc_result;
struct hc_call { const void *req; unsigned long len; void *reply; unsigned long max; long result; };
+static DEFINE_MUTEX(hc_mutex); /* one call at a time through the single slot (several CPUs may call) */
static void hc_call_body(void *p)
{
@@ -50,6 +51,7 @@ static void hc_call_body(void *p)
local_irq_enable();
preempt_enable();
+ mutex_lock(&hc_mutex);
if (!hc_buf)
hc_buf = kvmalloc(HC_MAX, GFP_KERNEL);
if (!hc_buf || c->len > HC_MAX) {
@@ -84,6 +86,7 @@ static void hc_call_body(void *p)
hc_state = 0; hc_seq = 0;
spin_unlock(&hc_lock);
out:
+ mutex_unlock(&hc_mutex);
preempt_disable();
local_irq_disable();
c->result = r;
diff --git a/fki-ko/fki_mod.c b/fki-ko/fki_mod.c
index dc07192..6fd54c4 100644
--- a/fki-ko/fki_mod.c
+++ b/fki-ko/fki_mod.c
@@ -30,6 +30,7 @@
#include <linux/kprobes.h>
#include <linux/hrtimer.h>
#include <linux/kthread.h>
+#include <linux/smp.h>
#include <linux/delay.h>
#include <linux/err.h>
#include <linux/sched.h>
@@ -271,6 +272,25 @@ int fki_thread_should_stop(void)
}
EXPORT_SYMBOL(fki_thread_should_stop);
+void fki_thread_wait(const volatile unsigned long *flag)
+{
+ for (;;) {
+ set_current_state(TASK_INTERRUPTIBLE);
+ if (READ_ONCE(*flag) || kthread_should_stop())
+ break;
+ schedule();
+ }
+ __set_current_state(TASK_RUNNING);
+}
+EXPORT_SYMBOL(fki_thread_wait);
+
+void fki_thread_wake(void *thread)
+{
+ if (thread)
+ wake_up_process(thread);
+}
+EXPORT_SYMBOL(fki_thread_wake);
+
void fki_msleep(unsigned int ms)
{
msleep(ms);
@@ -314,6 +334,8 @@ void fki_regs_set_pc(void *regs, unsigned long pc) { instruction_pointer_set((st
EXPORT_SYMBOL(fki_regs_set_pc);
void fki_regs_set_reg(void *regs, unsigned int n, unsigned long v) { if (n < 31) ((struct pt_regs *)regs)->regs[n] = v; }
EXPORT_SYMBOL(fki_regs_set_reg);
+unsigned long fki_regs_reg(void *regs, unsigned int n) { return n < 31 ? ((struct pt_regs *)regs)->regs[n] : 0; }
+EXPORT_SYMBOL(fki_regs_reg);
static struct kprobe fki_fault_kp = { .symbol_name = "__do_kernel_fault", .pre_handler = fki_fault_pre };
static int fki_fault_registered;
@@ -538,7 +560,8 @@ EXPORT_SYMBOL(fki_window_set);
* from a stack that is not this task's, the work runs on a stack of our own laid out like Linux's (the lower half of a
* 2 * THREAD_SIZE aligned block, which the linear map gives an order-aligned page block).
*/
-static void *fki_alt_stack[NR_CPUS];
+static void *fki_alt_stack[NR_CPUS]; /* allocated at load: an order-3 atomic allocation can fail once memory is fragmented */
+#define FKI_ALT_STACK_ORDER get_order(2 * THREAD_SIZE)
asm(
" .pushsection .text\n"
@@ -606,20 +629,12 @@ static void fki_linux_runs_body(void (*fn)(void *), void *arg)
fn(arg);
return;
}
- if (!fki_alt_stack[cpu]) {
- struct page *pg = alloc_pages(GFP_ATOMIC, get_order(2 * THREAD_SIZE));
- if (!pg) {
- fn(arg); /* no memory: take the chance */
- return;
- }
- fki_alt_stack[cpu] = page_address(pg);
- }
fki_run_on_stack(fn, arg, (char *)fki_alt_stack[cpu] + THREAD_SIZE);
}
-struct fki_idle_args { fki_u64 ns; };
+struct fki_idle_args { fki_u64 ns; const volatile unsigned int *wake; };
-static struct task_struct *fki_idle_task; /* the task sleeping in fki_idle_until, for fki_net's receive wakeup */
+static struct task_struct *fki_idle_task[NR_CPUS]; /* the task sleeping in fki_idle_until on each CPU, for wakeups */
static void fki_idle_body(void *p)
{
@@ -629,9 +644,12 @@ static void fki_idle_body(void *p)
local_irq_enable();
preempt_enable();
set_current_state(TASK_UNINTERRUPTIBLE);
- WRITE_ONCE(fki_idle_task, current);
- schedule_hrtimeout_range(&t, 50000, HRTIMER_MODE_REL);
- WRITE_ONCE(fki_idle_task, NULL);
+ WRITE_ONCE(fki_idle_task[smp_processor_id()], current);
+ smp_mb(); /* pairs with fki_kick_cpu: it sees this task, or this sees the word it set first */
+ if (!a->wake || !READ_ONCE(*a->wake))
+ schedule_hrtimeout_range(&t, 50000, HRTIMER_MODE_REL);
+ __set_current_state(TASK_RUNNING);
+ WRITE_ONCE(fki_idle_task[smp_processor_id()], NULL);
preempt_disable();
local_irq_disable();
}
@@ -645,7 +663,7 @@ static void fki_yield_body(void *p)
local_irq_disable();
}
-void fki_idle_until(fki_u64 counter_deadline, fki_u64 max_ns)
+void fki_idle_until(fki_u64 counter_deadline, fki_u64 max_ns, const volatile unsigned int *wake)
{
u64 now = __arch_counter_get_cntvct(), freq = arch_timer_get_cntfrq(), ns;
struct fki_idle_args a;
@@ -659,6 +677,7 @@ void fki_idle_until(fki_u64 counter_deadline, fki_u64 max_ns)
if (ns > max_ns)
ns = max_ns;
a.ns = ns;
+ a.wake = wake;
fki_linux_runs(fki_idle_body, &a);
}
EXPORT_SYMBOL(fki_idle_until);
@@ -669,6 +688,51 @@ void fki_yield(void)
}
EXPORT_SYMBOL(fki_yield);
+/*
+ * Make the foreign kernel on a CPU look at what another CPU left for it: wake it if it sleeps in fki_idle_until,
+ * otherwise interrupt that CPU (its user code runs with interrupts on; its kernel looks where it enables its own).
+ * Callable with interrupts off.
+ */
+static void fki_kick_fn(void *unused) { }
+static DEFINE_PER_CPU(call_single_data_t, fki_kick_csd);
+
+void fki_kick_cpu(int cpu)
+{
+ struct task_struct *t;
+
+ if (cpu < 0 || cpu >= nr_cpu_ids)
+ return;
+ smp_mb(); /* the caller's pending word before the idle task: pairs with fki_idle_body */
+ t = READ_ONCE(fki_idle_task[cpu]);
+ if (t)
+ wake_up_process(t);
+ else if (cpu != smp_processor_id())
+ /* irq_work_queue_on is not exported; an IPI already on its way (-EBUSY) is just as good */
+ smp_call_function_single_async(cpu, per_cpu_ptr(&fki_kick_csd, cpu));
+}
+EXPORT_SYMBOL(fki_kick_cpu);
+
+static void fki_read_mpidr(void *p) { *(u64 *)p = read_cpuid_mpidr(); }
+
+int fki_cpu_mpidr(int cpu, fki_u64 *mpidr)
+{
+ u64 v = 0;
+ int err;
+
+ if (cpu < 0 || cpu >= nr_cpu_ids || !cpu_online(cpu))
+ return -EINVAL;
+ err = smp_call_function_single(cpu, fki_read_mpidr, &v, 1);
+ *mpidr = v;
+ return err;
+}
+EXPORT_SYMBOL(fki_cpu_mpidr);
+
+int fki_num_cpus(void)
+{
+ return num_online_cpus();
+}
+EXPORT_SYMBOL(fki_num_cpus);
+
void fki_realtime(fki_u64 *sec, fki_u64 *nsec)
{
struct timespec64 ts;
@@ -699,9 +763,9 @@ static netdev_tx_t fki_net_xmit(struct sk_buff *skb, struct net_device *dev)
dev->stats.tx_packets++;
dev->stats.tx_bytes += skb->len;
skb_queue_tail(&fki_net_rxq, skb);
- t = READ_ONCE(fki_idle_task);
+ t = READ_ONCE(fki_idle_task[0]);
if (t)
- wake_up_process(t); /* the foreign kernel is idle: let it see the frame now */
+ wake_up_process(t); /* the foreign kernel's first CPU is idle: let it see the frame now */
return NETDEV_TX_OK;
}
@@ -788,11 +852,32 @@ long fki_net_pending(void)
}
EXPORT_SYMBOL(fki_net_pending);
+static void fki_free_alt_stacks(void)
+{
+ int cpu;
+
+ for_each_possible_cpu(cpu) {
+ if (fki_alt_stack[cpu])
+ free_pages((unsigned long)fki_alt_stack[cpu], FKI_ALT_STACK_ORDER);
+ fki_alt_stack[cpu] = NULL;
+ }
+}
+
static int __init fki_init(void)
{
struct net_device *dev;
- int err;
+ int err, cpu;
+ for_each_possible_cpu(cpu) {
+ struct page *pg = alloc_pages(GFP_KERNEL, FKI_ALT_STACK_ORDER);
+
+ if (!pg) {
+ fki_free_alt_stacks();
+ return -ENOMEM;
+ }
+ fki_alt_stack[cpu] = page_address(pg);
+ INIT_CSD(per_cpu_ptr(&fki_kick_csd, cpu), fki_kick_fn, NULL);
+ }
skb_queue_head_init(&fki_net_rxq);
fki_reserve();
err = fki_hostcall_init();
@@ -827,6 +912,7 @@ static void __exit fki_exit(void)
fki_netdev = NULL;
}
skb_queue_purge(&fki_net_rxq);
+ fki_free_alt_stacks();
}
module_init(fki_init);
module_exit(fki_exit);
diff --git a/kexts/XnuCPU/XnuCPU.cpp b/kexts/XnuCPU/XnuCPU.cpp
new file mode 100644
index 0000000..6c2245e
--- /dev/null
+++ b/kexts/XnuCPU/XnuCPU.cpp
@@ -0,0 +1,134 @@
+// SPDX-License-Identifier: BSD-2-Clause
+// XnuCPU: the hosted system's CPUs, one IOCPU per /cpus/cpuN node xnu.ko describes (compatible "xnulinux,cpu").
+//
+// On a Mac the platform's CPU driver registers each CPU with the kernel (ml_processor_register) and starts and signals
+// them through its own hardware; while hosted, the CPUs are Linux's: XNU's machine layer starts a CPU through the host
+// (cpu_start, LINUX64_CALL_CPU_START: xnu.ko runs it on a Linux kernel thread of that CPU) and signals one by setting
+// its pending IPI and asking the host to make it look (linux64_cpu_signal). This driver only registers the CPUs (XNU 12377
+// boots each one inside ml_processor_register) and routes IOCPU's signalCPU there. Its structure follows the ArmCpu driver of
+// DroidVM (BSD-2-Clause-Patent), without the GIC.
+#include <IOKit/IOCPU.h>
+#include <IOKit/IOLib.h>
+#include <IOKit/IOLocks.h>
+#include <libkern/c++/OSData.h>
+#include <libkern/c++/OSSymbol.h>
+#include <machine/machine_routines.h>
+
+extern "C" void linux64_cpu_signal(unsigned int cpu);
+
+class XnuCPU;
+
+namespace {
+// Reported idle latency: ml_delay_should_spin() blocks every IODelay when this is 0 (never reported), turning each short
+// delay into a timer; with a short latency short delays spin and long ones still block (as ArmCpu found).
+constexpr uint64_t kIdleLatencyNs = 5000;
+constexpr unsigned kMaxCPUs = 64;
+
+// The boot CPU registers first (registering boots a CPU, and the others send it IPIs from then on, as AppleARMSMP's
+// order is); a secondary matched before it waits here and is registered by the boot CPU's start
+IOLock *gLock;
+bool gBootRegistered;
+XnuCPU *gWaiting[kMaxCPUs];
+unsigned gWaitingCount;
+}
+
+class XnuCPU : public IOCPU {
+ OSDeclareDefaultStructors(XnuCPU)
+ uint32_t fPhysical = 0, fLogical = 0;
+ const OSSymbol *fName = nullptr;
+ bool registerProcessor();
+
+public:
+ bool start(IOService *provider) override;
+ void initCPU(bool boot) override;
+ void quiesceCPU() override {}
+ void haltCPU() override { setCPUState(kIOCPUStateStopped); }
+ kern_return_t startCPU(vm_offset_t, vm_offset_t) override { return KERN_SUCCESS; } // cpu_start asks the host
+ void signalCPU(IOCPU *target) override { linux64_cpu_signal(target->getCPUNumber()); }
+ const OSSymbol *getCPUName() override { return fName; }
+};
+
+OSDefineMetaClassAndStructors(XnuCPU, IOCPU)
+
+bool XnuCPU::start(IOService *provider)
+{
+ OSData *reg = OSDynamicCast(OSData, provider->getProperty("reg"));
+ if (reg == nullptr || reg->getLength() < sizeof(fPhysical)) {
+ return false;
+ }
+ memcpy(&fPhysical, reg->getBytesNoCopy(), sizeof(fPhysical));
+ fLogical = static_cast<uint32_t>(ml_get_cpu_number(fPhysical));
+ bool boot = fLogical == static_cast<uint32_t>(ml_get_boot_cpu_number());
+ fName = OSSymbol::withCStringNoCopy(boot ? "xnulinux boot CPU" : "xnulinux CPU");
+ if (fName == nullptr || !IOCPU::start(provider)) {
+ return false;
+ }
+ setCPUNumber(fLogical);
+ if (boot) {
+ if (!registerProcessor()) {
+ return false;
+ }
+ IOLockLock(gLock);
+ gBootRegistered = true;
+ unsigned n = gWaitingCount;
+ gWaitingCount = 0;
+ IOLockUnlock(gLock);
+ for (unsigned i = 0; i < n; i++) {
+ gWaiting[i]->registerProcessor();
+ gWaiting[i]->release();
+ }
+ return true;
+ }
+ IOLockLock(gLock);
+ if (!gBootRegistered && gWaitingCount < kMaxCPUs) {
+ retain();
+ gWaiting[gWaitingCount++] = this;
+ IOLockUnlock(gLock);
+ return true;
+ }
+ IOLockUnlock(gLock);
+ return registerProcessor();
+}
+
+// Register this CPU with the kernel; XNU 12377's ml_processor_register boots it too (processor_boot: cpu_start, which
+// asks the host)
+bool XnuCPU::registerProcessor()
+{
+ bool boot = fLogical == static_cast<uint32_t>(ml_get_boot_cpu_number());
+ ml_processor_info_t info = {};
+ info.cpu_id = this;
+ info.phys_id = fPhysical;
+ info.log_id = fLogical;
+ info.cluster_id = static_cast<uint32_t>(ml_get_cluster_number(fPhysical));
+ info.cluster_type = ml_get_boot_cluster_type();
+ info.powergate_latency = kIdleLatencyNs;
+ ipi_handler_t ipi = nullptr;
+ perfmon_interrupt_handler_func pmi = nullptr;
+ if (ml_processor_register(&info, &machProcessor, &ipi, &pmi) != KERN_SUCCESS) {
+ IOLog("XnuCPU: CPU %u (MPIDR %#x) registration failed\n", fLogical, fPhysical);
+ return false;
+ }
+ ipi_handler = ipi; // the machine layer calls cpu_signal_handler itself (linux64_ipi_take)
+ registerService();
+ IOLog("XnuCPU: CPU %u (MPIDR %#x) registered%s\n", fLogical, fPhysical, boot ? ", boot CPU" : "");
+ return true;
+}
+
+void XnuCPU::initCPU(bool boot)
+{
+ setCPUState(kIOCPUStateRunning);
+ // XNU clears a CPU's SIGPdisabled when it takes its first IPI (processor_up): send it one, as ArmCpu does
+ signalCPU(this);
+ (void)boot;
+}
+
+// Module start/stop for the collection's kext entry; the driver starts through IOKit matching.
+#include <mach/kmod.h>
+extern "C" {
+kern_return_t native_kext_start(kmod_info_t *, void *)
+{
+ gLock = IOLockAlloc();
+ return gLock ? KERN_SUCCESS : KERN_FAILURE;
+}
+kern_return_t native_kext_stop(kmod_info_t *, void *) { return KERN_SUCCESS; }
+}
diff --git a/kexts/XnuCPU/XnuCPU.json b/kexts/XnuCPU/XnuCPU.json
new file mode 100644
index 0000000..2e6d081
--- /dev/null
+++ b/kexts/XnuCPU/XnuCPU.json
@@ -0,0 +1,24 @@
+{
+ "name": "XnuCPU",
+ "bundle": "org.xnulinux.driver.XnuCPU",
+ "version": "1.0.0",
+ "objects": "out/x12377/native-kexts/XnuCPU/objects.json",
+ "start": "_native_kext_start",
+ "stop": "_native_kext_stop",
+ "libraries": {
+ "com.apple.kpi.iokit": "18.0.0",
+ "com.apple.kpi.libkern": "18.0.0",
+ "com.apple.kpi.mach": "18.0.0",
+ "com.apple.kpi.private": "18.0.0",
+ "com.apple.kpi.unsupported": "18.0.0"
+ },
+ "personalities": {
+ "XnuCPU": {
+ "CFBundleIdentifier": "org.xnulinux.driver.XnuCPU",
+ "IOClass": "XnuCPU",
+ "IOProviderClass": "IOPlatformDevice",
+ "IONameMatch": "xnulinux,cpu",
+ "IOProbeScore": 2000
+ }
+ }
+}
diff --git a/kexts/XnuDisk/XnuDisk.cpp b/kexts/XnuDisk/XnuDisk.cpp
index 9c437ef..8fe36fb 100644
--- a/kexts/XnuDisk/XnuDisk.cpp
+++ b/kexts/XnuDisk/XnuDisk.cpp
@@ -3,8 +3,8 @@
// The file is a whole disk as macOS makes one: a GUID partition table and an APFS container (System and Data volumes),
// built on a macOS host with Apple's own tools (scripts/mk-macvm-disk.sh). IOStorageFamily's IOBlockStorageDriver takes
// this device, publishes its media, the GUID partition scheme finds the container partition and APFS mounts its volumes,
-// as on a Mac's internal SSD. I/O goes through the host: xnu.ko disk=, upcalls 820 (I/O) and 821 (size) in
-// bsd/net/if_linux64.c, done synchronously through a bounce buffer (the host reads and writes the file in Linux context).
+// as on a Mac's internal SSD. I/O goes through the host: xnu.ko disk=, LINUX64_CALL_DISK_RW and _SIZE in
+// bsd/kern/linux64_host.c, done synchronously through a bounce buffer (the host reads and writes the file in Linux context).
// IOBlockStorageDevice.h declares some of its virtual methods (doLockUnlockMedia, reportLockability,
// reportPollRequirements, doDiscard) only under TARGET_OS_OSX; the collection's IOStorageFamily is the macOS one, so
// without it this class's vtable is three slots short of the family's and the family's calls land on the wrong methods
@@ -18,6 +18,7 @@
#include <IOKit/storage/IOBlockStorageDevice.h>
#include <IOKit/storage/IOStorageProtocolCharacteristics.h>
#include <IOKit/storage/IOStorageDeviceCharacteristics.h>
+#include <kern/thread.h>
extern "C" uint64_t linux64_disk_size(void);
extern "C" long linux64_disk_rw(int write, void *buffer, unsigned long length, unsigned long offset);
@@ -36,6 +37,7 @@ class XnuDisk : public IOBlockStorageDevice {
public:
bool start(IOService *provider) override;
+ static void publishAfterBSD(void *self, wait_result_t);
void free() override;
IOReturn doEjectMedia() override { return kIOReturnUnsupported; }
IOReturn doFormatMedia(UInt64) override { return kIOReturnUnsupported; }
@@ -101,11 +103,39 @@ bool XnuDisk::start(IOService *provider)
}
OSSafeReleaseNULL(protocol);
OSSafeReleaseNULL(device);
- registerService();
+ /*
+ * The disk is published once the IOBSD resource is (bsd_init's IOKitBSDInit publishes it, then waits for the root
+ * disk). Published earlier, it can deadlock the boot: APFS starts the first container's volumes holding its lock and
+ * waits there for IOBSD on IOResources, while IOResources' own matching (re-run when IOBSD is published) probes
+ * an APFS personality that needs that lock; the main container is never probed and bsd_init waits for its root
+ * volume forever (often, on one CPU). A Mac's internal disk sits under its PCIe controller and
+ * appears in its own time; ours hangs off IOResources and appears at once.
+ */
+ thread_t thread;
+ retain();
+ if (kernel_thread_start(&XnuDisk::publishAfterBSD, this, &thread) == KERN_SUCCESS) {
+ thread_deallocate(thread);
+ } else {
+ release();
+ registerService();
+ }
IOLog("XnuDisk: %llu blocks of %llu bytes (%llu MB)\n", fBlocks, kBlockSize, bytes >> 20);
return true;
}
+void XnuDisk::publishAfterBSD(void *arg, wait_result_t)
+{
+ XnuDisk *self = (XnuDisk *)arg;
+ OSDictionary *match = IOService::resourceMatching("IOBSD");
+ IOService *bsd = match ? IOService::waitForMatchingService(match) : nullptr;
+ OSSafeReleaseNULL(match);
+ OSSafeReleaseNULL(bsd);
+ self->registerService();
+ IOLog("XnuDisk: published after IOBSD\n");
+ self->release();
+ thread_terminate(current_thread());
+}
+
void XnuDisk::free()
{
if (fBounce)
diff --git a/kexts/XnuEthernet/XnuEthernet.cpp b/kexts/XnuEthernet/XnuEthernet.cpp
index 252a6cf..5bbd276 100644
--- a/kexts/XnuEthernet/XnuEthernet.cpp
+++ b/kexts/XnuEthernet/XnuEthernet.cpp
@@ -1,7 +1,7 @@
// SPDX-License-Identifier: BSD-2-Clause-Patent
// XnuEthernet: en0 of the hosted macOS, an IOEthernetController whose frames go through the host. It follows DroidVMEthernet of
// Droid-VM/macOS-DroidVM (overlay/kext/DroidVMEthernet.cpp, BSD-2-Clause-Patent) without its virtio-net: the transport is the
-// hosted kernel's (bsd/net/if_linux64.c, upcalls 816/817/815 to the Linux netdev xnu0, where Linux routes, NATs and answers DHCP).
+// hosted kernel's (bsd/kern/linux64_host.c, LINUX64_CALL_NET_SEND/RECV to the Linux netdev xnu0, where Linux routes, NATs and answers DHCP).
//
// Why a driver and not only the kernel's own ifnet: IOTimeSyncClockManager takes the TimeSync clock identifier from a built-in
// IOEthernetInterface's MAC, once, at its start; without one it never registers, clocksyncd waits for it and WindowServer
@@ -19,7 +19,7 @@
#include <kern/thread.h>
#include <net/ethernet.h>
-// bsd/net/if_linux64.c (the xnulinux kernel patch): one frame to the host, the next frame from it (bytes, 0 when none waits).
+// bsd/kern/linux64_host.c (the xnulinux kernel patch): one frame to the host, the next frame from it (bytes, 0 when none waits).
extern "C" long linux64_net_send(const void *frame, unsigned long length);
extern "C" long linux64_net_recv(void *buffer, unsigned long size);
diff --git a/kexts/XnuInput/XnuInput.cpp b/kexts/XnuInput/XnuInput.cpp
index f0efaf7..2d9bccf 100644
--- a/kexts/XnuInput/XnuInput.cpp
+++ b/kexts/XnuInput/XnuInput.cpp
@@ -4,7 +4,7 @@
// (overlay/kext/DroidVMInput/DroidVMInput.cpp, BSD-2-Clause-Patent): the same report descriptors (QEMU's USB keyboard and tablet),
// the same evdev-to-report translation. Its events come from the host instead of virtio-input: Linux evdev records
// {u16 type, u16 code, s32 value} that tools/hosted/xnu-input.py appends to xnu.ko's input_in file, read through the hosted
-// kernel's upcall (linux64_input_read, bsd/net/if_linux64.c). Keys (EV_KEY codes below 0x100) go to the keyboard; buttons,
+// kernel's upcall (linux64_input_read, bsd/kern/linux64_host.c). Keys (EV_KEY codes below 0x100) go to the keyboard; buttons,
// absolute X/Y (0..32767 across the screen) and the wheel to the tablet; SYN_REPORT ends a frame.
#include <IOKit/IOBufferMemoryDescriptor.h>
#include <IOKit/IOLib.h>
diff --git a/scripts/xnulinux-boot.sh b/scripts/xnulinux-boot.sh
index b5772a5..e5b51f7 100755
--- a/scripts/xnulinux-boot.sh
+++ b/scripts/xnulinux-boot.sh
@@ -7,7 +7,7 @@
# 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)
# FB_DUMP (/var/tmp/xnu-fb.raw) KEYSTORE (/var/tmp/xnu-keystore.bin) TRUSTCACHE (xnu/trustcache-mac.bin)
-# IMAGE (xnu/kc.bin: the kernel collection under /lib/firmware) GPU (auto|off)
+# IMAGE (xnu/kc.bin: the kernel collection under /lib/firmware) GPU (auto|off) CPUS (1: the hosted system's CPUs) XNU_ARGS (more xnu.ko parameters)
set -euo pipefail
cd "$(dirname "$0")/.."
if [ "${1:-}" = stop ]; then # end the running hosted system (its disk synced first) and remove xnu.ko
@@ -19,7 +19,7 @@ if [ "${1:-}" = stop ]; then # end the running hosted system (its disk synced fi
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}
+DISK=${DISK:-/var/tmp/mac.img}; RAM_MB=${RAM_MB:-7900}; GPU=${GPU:-auto}; CPUS=${CPUS:-1}
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}
KEYSTORE=${KEYSTORE:-/var/tmp/xnu-keystore.bin}; TRUSTCACHE=${TRUSTCACHE:-xnu/trustcache-mac.bin}; IMAGE=${IMAGE:-xnu/kc.bin}
BOOTARGS=${BOOTARGS:-amfi_get_out_of_my_way=1 lp-sip0=2050}
@@ -58,9 +58,9 @@ rm -f "$KEYSTORE"; truncate -s 1M "$KEYSTORE" # fresh each boot, as the disk was
for try in 1 2 3 4 5 6 7 8 9; do
sync; echo 3 | sudo tee /proc/sys/vm/drop_caches >/dev/null; echo 1 | sudo tee /proc/sys/vm/compact_memory >/dev/null
sudo dmesg -C
- sudo setsid nohup insmod xnu-ko/xnu.ko mode=3 ram_mb="$RAM_MB" image="$IMAGE" \
+ sudo setsid nohup insmod xnu-ko/xnu.ko mode=3 cpus="$CPUS" 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\"" \
+ console_in="$CONSOLE_IN" input_in="$INPUT_IN" fb_dump="$FB_DUMP" keystore="$KEYSTORE" bootargs="\"$BOOTARGS\"" ${XNU_ARGS:-} \
> /var/tmp/xnu-insmod.log 2>&1 < /dev/null &
sleep 5
sudo dmesg | grep -aq "contiguous allocation failed" || break
diff --git a/xnu-ko/world.S b/xnu-ko/world.S
index e0e00e8..d5a9a2c 100644
--- a/xnu-ko/world.S
+++ b/xnu-ko/world.S
@@ -1,7 +1,15 @@
/* World switch, see world.h. No PAC instructions here: keys change under our feet.
- * TPIDR_EL1 stays Linux's: the LINUX64 XNU keeps its thread pointer in memory (linux64_tpidr),
- * so a fault taken in XNU code reaches Linux with a sane per-cpu base and becomes a normal oops. */
-#define W(reg) adrp reg, xnu_W; add reg, reg, :lo12:xnu_W
+ * x18 is Linux's shadow call stack pointer (CONFIG_SHADOW_CALL_STACK), which belongs to the Linux task that entered the
+ * world on this CPU. XNU does not use it or save it per thread, so it stays this CPU's while XNU runs (Linux code XNU
+ * calls pushes and pops on it, balanced); the way out puts back the value the task entered with.
+ * TPIDR_EL1 stays Linux's: the LINUX64 XNU keeps its thread pointer in TPIDRRO_EL0, so a fault taken in XNU code
+ * reaches Linux with a sane per-cpu base and becomes a normal oops. Each CPU has its own save area. */
+/*
+ * This CPU's save area: xnu_worlds[slot], slot = affinity 0 and 1 of MPIDR_EL1, four bits each (LINUX64_CPU_SLOT).
+ * Clobbers x10.
+ */
+#define W(reg) mrs reg, mpidr_el1; and x10, reg, #0xf; ubfx reg, reg, #8, #4; orr reg, x10, reg, lsl #4; \
+ adrp x10, xnu_worlds; add x10, x10, :lo12:xnu_worlds; ldr reg, [x10, reg, lsl #3]
/*
* The user half (TTBR0, TCR.T0SZ) belongs to whichever world runs: XNU switches TTBR0 to its user pmaps (with its own
@@ -42,6 +50,7 @@
.type xnu_world_call, %function
xnu_world_call:
W(x9)
+ str x18, [x9, #464]
stp x19, x20, [x9, #0]
stp x21, x22, [x9, #16]
stp x23, x24, [x9, #32]
@@ -74,6 +83,7 @@ xnu_world_abort: /* from the upcall: Linux keys and TPIDR are live */
W(x9)
mov x19, #1
2: TO_LINUX_MM
+ ldr x18, [x9, #464]
ldr x10, [x9, #216]
msr tpidr_el0, x10
ldr x10, [x9, #224]
diff --git a/xnu-ko/world.h b/xnu-ko/world.h
index f13a5ae..bd168ec 100644
--- a/xnu-ko/world.h
+++ b/xnu-ko/world.h
@@ -12,12 +12,15 @@ struct xnu_world {
unsigned long long linux_ttbr0, linux_tcr; /* 416, 424: Linux's user address space while XNU runs */
unsigned long long xnu_ttbr0, xnu_tcr; /* 432, 440: XNU's (its user pmaps, its T0SZ) */
unsigned long long xnu_tpidr, xnu_tpidrro; /* 448, 456: XNU's user TLS registers across an upcall */
+ unsigned long long linux_scs; /* 464: x18, the shadow call stack of the Linux task that entered */
};
+_Static_assert(__builtin_offsetof(struct xnu_world, linux_scs) == 464, "xnu_world layout");
_Static_assert(__builtin_offsetof(struct xnu_world, xnu_tpidrro) == 456, "xnu_world layout");
_Static_assert(__builtin_offsetof(struct xnu_world, linux_ttbr0) == 416, "xnu_world layout");
_Static_assert(sizeof(struct fki_pac_keys) == 88, "fki_pac_keys layout");
_Static_assert(__builtin_offsetof(struct xnu_world, xnu_keys) == 328, "xnu_world layout");
-extern struct xnu_world xnu_W;
+extern struct xnu_world xnu_W; /* the boot CPU's */
+extern struct xnu_world *xnu_worlds[]; /* each CPU's, by slot (LINUX64_CPU_SLOT) */
/* Run fn(arg) in the XNU world. 0: fn returned; 1: the hook ended the run. */
long xnu_world_call(unsigned long fn, unsigned long arg);
/* The address XNU calls (linux64_hook); it calls xnu_hook(stage) in the Linux world. */
diff --git a/xnu-ko/xnu_main.c b/xnu-ko/xnu_main.c
index 03b7a6d..9fa6360 100644
--- a/xnu-ko/xnu_main.c
+++ b/xnu-ko/xnu_main.c
@@ -42,6 +42,18 @@ static int quiet_line(const char *l, unsigned n)
if (!x_strncmp(l + k, "triggered unnest", 16)) return 1;
return 0;
}
+/* XNU's CPUs: Linux CPUs 0 .. cpus-1 (XNU's CPU 0 is Linux CPU 0, where xnu.ko's loading task runs) */
+#define XNU_MAX_CPUS 16
+static int cpus = 1;
+module_param(cpus, int, 0444);
+static struct xnu_world worlds[XNU_MAX_CPUS]; /* worlds[0] is xnu_W's twin: see xnu_worlds */
+struct xnu_world *xnu_worlds[LINUX64_CPU_SLOTS]; /* by CPU slot (world.S finds its CPU's save area here) */
+static signed char linux_cpu_of_slot[LINUX64_CPU_SLOTS];
+static unsigned long long cpu_mpidr[XNU_MAX_CPUS];
+static void *cpu_thread[XNU_MAX_CPUS];
+static volatile int cpu_running[XNU_MAX_CPUS];
+static u64_t a_cpu_entry; /* XNU's linux64_cpu_entry */
+static inline unsigned this_slot(void) { unsigned long m; __asm__ volatile("mrs %0, mpidr_el1" : "=r"(m)); return LINUX64_CPU_SLOT(m); }
/* 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);
@@ -211,10 +223,12 @@ static void walk_log(const char *what, u64_t va, const unsigned long long *l1)
* Kernel page faults on XNU addresses, taken in Linux's vectors while XNU runs (XNU's keys and stack live), go to
* XNU's own linux64_kernel_fault (vm_fault on the kernel map). in_xnu is 0 while host code runs (upcalls, monitor).
*/
-static volatile int in_xnu;
+static volatile int in_xnu_slot[LINUX64_CPU_SLOTS];
+#define in_xnu in_xnu_slot[this_slot()]
static unsigned long (*xnu_kfault)(unsigned long far, unsigned long esr);
static unsigned long (*xnu_kfault_recover)(unsigned long pc, unsigned long far, unsigned long esr);
static unsigned long kfaults;
+static unsigned long kfault_moved; /* kernel faults whose vm_fault came back on another CPU (the monitor's moved=) */
#define XNU_VA_LO 0xffffffe000000000ULL
#define XNU_VA_HI 0xfffffffc00000000ULL
@@ -225,11 +239,18 @@ static unsigned long kfaults;
* 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;
+/* each CPU's: the fault handler and the trampoline it returns into run on the same CPU, with nothing between them */
+static struct { unsigned long far, esr, pc, pstate; } xnu_deferred_slot[LINUX64_CPU_SLOTS];
+#define xnu_deferred xnu_deferred_slot[this_slot()]
extern void xnu_fault_tramp(void);
extern void xnu_world_fault_abort(void);
-unsigned long xnu_fault_deferred(unsigned long *frame);
+/*
+ * No shadow call stack here: vm_fault may block, and the thread may come back on another CPU, whose Linux task's shadow
+ * stack x18 then points into (the return address pushed on the first CPU's would be popped from the second's). XNU never
+ * saves x18 per thread, so the register follows the CPU: what this calls pushes and pops on the current CPU's.
+ */
+unsigned long xnu_fault_deferred(unsigned long *frame) __attribute__((no_sanitize("shadow-call-stack")));
unsigned long xnu_fault_deferred(unsigned long *frame)
{
unsigned long far = xnu_deferred.far, esr = xnu_deferred.esr, pc = xnu_deferred.pc;
@@ -242,7 +263,21 @@ unsigned long xnu_fault_deferred(unsigned long *frame)
* 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) {
+ unsigned s0 = this_slot();
+ long kr = xnu_kfault(far, esr);
+ if (this_slot() != s0) {
+ /*
+ * vm_fault blocked and the thread came back on another CPU. xnu_fault_tramp's eret restores every register
+ * of the faulting context from frame, x18 included: that would be the first CPU's shadow stack pointer, and
+ * from then on this CPU's upcalls push and pop on the first CPU's Linux task's shadow stack while that CPU
+ * uses it too (corrupted shadow stacks, FPAC in whatever Linux code runs next). x18 follows the CPU.
+ */
+ unsigned long x18;
+ __asm__ volatile("mov %0, x18" : "=r"(x18));
+ frame[18] = x18;
+ kfault_moved++;
+ }
+ if (kr == 0) {
if (repeats && (repeats & (repeats - 1)) == 0 && repeats >= 1024) {
logkv("xnu: one address keeps taking resolved kernel faults, repeats", repeats);
logkv("xnu: far", far);
@@ -321,10 +356,52 @@ static int xnu_fault(unsigned long far, unsigned long esr, void *regs)
logkv("xnu: lr ", fki_regs_lr(regs));
logkv("xnu: far", far);
logkv("xnu: esr", esr);
+ logkv("xnu: CPU slot", this_slot());
+ logkv("xnu: x0 ", fki_regs_reg(regs, 0));
+ logkv("xnu: x1 ", fki_regs_reg(regs, 1));
+ { /* XNU's frame-pointer chain (return addresses with the kernel's all-ones top in place of their PAC bits) */
+ unsigned long *fp = (unsigned long *)fki_regs_reg(regs, 29);
+ for (int i = 0; i < 12 && fp && !((unsigned long)fp & 15) && (unsigned long)fp >= XNU_VA_LO &&
+ (unsigned long)fp < XNU_VA_HI; i++) {
+ logkv("xnu: frame", fp[1] | 0xffffff8000000000ul);
+ if ((unsigned long *)fp[0] <= fp) break;
+ fp = (unsigned long *)fp[0];
+ }
+ }
fki_regs_set_pc(regs, (unsigned long)xnu_world_fault_abort);
return 0;
}
+/* A secondary CPU's host thread: its own world, entered at linux64_cpu_entry(cpu_data); returns when the run ends */
+static unsigned long cpu_start_arg[XNU_MAX_CPUS];
+static int park_secondaries; /* diagnostics: 1 keeps secondary CPUs out of XNU */
+module_param(park_secondaries, int, 0444);
+static int cpu_fn(void *arg)
+{
+ int c = (int)(unsigned long)arg;
+
+ fki_thread_wait(&cpu_start_arg[c]); /* until XNU starts this CPU (LINUX64_CALL_CPU_START) */
+ if (!cpu_start_arg[c])
+ return 0; /* the run ended first: told to stop */
+ logkv("xnu: XNU CPU starts on Linux CPU", (u64_t)c);
+ if (park_secondaries) { /* diagnostics: the CPU is asked for but never enters XNU */
+ logkv("xnu: secondary CPU parked (park_secondaries)", (u64_t)c);
+ cpu_running[c] = 0;
+ while (!fki_thread_should_stop())
+ fki_msleep(10);
+ return 0;
+ }
+ in_xnu = 1;
+ long r = xnu_world_call(a_cpu_entry, cpu_start_arg[c]);
+ in_xnu = 0;
+ if (!r) logkv("xnu: linux64_cpu_entry returned (unexpected) on CPU", (u64_t)c);
+ stop_run = 1; /* one CPU's run ending (a fatal fault, a stop) ends all of them */
+ cpu_running[c] = 0;
+ while (!fki_thread_should_stop()) /* kthread_stop() from the module's exit wants the thread alive */
+ fki_msleep(10);
+ return 0;
+}
+
/* 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)
@@ -494,7 +571,8 @@ static long xnu_hook_body(unsigned long call, unsigned long a1, unsigned long a2
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);
+ fki_idle_until(fki_counter() + ns * fki_counter_frequency() / 1000000000ULL, ns,
+ (const volatile unsigned int *)a2);
}
return idle_max && idles >= (unsigned long)idle_max;
}
@@ -533,6 +611,24 @@ static long xnu_hook_body(unsigned long call, unsigned long a1, unsigned long a2
}
return 1;
}
+ if (call == LINUX64_CALL_CPU_START) { /* start XNU's CPU of MPIDR a1 at linux64_cpu_entry(a2), asynchronously */
+ int c = linux_cpu_of_slot[LINUX64_CPU_SLOT(a1)];
+ /* its thread was made before XNU ran (an upcall runs with preemption off: no thread creation here) */
+ if (c <= 0 || c >= cpus || !cpu_thread[c] || !a2 || cpu_start_arg[c]) {
+ logkv("xnu: XNU asked to start a CPU it was not given, MPIDR", a1);
+ return 0;
+ }
+ cpu_running[c] = 1;
+ WRITE_ONCE(cpu_start_arg[c], a2);
+ fki_thread_wake(cpu_thread[c]);
+ return 0;
+ }
+ if (call == LINUX64_CALL_IPI) { /* XNU's CPU of MPIDR a1 has an IPI pending: make it look */
+ int c = linux_cpu_of_slot[LINUX64_CPU_SLOT(a1)];
+ if (c >= 0)
+ fki_kick_cpu(c);
+ return 0;
+ }
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 */
@@ -555,12 +651,30 @@ static struct boot_args_v2 *build_boot(unsigned char *base_va, u64_t phys, u64_t
static unsigned char seed[256];
fki_random(seed, sizeof(seed));
- /* XNU identifies its CPU by MPIDR: run on CPU 0 and describe exactly that CPU. */
+ /*
+ * XNU identifies its CPUs by MPIDR: its CPU 0 runs here, bound to Linux CPU 0; CPUs 1 .. cpus-1 are Linux's of the
+ * same numbers, started when XNU asks (LINUX64_CALL_CPU_START). Their slots in the per-CPU arrays must differ.
+ */
int berr = fki_bind_cpu(0);
if (berr) { logkv("xnu: cannot bind to cpu0, err", (u64_t)berr); return 0; }
- u64_t mpidr; __asm__ volatile("mrs %0, mpidr_el1" : "=r"(mpidr));
- mpidr &= 0xffff; /* XNU compares Aff1:Aff0 */
+ if (cpus < 1) cpus = 1;
+ if (cpus > XNU_MAX_CPUS) cpus = XNU_MAX_CPUS;
+ if (cpus > fki_num_cpus()) cpus = fki_num_cpus();
+ for (int i = 0; i < LINUX64_CPU_SLOTS; i++) linux_cpu_of_slot[i] = -1;
+ for (int c = 0; c < cpus; c++) {
+ fki_u64 m = 0;
+ if (fki_cpu_mpidr(c, &m) || linux_cpu_of_slot[LINUX64_CPU_SLOT(m)] >= 0) {
+ logkv("xnu: no distinct MPIDR slot for Linux CPU, using CPUs below it:", (u64_t)c);
+ cpus = c;
+ break;
+ }
+ cpu_mpidr[c] = m & 0xffff; /* XNU compares Aff1:Aff0 */
+ linux_cpu_of_slot[LINUX64_CPU_SLOT(m)] = (signed char)c;
+ xnu_worlds[LINUX64_CPU_SLOT(m)] = c ? &worlds[c] : &xnu_W;
+ }
+ u64_t mpidr = cpu_mpidr[0];
logkv("xnu: running on MPIDR Aff1:Aff0", mpidr);
+ logkv("xnu: XNU CPUs", (u64_t)cpus);
adt_init(&a, base_va + off_dt, 0x40000);
adt_node(&a, 3, 6); /* / */
@@ -631,18 +745,24 @@ static struct boot_args_v2 *build_boot(unsigned char *base_va, u64_t phys, u64_t
adt_prop_str(&a, "name", "asmb");
adt_prop_u64(&a, "lp-sip0", 0x2); /* CSR_ALLOW_UNTRUSTED_KEXTS, as DroidVM boots */
adt_prop_u32(&a, "lp-sip1", 1); /* CSR_ALLOW_UNAUTHENTICATED_ROOT */
- adt_node(&a, 1, 1); /* /cpus */
+ adt_node(&a, 1, cpus); /* /cpus */
adt_prop_str(&a, "name", "cpus");
/*
* /cpus/cpu0, without device_type "cpu": that would match Apple's CPU driver (AppleARMCPU, IONameMatch "cpu"),
* which drives the AIC interrupts and IPIs of real hardware. While hosted, the CPU is Linux's.
*/
- adt_node(&a, 5, 0);
- adt_prop_str(&a, "name", "cpu0");
- adt_prop_str(&a, "state", "running");
- adt_prop_u32(&a, "reg", (unsigned)mpidr);
- adt_prop_u64(&a, "timebase-frequency", fki_counter_frequency());
- adt_prop_u32(&a, "cluster-type", 'P'); /* the AMP scheduler wants E/M/P, not SMP */
+ for (int c = 0; c < cpus; c++) { /* compatible: kexts/XnuCPU registers each with XNU and starts it */
+ static char cname[XNU_MAX_CPUS][8];
+ cname[c][0] = 'c'; cname[c][1] = 'p'; cname[c][2] = 'u';
+ if (c < 10) { cname[c][3] = '0' + c; cname[c][4] = 0; } else { cname[c][3] = '1'; cname[c][4] = '0' + c - 10; cname[c][5] = 0; }
+ adt_node(&a, 6, 0);
+ adt_prop_str(&a, "name", cname[c]);
+ adt_prop_str(&a, "compatible", "xnulinux,cpu");
+ adt_prop_str(&a, "state", c ? "waiting" : "running");
+ adt_prop_u32(&a, "reg", (unsigned)cpu_mpidr[c]);
+ adt_prop_u64(&a, "timebase-frequency", fki_counter_frequency());
+ adt_prop_u32(&a, "cluster-type", 'P'); /* the AMP scheduler wants E/M/P, not SMP */
+ }
adt_node(&a, 1, 0); /* /defaults: XNU looks these up without checking */
adt_prop_str(&a, "name", "defaults");
adt_node(&a, 1, 0); /* /product */
@@ -724,7 +844,7 @@ static struct boot_args_v2 *build_boot(unsigned char *base_va, u64_t phys, u64_t
*/
static volatile const unsigned long *xnu_dbg;
static void *monitor;
-static int monitor_cpu = 1;
+static int monitor_cpu = -2; /* -2: the first Linux CPU XNU does not run on; -1: no monitor */
module_param(monitor_cpu, int, 0444);
static char *put_dec(char *p, unsigned long v)
@@ -739,6 +859,10 @@ 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 */
+/* writing 1 asks XNU for a dump of its threads at its next idle (/sys/module/xnu/parameters/dump_threads) */
+static int dump_threads;
+module_param(dump_threads, int, 0644);
+
static int monitor_fn(void *arg)
{
static const struct { int i; const char *name; } dec[] = {
@@ -754,12 +878,17 @@ static int monitor_fn(void *arg)
(void)arg;
while (!fki_thread_should_stop()) {
fki_msleep(2000);
+ if (xnu_dbg && *(volatile int *)&dump_threads) {
+ ((volatile unsigned long *)xnu_dbg)[LINUX64_CTR_DUMP_REQ] = 1;
+ dump_threads = 0;
+ }
if (!xnu_dbg || (lines >= 90 && (++ticks % 10) != 0))
continue;
char buf[420]; char *p = buf;
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);
+ put_str(&p, " moved="); p = put_dec(p, kfault_moved);
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);
@@ -811,10 +940,15 @@ static int enter_arm_init(struct boot_args_v2 *ba)
diag_va[4] = macho_sym(&img, "_port_crumb");
diag_va[5] = macho_sym(&img, "_strlen");
xnu_dbg = (const unsigned long *)macho_sym(&img, "_linux64_dbg");
- if (xnu_dbg && monitor_cpu >= 0)
- monitor = fki_thread_start(monitor_fn, 0, monitor_cpu, "xnu-monitor");
- if (fb_off && fb_dump && fb_dump_ms > 0 && img.region.va)
- fb_thread = fki_thread_start(fb_fn, 0, monitor_cpu >= 0 ? monitor_cpu : 1, "xnu-fb");
+ { /* the helpers run where XNU does not: a CPU running XNU lets Linux in only at XNU's calls into the host */
+ int host_cpu = cpus < fki_num_cpus() ? cpus : fki_num_cpus() - 1;
+ if (monitor_cpu == -2)
+ monitor_cpu = host_cpu;
+ if (xnu_dbg && monitor_cpu >= 0)
+ monitor = fki_thread_start(monitor_fn, 0, monitor_cpu, "xnu-monitor");
+ if (fb_off && fb_dump && fb_dump_ms > 0 && img.region.va)
+ fb_thread = fki_thread_start(fb_fn, 0, monitor_cpu >= 0 ? monitor_cpu : host_cpu, "xnu-fb");
+ }
xnu_kfault = (void *)macho_sym(&img, "_linux64_kernel_fault");
xnu_kfault_recover = (void *)macho_sym(&img, "_linux64_kernel_fault_recover");
if (xnu_kfault && fki_fault_register(0xffffffe000000000ULL, 0xfffffffc00000000ULL, xnu_fault) == 0)
@@ -836,10 +970,29 @@ static int enter_arm_init(struct boot_args_v2 *ba)
xnu_W.xnu_tcr = tcr & ~(1ULL << 22);
xnu_W.xnu_ttbr0 = ttbr0;
}
+ a_cpu_entry = macho_sym(&img, "_linux64_cpu_entry");
+ for (int c = 1; c < cpus; c++) { /* the secondary CPUs' save areas start as the boot CPU's: XNU's keys, user TTBR0/TCR */
+ worlds[c].xnu_keys = xnu_W.xnu_keys;
+ worlds[c].xnu_tcr = xnu_W.xnu_tcr;
+ worlds[c].xnu_ttbr0 = xnu_W.xnu_ttbr0;
+ }
+ if (cpus > 1 && !a_cpu_entry) { logs("xnu: kernel without linux64_cpu_entry: one CPU"); cpus = 1; }
+ for (int c = 1; c < cpus; c++) { /* each secondary CPU's host thread, waiting for XNU to start that CPU */
+ cpu_start_arg[c] = 0;
+ cpu_thread[c] = fki_thread_start(cpu_fn, (void *)(unsigned long)c, c, "xnu-cpu");
+ if (!cpu_thread[c]) { logkv("xnu: cannot make a thread for CPU, running with CPUs below it:", (u64_t)c); cpus = c; }
+ }
logs("xnu: entering arm_init");
in_xnu = 1;
long r = xnu_world_call(a_init, (unsigned long)ba);
in_xnu = 0;
+ stop_run = 1; /* the other CPUs end at their next call into the host (kicked out of idle) */
+ for (int c = 1; c < cpus; c++) {
+ for (int t = 0; cpu_running[c] && t < 500; t++) { fki_kick_cpu(c); fki_msleep(10); }
+ if (cpu_running[c]) logkv("xnu: CPU did not leave XNU in 5 s:", (u64_t)c);
+ fki_thread_stop(cpu_thread[c]);
+ cpu_thread[c] = 0;
+ }
fki_fault_unregister();
logkv("xnu: kernel faults forwarded to XNU", kfaults);
fki_thread_stop(monitor);
diff --git a/xnu-patches/0001-linux64-machine-layer.patch b/xnu-patches/0001-linux64-machine-layer.patch
index c5d2c4e..4e521e7 100644
--- a/xnu-patches/0001-linux64-machine-layer.patch
+++ b/xnu-patches/0001-linux64-machine-layer.patch
@@ -111,7 +111,7 @@ index d46815b..acea296 100644
g_crypto_funcs->random_kmem_init_fn(ctx);
}
diff --git a/osfmk/arm/arm_init.c b/osfmk/arm/arm_init.c
-index ac1713e..3f0cbde 100644
+index ac1713e..8486021 100644
--- a/osfmk/arm/arm_init.c
+++ b/osfmk/arm/arm_init.c
@@ -1,4 +1,5 @@
@@ -120,20 +120,21 @@ index ac1713e..3f0cbde 100644
/*
* Copyright (c) 2007-2024 Apple Inc. All rights reserved.
*
-@@ -228,6 +229,12 @@ extern vm_offset_t segLOWESTKC, segHIGHESTKC, segLOWESTROKC, segHIGHESTROKC;
+@@ -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;
+uintptr_t linux64_slide;
-+unsigned int linux64_vint;
++unsigned int linux64_vint[LINUX64_CPU_SLOTS];
++unsigned int linux64_ipi_pending[LINUX64_CPU_SLOTS];
+unsigned long linux64_dbg[LINUX64_NCOUNTERS];
+
static void
arm_slide_rebase_and_sign_image(void)
{
-@@ -285,10 +292,14 @@ 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;
@@ -149,10 +150,24 @@ index ac1713e..3f0cbde 100644
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 +352,14 @@ arm_auxkc_init(void *mh, void *base)
+@@ -341,6 +353,28 @@ arm_auxkc_init(void *mh, void *base)
#endif /* defined(HAS_APPLE_PAC) */
}
++/*
++ * LINUX64 (xnulinux): where a secondary CPU starts (LINUX64_CALL_CPU_START), on the host's thread for that CPU, in
++ * its own world (the host's page tables, which hold XNU's kernel mappings; XNU's keys). start_cpu's work on hardware
++ * (MMU, vectors, stacks) is the host's; arm_init_cpu sets the thread pointer and goes on into the scheduler.
++ */
++void arm_init_cpu(cpu_data_t *cpu_data_ptr, uint64_t hib_header_phys);
++void linux64_cpu_entry(cpu_data_t *cpu_data_ptr) __attribute__((noreturn));
++void
++linux64_cpu_entry(cpu_data_t *cpu_data_ptr)
++{
++ arm_init_cpu(cpu_data_ptr, 0);
++ __builtin_unreachable();
++}
++
+/* 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)
@@ -206,6 +221,26 @@ index 743117b..753d128 100644
__asm__ volatile (
"msr SPSel, #1 \n"
"mov %0, sp \n"
+diff --git a/osfmk/arm/locks.h b/osfmk/arm/locks.h
+index e5c898f..da72512 100644
+--- a/osfmk/arm/locks.h
++++ b/osfmk/arm/locks.h
+@@ -112,7 +112,14 @@ extern bool has_lock_pv;
+ #define LOCK_SNOOP_SPINS_MCS 10
+ #define LOCK_PRETEST 0
+
+-#define wait_for_event() __builtin_arm_wfe()
++/*
++ * LINUX64 (xnulinux): a CPU waiting here may wait for another that the host holds (it runs Linux for a while); every
++ * ~1 ms of waiting lets the host take this CPU's interrupts, so the two cannot wait on each other forever
++ * (linux64_spin_relax, osfmk/arm/machine_routines_common.c).
++ */
++extern unsigned long linux64_hook;
++extern void linux64_spin_relax(void);
++#define wait_for_event() ({ __builtin_arm_wfe(); if (__improbable(linux64_hook)) linux64_spin_relax(); })
+
+ #ifndef __BUILDING_XNU_LIB_UNITTEST__
+ #if SCHED_HYGIENE_DEBUG
diff --git a/osfmk/arm/machdep_call.c b/osfmk/arm/machdep_call.c
index 7dc0e57..349d015 100644
--- a/osfmk/arm/machdep_call.c
@@ -240,7 +275,7 @@ index 7dc0e57..349d015 100644
}
diff --git a/osfmk/arm/machine_routines_common.c b/osfmk/arm/machine_routines_common.c
-index b65f76c..b1ab2a2 100644
+index b65f76c..eac911b 100644
--- a/osfmk/arm/machine_routines_common.c
+++ b/osfmk/arm/machine_routines_common.c
@@ -27,6 +27,7 @@
@@ -251,7 +286,7 @@ index b65f76c..b1ab2a2 100644
#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)
+@@ -1094,6 +1095,52 @@ ml_set_interrupts_enabled_with_debug(boolean_t enable, boolean_t __unused debug)
thread = current_thread();
@@ -259,37 +294,43 @@ index b65f76c..b1ab2a2 100644
+ /*
+ * 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.
++ * XNU's view in linux64_vint (per CPU); timer "interrupts" are delivered from cpu_idle.
+ */
+ if (linux64_hook) {
-+ boolean_t was = linux64_vint ? TRUE : FALSE;
++ unsigned int slot = linux64_cpu_slot();
++ boolean_t was = linux64_vint[slot] ? 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.
++ * interrupts every 2 ms and deliver XNU's timer if it is due, as the IRQ path does; and take an
++ * IPI another CPU sent.
+ */
-+ static uint64_t linux64_last_kyield;
++ static uint64_t linux64_last_kyield[LINUX64_CPU_SLOTS];
+ 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);
++ cpu_data_t *cdp = thread->machine.CpuDatap;
++ if (cdp->cpu_int_state == NULL) {
++ 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);
++ if (cdp->rtcPop != 0 && cdp->rtcPop != 0xFFFFFFFFFFFFFFFFULL && mach_absolute_time() >= cdp->rtcPop) {
++ cdp->cpu_decrementer = -1;
++ rtclock_intr(FALSE);
++ }
+ }
++ linux64_ipi_take();
+ }
+ if (get_preemption_level() == 0) {
+ while (thread->machine.CpuDatap->cpu_pending_ast & AST_URGENT) {
+ ast_taken_kernel();
+ }
+ }
-+ linux64_vint = 1;
++ /* ast_taken_kernel may have switched this thread out: it can be back on another CPU */
++ linux64_vint[linux64_cpu_slot()] = 1;
+ } else if (!enable) {
-+ linux64_vint = 0;
++ linux64_vint[slot] = 0;
+ }
+ return was;
+ }
@@ -298,7 +339,66 @@ index b65f76c..b1ab2a2 100644
state = __builtin_arm_rsr("DAIF");
if (__improbable(!(state & DAIF_DEBUGF))) {
-@@ -1384,6 +1425,12 @@ ml_wait_max_cpus(void)
+@@ -1366,6 +1413,58 @@ ml_early_cpu_max_number(void)
+ return ml_get_max_cpu_number();
+ }
+
++/*
++ * LINUX64 (xnulinux): inter-processor interrupts while hosted. The sender sets the target's pending slot and asks the
++ * host to make the target look (wake it from its idle call, or interrupt its user code); the target takes it where its
++ * interrupts are enabled again (ml_set_interrupts_enabled), when the host interrupted its user code, and after idle,
++ * as the IPI's FIQ would be taken on hardware: cpu_signal_handler, with interrupts off.
++ */
++/*
++ * LINUX64 (xnulinux): called from spin-waits (wait_for_event, the cross-call wait). The CPU being waited for may be
++ * held by the host: in a call into it (file I/O, idle) or running Linux there. On hardware this CPU would take
++ * interrupts meanwhile; hosted, with interrupts masked here, the host would never get this CPU back, and if the other
++ * CPU's host side waits for this one (an IPI, a lock), neither moves. So every ~1 ms of spinning the host takes this
++ * CPU's interrupts (LINUX64_CALL_PREEMPTED). Nothing of XNU's runs here (no IPI, no AST): the spinning code may hold
++ * per-CPU lock state that a context switch would break.
++ */
++static uint64_t linux64_last_relax[LINUX64_CPU_SLOTS];
++void
++linux64_spin_relax(void)
++{
++ unsigned int slot = linux64_cpu_slot();
++ uint64_t now = mach_absolute_time();
++
++ if (now - linux64_last_relax[slot] < 24000) { /* ~1 ms of the 24 MHz timebase */
++ return;
++ }
++ linux64_last_relax[slot] = now;
++ linux64_call2(LINUX64_CALL_PREEMPTED, 1, 0);
++}
++
++void
++linux64_ipi_take(void)
++{
++ unsigned int slot = linux64_cpu_slot();
++
++ if (os_atomic_load(&linux64_ipi_pending[slot], relaxed) && os_atomic_xchg(&linux64_ipi_pending[slot], 0, acquire)) {
++ cpu_signal_handler();
++ }
++}
++
++void
++linux64_cpu_signal(unsigned int cpu)
++{
++ cpu_data_t *target = CpuDataEntries[cpu].cpu_data_vaddr;
++ uint64_t mpidr;
++
++ if (target == NULL) {
++ return;
++ }
++ mpidr = target->cpu_phys_id;
++ os_atomic_store(&linux64_ipi_pending[LINUX64_CPU_SLOT(mpidr)], 1, release);
++ linux64_call2(LINUX64_CALL_IPI, mpidr, 0);
++}
++
+ void
+ ml_set_max_cpus(unsigned int max_cpus __unused)
+ {
+@@ -1384,6 +1483,12 @@ ml_wait_max_cpus(void)
{
assert(lockdown_done);
lck_mtx_lock(&max_cpus_lock);
@@ -536,7 +636,7 @@ index 84deb3f..2579711 100644
.macro BRANCH_EXTERN
diff --git a/osfmk/arm64/cpu.c b/osfmk/arm64/cpu.c
-index d10d7a1..5124822 100644
+index d10d7a1..0c3e1ed 100644
--- a/osfmk/arm64/cpu.c
+++ b/osfmk/arm64/cpu.c
@@ -32,6 +32,7 @@
@@ -567,7 +667,7 @@ index d10d7a1..5124822 100644
if (unmask) {
/* Latch SW IRQ+FIQ counter prior to unmasking
* interrupts.
-@@ -494,6 +501,39 @@ wfe_to_deadline_or_interrupt(uint32_t cid, uint64_t wfe_deadline, cpu_data_t *cd
+@@ -494,6 +501,37 @@ wfe_to_deadline_or_interrupt(uint32_t cid, uint64_t wfe_deadline, cpu_data_t *cd
return ipending || (nirqc != irqc);
}
@@ -590,16 +690,14 @@ index d10d7a1..5124822 100644
+ /* 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 */
-+ linux64_dump_threads(); /* who is blocked, and where */
++ if (linux64_dbg[LINUX64_CTR_DUMP_REQ] && os_atomic_xchg(&linux64_dbg[LINUX64_CTR_DUMP_REQ], 0, relaxed)) {
++ linux64_dump_threads(); /* the host asked: who is blocked, and where */
+ }
-+#else
+ linux64_count(LINUX64_CTR_HOST_IDLE);
-+#endif
-+ linux64_call2(LINUX64_CALL_IDLE, ns, 0);
++ linux64_call2(LINUX64_CALL_IDLE, ns, (unsigned long)&linux64_ipi_pending[linux64_cpu_slot()]);
+ cpu_data_ptr->cpu_decrementer = -1;
+ rtclock_intr(FALSE);
++ linux64_ipi_take(); /* what woke the host's idle call early, if it was another CPU */
+ ClearIdlePop(TRUE);
+ cpu_idle_exit(FALSE);
+}
@@ -607,7 +705,7 @@ index d10d7a1..5124822 100644
/*
* Routine: cpu_idle
* Function:
-@@ -506,6 +546,9 @@ cpu_idle(void)
+@@ -506,6 +544,9 @@ cpu_idle(void)
uint64_t new_idle_timeout_ticks = 0x0ULL, lastPop;
bool idle_disallowed = false;
@@ -617,6 +715,20 @@ index d10d7a1..5124822 100644
if (__improbable((!idle_enable))) {
idle_disallowed = true;
os_atomic_inc(&virt_idle_disallowed[0], relaxed);
+@@ -1004,7 +1045,12 @@ cpu_start(int cpu)
+ #endif
+ #endif /* CONFIG_SPTM */
+
+- PE_cpu_start_internal(cpu_data_ptr->cpu_id, (vm_offset_t)NULL, (vm_offset_t)NULL);
++ if (linux64_hook) {
++ /* LINUX64 (xnulinux): the host starts the CPU, on a Linux CPU of that MPIDR, at linux64_cpu_entry */
++ linux64_call2(LINUX64_CALL_CPU_START, cpu_data_ptr->cpu_phys_id, (unsigned long)cpu_data_ptr);
++ } else {
++ PE_cpu_start_internal(cpu_data_ptr->cpu_id, (vm_offset_t)NULL, (vm_offset_t)NULL);
++ }
+
+ }
+ }
diff --git a/osfmk/arm64/cswitch.s b/osfmk/arm64/cswitch.s
index a191eb3..035b1a8 100644
--- a/osfmk/arm64/cswitch.s
@@ -1209,7 +1321,7 @@ index 13d2819..1837c6a 100644
mrs x1, MPIDR_EL1
diff --git a/osfmk/arm64/machine_routines.c b/osfmk/arm64/machine_routines.c
-index f456377..8d66fb7 100644
+index f456377..b66afca 100644
--- a/osfmk/arm64/machine_routines.c
+++ b/osfmk/arm64/machine_routines.c
@@ -27,6 +27,7 @@
@@ -1235,7 +1347,7 @@ index f456377..8d66fb7 100644
+ {
+ /* LINUX64 (xnulinux): hosted, hardware IRQs stay masked; only the virtual flag changes. */
+ if (linux64_hook) {
-+ linux64_vint = 1;
++ LINUX64_VINT = 1;
+ return;
+ }
+ }
@@ -1249,7 +1361,7 @@ index f456377..8d66fb7 100644
+ {
+ /* LINUX64: interrupts are virtual while hosted (see ml_set_interrupts_enabled_with_debug). */
+ if (linux64_hook) {
-+ return linux64_vint ? TRUE : FALSE;
++ return LINUX64_VINT ? TRUE : FALSE;
+ }
+ }
MRS(value, "DAIF");
@@ -1326,7 +1438,7 @@ index d211433..cb48971 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..9e0422b 100644
+index d8f1b19..3fac7b4 100644
--- a/osfmk/arm64/sleh.c
+++ b/osfmk/arm64/sleh.c
@@ -1,4 +1,5 @@
@@ -1343,7 +1455,7 @@ index d8f1b19..9e0422b 100644
#endif
#include <prng/entropy.h>
-@@ -3646,3 +3648,210 @@ sleh_panic_lockdown_should_initiate_el1_sp0_sync(uint64_t esr, uint64_t elr,
+@@ -3646,3 +3648,215 @@ sleh_panic_lockdown_should_initiate_el1_sp0_sync(uint64_t esr, uint64_t elr,
}
__SECURITY_STACK_DISALLOWED_POP
#endif /* CONFIG_SPTM */
@@ -1528,6 +1640,11 @@ index d8f1b19..9e0422b 100644
+ rtclock_intr(TRUE);
+ cdp->cpu_int_state = NULL;
+ }
++ if (os_atomic_load(&linux64_ipi_pending[linux64_cpu_slot()], relaxed)) { /* another CPU's IPI, as sleh_fiq takes it */
++ cdp->cpu_int_state = ss;
++ linux64_ipi_take();
++ cdp->cpu_int_state = NULL;
++ }
+ thread_exception_return();
+ }
+ if (ESR_EC(f->esr) == ESR_EC_SVC_64 && linux64_tracing()) {
@@ -1872,7 +1989,7 @@ index 2fc6931..d581670 100644
struct console_printbuf_state info_data;
diff --git a/osfmk/kern/sched_prim.c b/osfmk/kern/sched_prim.c
-index b2aae03..3e83e72 100644
+index b2aae03..af01ff3 100644
--- a/osfmk/kern/sched_prim.c
+++ b/osfmk/kern/sched_prim.c
@@ -65,6 +65,7 @@
@@ -1899,15 +2016,15 @@ index b2aae03..3e83e72 100644
/*
* 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,
+@@ -9984,3 +9987,45 @@ 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.
++ * LINUX64 (xnulinux) diagnostics: print every thread's state, wait event, continuation and a few saved frames, when the
++ * host asks (LINUX64_CTR_DUMP_REQ). Called from the hosted idle path with interrupts off; the list is walked without its
++ * lock (another CPU may change it meanwhile: a diagnostic, not a consistent snapshot).
+ */
+void
+linux64_dump_threads(void)
@@ -1945,7 +2062,6 @@ index b2aae03..3e83e72 100644
+ }
+ }
+}
-+#endif /* LINUX64_DEBUG */
diff --git a/osfmk/kern/stack.c b/osfmk/kern/stack.c
index 1111ccf..9bc5118 100644
--- a/osfmk/kern/stack.c
diff --git a/xnu-patches/include/linux64.h b/xnu-patches/include/linux64.h
index 6b4a078..f9b66fd 100644
--- a/xnu-patches/include/linux64.h
+++ b/xnu-patches/include/linux64.h
@@ -34,8 +34,21 @@ extern "C" {
*/
extern unsigned long linux64_hook;
extern unsigned long linux64_slide;
-/* XNU's interrupt-enable state: hardware interrupts stay masked while XNU runs; this flag is the virtual one */
-extern unsigned int linux64_vint;
+/* This CPU's slot in the per-CPU arrays (LINUX64_CPU_SLOT of its MPIDR): valid before XNU knows its cpu number */
+static inline unsigned
+linux64_cpu_slot(void)
+{
+ unsigned long mpidr;
+
+ __asm__ volatile ("mrs %0, MPIDR_EL1" : "=r"(mpidr));
+ return LINUX64_CPU_SLOT(mpidr);
+}
+
+/* Each CPU's interrupt-enable state: hardware interrupts stay masked while XNU runs; this flag is the virtual one */
+extern unsigned int linux64_vint[LINUX64_CPU_SLOTS];
+#define LINUX64_VINT linux64_vint[linux64_cpu_slot()]
+/* Each CPU's pending inter-processor interrupt (set by the sender, taken where XNU's interrupts are enabled again) */
+extern unsigned int linux64_ipi_pending[LINUX64_CPU_SLOTS];
/* enum linux64_counter */
extern unsigned long linux64_dbg[LINUX64_NCOUNTERS];
@@ -95,12 +108,18 @@ linux64_count(enum linux64_counter c)
/* osfmk/arm/arm_init.c */
void linux64_assert_report(const char *file, int line, const char *expr);
+/* osfmk/arm/machine_routines_common.c: IPIs. With XNU's interrupts off: take this CPU's pending IPI, if any */
+void linux64_ipi_take(void);
+/* signal a CPU (kexts/XnuCPU's IOCPU::signalCPU): its logical number */
+void linux64_cpu_signal(unsigned int cpu);
/* 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) */
+/* osfmk/arm/machine_routines_common.c: in a spin-wait, let the host take this CPU now and then (see arm/locks.h) */
+void linux64_spin_relax(void);
+/* osfmk/kern/sched_prim.c: every thread's state and saved frames to the host log (on the host's request) */
void linux64_dump_threads(void);
#ifdef __cplusplus
diff --git a/xnu-patches/include/linux64_abi.h b/xnu-patches/include/linux64_abi.h
index 73e966d..41eaf45 100644
--- a/xnu-patches/include/linux64_abi.h
+++ b/xnu-patches/include/linux64_abi.h
@@ -22,11 +22,12 @@
#ifndef _LINUX64_ABI_H_
#define _LINUX64_ABI_H_
-#define LINUX64_ABI_VERSION 2
+#define LINUX64_ABI_VERSION 3
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 = nanoseconds to XNU's next timer (0: one is due); the host runs Linux meanwhile */
+ LINUX64_CALL_IDLE = 810, /* a1 = nanoseconds to XNU's next timer (0: one is due), a2 = this CPU's pending-IPI word
+ * (the host does not sleep while it is set); 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 */
@@ -37,6 +38,8 @@ enum linux64_call {
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_CPU_START = 840, /* a1 = a CPU's MPIDR, a2 = its cpu_data_t: the host enters linux64_cpu_entry(a2) there */
+ LINUX64_CALL_IPI = 841, /* a1 = the target CPU's MPIDR: its linux64_ipi_pending slot is set; make it look */
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 */
@@ -85,6 +88,13 @@ struct linux64_input_event {
int value;
};
+/*
+ * Per-CPU state shared by XNU and the host lives in arrays indexed by a CPU's slot: affinity 0 and affinity 1 of its
+ * MPIDR, four bits each. The host only starts CPUs whose slots differ.
+ */
+#define LINUX64_CPU_SLOTS 256
+#define LINUX64_CPU_SLOT(mpidr) ((unsigned)(((mpidr) & 0xf) | (((mpidr) >> 4) & 0xf0)))
+
enum linux64_counter {
LINUX64_CTR_IDLE_THREAD = 0, /* XNU's idle thread loops */
LINUX64_CTR_MACHINE_IDLE = 1, /* machine_idle calls */
@@ -99,6 +109,7 @@ enum linux64_counter {
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_CTR_DUMP_REQ = 15, /* host to XNU: nonzero asks for a thread dump (linux64_dump_threads) at the next idle */
LINUX64_NCOUNTERS = 16,
};