Apple's open-source XNU kernel on Android phones: its own loader and drivers, Metal on the Adreno. Runs from RAM; a reboot gives the phone back to Android.
C
SMP: the kernel side (exported), prebuilt binaries
vcvkk20b1625f8e0c
diff --git a/prebuilt/SHA256SUMS b/prebuilt/SHA256SUMSindex 0a0d5de..b3f55af 100644--- a/prebuilt/SHA256SUMS+++ b/prebuilt/SHA256SUMS@@ -1,12 +1,13 @@-Built 2026-10-12 16:38 from this tree.+Built 2026-10-12 17:14 from this tree.-fd38c8f5dc3224489d2efed0646c5e97805e303d04c92be5985923568c64d389 prebuilt/mach.development.bcm2837-4a875f2943b3c2ead63ee9e4c6141251c1a62c24639954114651e37157f4dab8 prebuilt/loader.efi+8beb0ca4e478227e66bc2277856179a764b30720955cda7d8d5ba7f57777fced prebuilt/mach.development.bcm2837+3fe61d8611217b8ae578f2bea50f7cb796a946d920a8c394805a46d1dda24318 prebuilt/loader.efid2a35a4a1d6658ffb3696914f727661b52c9333de8a3af8a31642b8023ce03ac prebuilt/userland/child+1a413befd511384052e1962c1394adce20f718e1f2657ce63ab09828ebc4bd1b prebuilt/userland/cpu_testdb564073effc31e7ab1679a7ffe0631ec22c3030ad347c927028f3e53c8583c3 prebuilt/userland/helloa8baa9ab38333280369b0824aafaf92c7aa6a85851ff0b2551a4c711dbe59cfd prebuilt/userland/hello_dyn9d951ac5274c2f0868b5eeeb7589616301f3d8893a592ad49c3f4a5001230def prebuilt/userland/init-8bee98ddfe1c3e1176b4a9554abc744d175b953ee3130223b596637618605df9 prebuilt/userland/libredwood.dylib+0e745603f8e5e65867631133efe54311670d09b58ff04ceed86c7a94040303e1 prebuilt/userland/libredwood.dylib8a3eb47519e80f6edb97580e8f7a9d9aafc25e88374dd00bf07cfde66acadce2 prebuilt/userland/libredwood-sb.dylibb540c061fc5909e9c640cccf4f6f84fd15b58337caa4f95a3610aa694d198346 prebuilt/userland/mg_teste9dd4a78e3f61d5001fd4745cbc3dd6d498850a4140b3e90eeb8592e9dccf349 prebuilt/userland/rwtouchdiff --git a/prebuilt/loader.efi b/prebuilt/loader.efiindex 1789028..8c69a09 100755Binary files a/prebuilt/loader.efi and b/prebuilt/loader.efi differdiff --git a/prebuilt/mach.development.bcm2837 b/prebuilt/mach.development.bcm2837index 6c024ce..00bc7dd 100755Binary files a/prebuilt/mach.development.bcm2837 and b/prebuilt/mach.development.bcm2837 differdiff --git a/prebuilt/userland/cpu_test b/prebuilt/userland/cpu_testnew file mode 100755index 0000000..d478cb4Binary files /dev/null and b/prebuilt/userland/cpu_test differdiff --git a/prebuilt/userland/libredwood.dylib b/prebuilt/userland/libredwood.dylibindex 1c1249f..51c47d0 100755Binary files a/prebuilt/userland/libredwood.dylib and b/prebuilt/userland/libredwood.dylib differdiff --git a/xnu/files/bsd/dev/redwood_cpufreq.c b/xnu/files/bsd/dev/redwood_cpufreq.cindex 494c427..9d345de 100644--- a/xnu/files/bsd/dev/redwood_cpufreq.c+++ b/xnu/files/bsd/dev/redwood_cpufreq.c@@ -1,18 +1,20 @@/*- * The clock speed of the processor core the kernel runs on, on the POCO X5 Pro (redwood).+ * The clock speed of the processor cores the kernel runs on, on the POCO X5 Pro (redwood).* Only with boot-arg cpufreq=1: the addresses are this phone's.** The boot loader leaves each group of cores at a modest frequency and expects the operating* system to ask for more. On this SoC that is one register write: the hardware ("EPSS") has* a table of frequencies per group and switches the clock source and the supply voltage by* itself when told which row is wanted. There is no reason for us ever to want less than the- * top row: one core is all the kernel uses.+ * top row, for every group that has a core of ours in it (one core, unless boot-arg cpus=N+ * says more).** Register layout: Linux drivers/cpufreq/qcom-cpufreq-hw.c ("epss" variant).*/#include <kern/clock.h>#include <libkern/libkern.h>#include <mach/mach_types.h>+#include <machine/machine_routines.h>#include <pexpert/pexpert.h>#include <sys/redwood_input.h>#include <sys/systm.h>@@ -21,6 +23,7 @@ extern vm_offset_t ml_io_map(vm_offset_t phys_addr, vm_size_t size);#define EPSS_PHYS 0x18591000UL /* three groups ("domains") of 0x1000: small cores, big, biggest */#define EPSS_DOMAIN_SIZE 0x1000UL+#define EPSS_DOMAINS 3#define EPSS_FREQ_TABLE 0x100 /* a word per row: [31:30] clock source, [7:0] multiple of 19.2 MHz */#define EPSS_TABLE_ROWS 40#define EPSS_PERF_STATE 0x320 /* the row that is wanted */@@ -41,17 +44,21 @@ loop_speed(void)return nanos ? (uint32_t)(2000000ULL * 1000 / nanos) : 0;}-void-redwood_cpufreq_init(void)+/* The group of the core with that number in its MPIDR (the device tree's "reg": the number is the second field). */+static uint32_t+domain_of(uint32_t phys_id){- uint64_t mpidr = __builtin_arm_rsr64("MPIDR_EL1");- uint32_t core = (uint32_t)(mpidr >> 8) & 0xff, domain = core < 4 ? 0 : core < 7 ? 1 : 2;- uint32_t enabled = 0, top = 0, top_khz = 0, before = loop_speed(), was;+ uint32_t core = (phys_id >> 8) & 0xff;++ return core < 4 ? 0 : core < 7 ? 1 : 2;+}++static void+raise_domain(uint32_t domain, uint32_t cores)+{+ uint32_t top = 0, top_khz = 0, was;vm_offset_t base;- if (!PE_parse_boot_argn("cpufreq", &enabled, sizeof(enabled)) || !enabled) {- return;- }base = ml_io_map(EPSS_PHYS + domain * EPSS_DOMAIN_SIZE, EPSS_DOMAIN_SIZE);for (uint32_t row = 0; row < EPSS_TABLE_ROWS; row++) {uint32_t entry = *(volatile uint32_t *)(base + EPSS_FREQ_TABLE + 4 * row);@@ -66,6 +73,29 @@ redwood_cpufreq_init(void)was = *(volatile uint32_t *)(base + EPSS_PERF_STATE);*(volatile uint32_t *)(base + EPSS_PERF_STATE) = top;delay_for_interval(20, NSEC_PER_MSEC);- printf("cpufreq: core %u (group %u): row %u -> %u of the frequency table, %u MHz; a loop ran at %u, now at %u\n", core,- domain, was, top, top_khz / 1000, before, loop_speed());+ printf("cpufreq: group %u (%u of our cores): row %u -> %u of the frequency table, %u MHz\n", domain, cores, was, top,+ top_khz / 1000);+}++void+redwood_cpufreq_init(void)+{+ const ml_topology_info_t *topology = ml_get_topology_info();+ uint32_t enabled = 0, cores[EPSS_DOMAINS] = { 0 }, before, here;++ if (!PE_parse_boot_argn("cpufreq", &enabled, sizeof(enabled)) || !enabled) {+ return;+ }+ for (unsigned int i = 0; i < topology->num_cpus; i++) {+ cores[domain_of(topology->cpus[i].phys_id)]++;+ }+ /* (whichever core this thread happens to be on, and stays on or not: it only goes to the log) */+ here = (uint32_t)(__builtin_arm_rsr64("MPIDR_EL1") >> 8) & 0xff;+ before = loop_speed();+ for (uint32_t domain = 0; domain < EPSS_DOMAINS; domain++) {+ if (cores[domain] != 0) {+ raise_domain(domain, cores[domain]);+ }+ }+ printf("cpufreq: on core %u a loop ran at %u, now at %u\n", here, before, loop_speed());}diff --git a/xnu/files/iokit/Kernel/GenericARMPE.cpp b/xnu/files/iokit/Kernel/GenericARMPE.cppindex a4e7082..0f3e578 100644--- a/xnu/files/iokit/Kernel/GenericARMPE.cpp+++ b/xnu/files/iokit/Kernel/GenericARMPE.cpp@@ -9,6 +9,7 @@*/extern "C" {#include <pexpert/pexpert.h>+#include <pexpert/arm64/board_config.h>#include <kern/cpu_number.h>}#include <machine/machine_routines.h>@@ -20,7 +21,18 @@ extern "C" {#include "MiniDrivers.h"-extern "C" kern_return_t processor_start(processor_t processor);+extern "C" {+kern_return_t processor_start(processor_t processor);+kern_return_t processor_exit(processor_t processor);+extern uint32_t processor_avail_count;++/* osfmk/arm64/psci_smp.c and gic_v3_irq.c */+void psci_smp_init(void);+kern_return_t psci_smp_start_cpu(int cpu);+void psci_smp_cpu_running(void);+void psci_smp_cpu_off(void) __dead2;+void gic_v3_irq_signal(uint32_t phys_id);+}/** GenericARMCPU: registers a device-tree CPU node with the kernel. The closed@@ -28,85 +40,133 @@ extern "C" kern_return_t processor_start(processor_t processor);* forever for the CPU count (ml_wait_max_cpus) and never calls* cpu_machine_init() on the boot processor.*- * Only the boot CPU is brought up for now. Secondary CPUs need a start- * method (PSCI CPU_ON) and inter-processor interrupts through the GIC.+ * The other processors are started through the firmware (PSCI CPU_ON, see+ * osfmk/arm64/psci_smp.c) and signalled with interrupts of the GIC+ * (osfmk/arm64/gic_v3_irq.c). How many there are is the device tree's and the+ * boot-arg cpus=N's to say (ml_parse_cpu_topology()); with one, nothing of+ * that is used.*/class GenericARMCPU : public IOCPU{OSDeclareDefaultStructors(GenericARMCPU);+ uint32_t physID; /* the device tree's "reg": the low affinity fields of the core's MPIDR */+public:virtual bool start(IOService * provider) APPLE_KEXT_OVERRIDE;virtual void initCPU(bool boot) APPLE_KEXT_OVERRIDE;virtual void quiesceCPU(void) APPLE_KEXT_OVERRIDE;virtual kern_return_t startCPU(vm_offset_t start_paddr, vm_offset_t arg_paddr) APPLE_KEXT_OVERRIDE;virtual void haltCPU(void) APPLE_KEXT_OVERRIDE;+ virtual void signalCPU(IOCPU * target) APPLE_KEXT_OVERRIDE;virtual const OSSymbol * getCPUName(void) APPLE_KEXT_OVERRIDE;++ static int cpuNumberOfNub(IOService * nub);+ void run(void);};OSDefineMetaClassAndStructors(GenericARMCPU, IOCPU);+/* The kernel's number for the processor of a /cpus node, -1 if it is not to be used (boot-arg cpus=N). */+int+GenericARMCPU::cpuNumberOfNub(IOService * nub)+{+ OSData * reg = OSDynamicCast(OSData, nub->getProperty("reg"));++ if (nub->getProperty("state") == NULL || reg == NULL || reg->getLength() < sizeof(uint32_t)) {+ return -1;+ }+ return ml_get_cpu_number(*(const uint32_t *)reg->getBytesNoCopy());+}++/* Registers the processor; run() starts it. */boolGenericARMCPU::start(IOService * provider){ml_processor_info_t info;perfmon_interrupt_handler_func pmi_handler = NULL;- uint32_t phys_id = 0;+ int cpu = cpuNumberOfNub(provider);- if (!IOCPU::start(provider)) {+ if (cpu < 0 || !IOCPU::start(provider)) {return false;}+ const ml_topology_cpu_t * topology = &ml_get_topology_info()->cpus[cpu];- OSData * reg = OSDynamicCast(OSData, provider->getProperty("reg"));- if (reg != NULL && reg->getLength() >= sizeof(uint32_t)) {- phys_id = *(const uint32_t *)reg->getBytesNoCopy();- }-- setCPUNumber((UInt32)ml_get_boot_cpu_number());+ physID = topology->phys_id;+ setCPUNumber((UInt32)cpu);bzero(&info, sizeof(info));info.cpu_id = (cpu_id_t)this;info.log_id = getCPUNumber();- info.phys_id = phys_id;- info.cluster_type = CLUSTER_TYPE_SMP;+ info.phys_id = physID;+ info.cluster_id = topology->cluster_id;+ info.cluster_type = topology->cluster_type;if (ml_processor_register(&info, &machProcessor, &ipi_handler, &pmi_handler) != KERN_SUCCESS) {IOLog("GenericARMCPU: ml_processor_register failed\n");return false;}- /* Unblocks everything that waits for the CPU count to be known. */- ml_set_max_cpus(1);-setCPUState(kIOCPUStateUninitalized);registerService();+ IOLog("GenericARMCPU: cpu %u (phys id 0x%x) registered\n", (unsigned)getCPUNumber(), physID);+ return true;+}- /* Runs cpu_machine_init() -> initCPU(true) on this (the boot) processor. */+/*+ * The boot processor: runs cpu_machine_init() -> initCPU(true) on it, right here.+ * Any other: cpu_start() -> startCPU(), and the new core comes to initCPU() by itself.+ */+void+GenericARMCPU::run(void)+{processor_start(machProcessor);- IOLog("GenericARMCPU: cpu %u (phys id 0x%x) registered\n", (unsigned)getCPUNumber(), phys_id);- return true;}+/* On the processor itself, with its interrupts off, when it joins (or rejoins) the scheduler. */voidGenericARMCPU::initCPU(bool boot){- /* The interrupt controller and timer were set up in arm_init (pe_init_fiq). */+ /* The interrupt controller and timer were set up in arm_init / arm_init_cpu (pe_init_fiq). */setCPUState(kIOCPUStateRunning);+ if (ml_get_cpu_count() > 1) {+ psci_smp_cpu_running();+ /*+ * A processor takes no signals until it has handled an interrupt for one+ * (cpu_signal_handler() lifts SIGPdisabled), and until then it does not go to+ * sleep when idle either: send it its first.+ */+ gic_v3_irq_signal(physID);+ }}+/* On the processor itself, at the end of processor_exit(): it is to stop for good. */voidGenericARMCPU::quiesceCPU(void){+ if (getCPUNumber() != (UInt32)master_cpu) {+ setCPUState(kIOCPUStateStopped);+ psci_smp_cpu_off();+ }}kern_return_tGenericARMCPU::startCPU(vm_offset_t start_paddr, vm_offset_t arg_paddr){- return KERN_NOT_SUPPORTED;+ return psci_smp_start_cpu((int)getCPUNumber());}voidGenericARMCPU::haltCPU(void){+ if (getCPUNumber() != (UInt32)master_cpu) {+ processor_exit(machProcessor);+ }+}++void+GenericARMCPU::signalCPU(IOCPU * target)+{+ gic_v3_irq_signal(((GenericARMCPU *)target)->physID);}const OSSymbol *@@ -157,24 +217,30 @@ GenericARMPE::start(IOService * provider)IOLog("GenericARMPE: platform \"%s\"\n", provider->getName());/*- * super::start() published the /cpus children as nubs. Attach a CPU- * driver to the boot processor's nub (device-tree state "running").+ * super::start() published the /cpus children as nubs. Attach a CPU driver to each+ * one the kernel has a number for, register them all -- that settles the CPU count --+ * and then start them, the boot processor (number master_cpu) first.*/+ GenericARMCPU * cpus[MAX_CPUS] = {};+ unsigned int count = 0;OSIterator * iter = getChildIterator(gIOServicePlane);if (iter != NULL) {OSObject * obj;while ((obj = iter->getNextObject()) != NULL) {IOService * nub = OSDynamicCast(IOService, obj);- OSData * state = nub ? OSDynamicCast(OSData, nub->getProperty("state")) : NULL;+ int number = nub ? GenericARMCPU::cpuNumberOfNub(nub) : -1;- if (state == NULL || strncmp((const char *)state->getBytesNoCopy(), "running", state->getLength()) != 0) {+ if (number < 0 || number >= MAX_CPUS || cpus[number] != NULL) {continue;}GenericARMCPU * cpu = new GenericARMCPU;if (cpu != NULL && cpu->init() && cpu->attach(nub)) {- if (!cpu->start(nub)) {- cpu->detach(nub);+ if (cpu->start(nub)) {+ cpus[number] = cpu; /* kept: the kernel has its address as the cpu's id */+ count++;+ continue;}+ cpu->detach(nub);}if (cpu != NULL) {cpu->release();@@ -182,6 +248,22 @@ GenericARMPE::start(IOService * provider)}iter->release();}+ if (cpus[master_cpu] != NULL) {+ /* Unblocks everything that waits for the CPU count to be known. */+ ml_set_max_cpus(count);+ if (count > 1) {+ psci_smp_init();+ }+ cpus[master_cpu]->run();+ for (unsigned int number = 0; number < MAX_CPUS; number++) {+ if (cpus[number] != NULL && number != (unsigned int)master_cpu) {+ cpus[number]->run();+ }+ }+ if (count > 1) {+ IOLog("GenericARMPE: %u of %u processors are running\n", processor_avail_count, count);+ }+ }/* BSD looks the platform expert up by class (IOSecureBSDRoot). */registerService();diff --git a/xnu/files/osfmk/arm64/gic_v3_irq.c b/xnu/files/osfmk/arm64/gic_v3_irq.cindex d56a7dd..31a0925 100644--- a/xnu/files/osfmk/arm64/gic_v3_irq.c+++ b/xnu/files/osfmk/arm64/gic_v3_irq.c@@ -8,17 +8,26 @@** - the CPU interface is driven through the ICC_*_EL1 system registers* - the EL1 virtual timer PPI is routed to the kernel's rtclock+ * - with more than one processor (psci_smp.c), two software-generated+ * interrupts carry the kernel's signals between them: cpu_signal() and+ * the order to stop when the system goes back to the boot loader* - any other interrupt that fires is masked and counted, until a real* driver registers a handler for it*+ * Every processor has its own CPU interface, redistributor frame and timer,+ * and sets them up for itself (gic_v3_irq_cpu_init(), from PE_init_cpu()).+ ** Registers come from the device tree node /arm-io/gic:* reg = <distributor offset, size, redistributor offset, size>*/#include <mach/mach_types.h>#include <kern/debug.h>#include <arm/cpu_data_internal.h>+#include <arm/cpu_internal.h>+#include <arm/machine_cpu.h>#include <arm/machine_routines.h>#include <arm/rtclock.h>+#include <arm64/psci_smp.h>#include <arm64/proc_reg.h>#include <pexpert/pexpert.h>#include <pexpert/device_tree.h>@@ -42,23 +51,28 @@#define GICR_IGROUPR0 (GICR_SGI_BASE + 0x0080)#define GICR_ISENABLER0 (GICR_SGI_BASE + 0x0100)#define GICR_ICENABLER0 (GICR_SGI_BASE + 0x0180)+#define GICR_ICACTIVER0 (GICR_SGI_BASE + 0x0380)#define GICR_IPRIORITYR(n) (GICR_SGI_BASE + 0x0400 + (n))#define GICR_IGRPMODR0 (GICR_SGI_BASE + 0x0d00)+#define GIC_SGI_SIGNAL 0 /* cpu_signal(): another processor wants this one's attention */+#define GIC_SGI_STOP 1 /* psci_smp_stop_here(): the system is going back to the boot loader */#define GIC_INTID_VTIMER 27 /* EL1 virtual timer PPI */#define GIC_INTID_SPURIOUS_MIN 1020#define GIC_PRIORITY_DEFAULT 0xa0static vm_offset_t gicd_base, gicr_base;static vm_size_t gicr_size;-static vm_offset_t gicr_cpu_base; /* boot CPU's redistributor frame */+static vm_offset_t gicr_cpu_base[MAX_CPUS]; /* each processor's redistributor frame */-static uint64_t gic_active_iar; /* acknowledged, not yet EOI'd */+static uint64_t gic_active_iar[MAX_CPUS]; /* acknowledged, not yet EOI'd */uint64_t gic_unhandled_count;uint32_t gic_last_unhandled;void gic_v3_irq_cpu_init(void);void gic_v3_irq_quiesce(void);+void gic_v3_irq_signal(uint32_t phys_id);+void gic_v3_irq_signal_stop(uint32_t phys_id);static inline uint32_tgic_read32(vm_offset_t addr)@@ -76,15 +90,45 @@ static voidgic_mask(uint32_t intid){if (intid < 32) {- gic_write32(gicr_cpu_base + GICR_ICENABLER0, 1u << intid);+ gic_write32(gicr_cpu_base[cpu_number()] + GICR_ICENABLER0, 1u << intid);} else {gic_write32(gicd_base + GICD_ICENABLER(intid / 32), 1u << (intid % 32));}}+/*+ * A software-generated interrupt for the processor with that MPIDR (its two+ * low affinity fields, as in the device tree's "reg").+ * ICC_SGI1R_EL1: Aff1 in [23:16], the interrupt in [27:24], and in [15:0] a+ * bit for every Aff0 addressed -- which is why Aff0 has to be below 16.+ */+static void+gic_send_sgi(uint32_t phys_id, uint32_t sgi)+{+ uint64_t aff0 = phys_id & 0xff, aff1 = (phys_id >> 8) & 0xff;++ __builtin_arm_wsr64("ICC_SGI1R_EL1", ((uint64_t)sgi << 24) | (aff1 << 16) | (1ULL << (aff0 & 15)));+ __builtin_arm_isb(ISB_SY);+}++/* The platform's half of cpu_signal(): interrupt that processor (GenericARMCPU::signalCPU()). */+void+gic_v3_irq_signal(uint32_t phys_id)+{+ gic_send_sgi(phys_id, GIC_SGI_SIGNAL);+}++void+gic_v3_irq_signal_stop(uint32_t phys_id)+{+ gic_send_sgi(phys_id, GIC_SGI_STOP);+}+static voidgic_irq_handler(__unused void *target, __unused void *refCon, __unused void *nub, __unused int source){+ int cpu = cpu_number();+for (;;) {uint64_t iar = __builtin_arm_rsr64("ICC_IAR1_EL1");uint32_t intid = (uint32_t)(iar & 0xffffff);@@ -92,12 +136,17 @@ gic_irq_handler(__unused void *target, __unused void *refCon, __unused void *nubif (intid >= GIC_INTID_SPURIOUS_MIN) {break;}- gic_active_iar = iar;+ gic_active_iar[cpu] = iar;if (intid == GIC_INTID_VTIMER) {/* same sequence as the FIQ path in sleh_fiq() */getCpuDatap()->cpu_decrementer = -1; /* Large */rtclock_intr(TRUE);+ } else if (intid == GIC_SGI_SIGNAL) {+ cpu_signal_handler();+ } else if (intid == GIC_SGI_STOP) {+ /* comes back only if nobody has in fact asked for that */+ psci_smp_stop_here();} else {/* nobody owns this interrupt yet: keep it from storming */gic_mask(intid);@@ -107,22 +156,29 @@ gic_irq_handler(__unused void *target, __unused void *refCon, __unused void *nub__builtin_arm_wsr64("ICC_EOIR1_EL1", iar);__builtin_arm_isb(ISB_SY);- gic_active_iar = 0;+ gic_active_iar[cpu] = 0;}}/** Leave the controller in a state another environment can take over from:- * finish any interrupt that was acknowledged but not completed. Used when- * control goes back to the boot loader (see loader_return.c).+ * finish any interrupt that this processor acknowledged but did not complete.+ * Used when control goes back to the boot loader (see loader_return.c), and+ * by a processor that is about to be switched off for that (psci_smp.c).*/voidgic_v3_irq_quiesce(void){- if (gic_active_iar != 0) {- __builtin_arm_wsr64("ICC_EOIR1_EL1", gic_active_iar);+ int cpu;++ if (gicd_base == 0) {+ return; /* as early as this there is no interrupt, nor a cpu number to ask for */+ }+ cpu = cpu_number();+ if (gic_active_iar[cpu] != 0) {+ __builtin_arm_wsr64("ICC_EOIR1_EL1", gic_active_iar[cpu]);__builtin_arm_isb(ISB_SY);- gic_active_iar = 0;+ gic_active_iar[cpu] = 0;}}@@ -146,10 +202,14 @@ gic_find_redistributor(void)panic("gic: no redistributor for MPIDR 0x%llx", mpidr);}-/* Per-CPU bring-up; only the boot CPU is supported for now. */+/* Per-CPU bring-up: every processor calls this for itself, the boot processor first. */voidgic_v3_irq_cpu_init(void){+ int cpu = cpu_number();+ vm_offset_t gicr;+ uint32_t mine = 1u << GIC_INTID_VTIMER;+if (gicd_base == 0) {DTEntry entry;void const *prop;@@ -169,7 +229,7 @@ gic_v3_irq_cpu_init(void)if (gicd_base == 0 || gicr_base == 0) {panic("gic: cannot map the distributor/redistributor");}- } else if (gicr_cpu_base != 0) {+ } else if (gicr_cpu_base[cpu] != 0) {return;}@@ -177,21 +237,35 @@ gic_v3_irq_cpu_init(void)__builtin_arm_wsr64("ICC_SRE_EL1", __builtin_arm_rsr64("ICC_SRE_EL1") | 1);__builtin_arm_isb(ISB_SY);- gicr_cpu_base = gic_find_redistributor();+ gicr = gicr_cpu_base[cpu] = gic_find_redistributor();- uint32_t waker = gic_read32(gicr_cpu_base + GICR_WAKER);+ uint32_t waker = gic_read32(gicr + GICR_WAKER);if (waker & (GICR_WAKER_PROCSLEEP | GICR_WAKER_CHILDASLEEP)) {- gic_write32(gicr_cpu_base + GICR_WAKER, waker & ~GICR_WAKER_PROCSLEEP);- while (gic_read32(gicr_cpu_base + GICR_WAKER) & GICR_WAKER_CHILDASLEEP) {+ gic_write32(gicr + GICR_WAKER, waker & ~GICR_WAKER_PROCSLEEP);+ while (gic_read32(gicr + GICR_WAKER) & GICR_WAKER_CHILDASLEEP) {/* spin until the redistributor is awake */}}- /* Virtual timer PPI: Group 1 (IRQ), default priority, enabled */- gic_write32(gicr_cpu_base + GICR_IGROUPR0, gic_read32(gicr_cpu_base + GICR_IGROUPR0) | (1u << GIC_INTID_VTIMER));- gic_write32(gicr_cpu_base + GICR_IGRPMODR0, gic_read32(gicr_cpu_base + GICR_IGRPMODR0) & ~(1u << GIC_INTID_VTIMER));- *(volatile uint8_t *)(gicr_cpu_base + GICR_IPRIORITYR(GIC_INTID_VTIMER)) = GIC_PRIORITY_DEFAULT;- gic_write32(gicr_cpu_base + GICR_ISENABLER0, 1u << GIC_INTID_VTIMER);+ /*+ * The interrupts between processors, where there is more than one. A core that an earlier+ * kernel switched off in the middle of one (a return to the boot loader, started again+ * since) may still have it marked active, and would then never see another.+ */+ if (ml_get_cpu_count() > 1) {+ uint32_t sgis = (1u << GIC_SGI_SIGNAL) | (1u << GIC_SGI_STOP);++ gic_write32(gicr + GICR_ICACTIVER0, sgis);+ *(volatile uint8_t *)(gicr + GICR_IPRIORITYR(GIC_SGI_SIGNAL)) = GIC_PRIORITY_DEFAULT;+ *(volatile uint8_t *)(gicr + GICR_IPRIORITYR(GIC_SGI_STOP)) = GIC_PRIORITY_DEFAULT;+ mine |= sgis;+ }++ /* Virtual timer PPI (and those): Group 1 (IRQ), default priority, enabled */+ gic_write32(gicr + GICR_IGROUPR0, gic_read32(gicr + GICR_IGROUPR0) | mine);+ gic_write32(gicr + GICR_IGRPMODR0, gic_read32(gicr + GICR_IGRPMODR0) & ~mine);+ *(volatile uint8_t *)(gicr + GICR_IPRIORITYR(GIC_INTID_VTIMER)) = GIC_PRIORITY_DEFAULT;+ gic_write32(gicr + GICR_ISENABLER0, mine);/* Distributor: affinity routing, Group 1 enabled (normally already so) */uint32_t ctlr = gic_read32(gicd_base + GICD_CTLR);@@ -209,8 +283,8 @@ gic_v3_irq_cpu_init(void)__builtin_arm_isb(ISB_SY);ml_install_interrupt_handler(NULL, 0, NULL, gic_irq_handler, NULL);- kprintf("gic: v3, distributor %p, redistributor %p, virtual timer on PPI %d\n",- (void *)gicd_base, (void *)gicr_cpu_base, GIC_INTID_VTIMER);+ kprintf("gic: v3, distributor %p, cpu %d's redistributor %p, virtual timer on PPI %d\n",+ (void *)gicd_base, cpu, (void *)gicr, GIC_INTID_VTIMER);}#endif /* GENERIC_GIC_V3_IRQ */diff --git a/xnu/files/osfmk/arm64/loader_return.c b/xnu/files/osfmk/arm64/loader_return.cindex ae8fe58..ea8b043 100644--- a/xnu/files/osfmk/arm64/loader_return.c+++ b/xnu/files/osfmk/arm64/loader_return.c@@ -12,10 +12,15 @@* Only valid while the kernel does not drive hardware that UEFI also uses.*/#include <mach/mach_types.h>+#include <machine/atomic.h>+#include <kern/cpu_number.h>#include <kern/debug.h>#include <kern/startup.h>#include <kern/thread_call.h>#include <kern/clock.h>+#include <arm/cpu_internal.h>+#include <arm/machine_routines.h>+#include <arm64/psci_smp.h>#include <arm64/proc_reg.h>#include <pexpert/pexpert.h>#include <pexpert/arm64/board_config.h>@@ -54,26 +59,48 @@ static bool loader_log_wrapped;static bool loader_log_linear; /* the pieces have been put in order: only appending from now on */static char loader_log_scratch[LOADER_LOG_RING];+/*+ * Characters come from every processor, and from interrupt handlers on top of whatever was+ * writing one. The lock is of the simplest kind, good from the first line of C code to the+ * last of a panic; whoever cannot have it for a long while (its holder is gone: a panic+ * inside this very function) goes ahead without it.+ */+static uint32_t loader_log_lock;+voidloader_log_putc(char c){+ uint64_t daif;+ bool locked = false;+if (c == '\r') {return;}+ daif = __builtin_arm_rsr64("DAIF");+ __builtin_arm_wsr("DAIFSet", DAIFSC_IRQF | DAIFSC_FIQF);+ for (uint32_t tries = 0; !locked && tries < 10000000; tries++) {+ locked = os_atomic_cmpxchg(&loader_log_lock, 0, 1, acquire);+ }+if (loader_log_linear || loader_log_len < LOADER_LOG_HEAD) {if (loader_log_len < LOADER_LOG_SIZE) {loader_log[loader_log_len++] = c;}- return;- }- loader_log[LOADER_LOG_HEAD + loader_log_ring_at] = c;- if (++loader_log_ring_at == LOADER_LOG_RING) {- loader_log_ring_at = 0;- loader_log_wrapped = true;+ } else {+ loader_log[LOADER_LOG_HEAD + loader_log_ring_at] = c;+ if (++loader_log_ring_at == LOADER_LOG_RING) {+ loader_log_ring_at = 0;+ loader_log_wrapped = true;+ }+ if (!loader_log_wrapped) {+ loader_log_len = LOADER_LOG_HEAD + loader_log_ring_at;+ }}- if (!loader_log_wrapped) {- loader_log_len = LOADER_LOG_HEAD + loader_log_ring_at;++ if (locked) {+ os_atomic_store(&loader_log_lock, 0, release);}+ __builtin_arm_wsr64("DAIF", daif);}/* Oldest first: the head, a note about what was dropped, then the ring from its oldest character. */@@ -263,6 +290,14 @@ loader_log_append_msgbuf(void)voidloader_return(void){+#if defined(GENERIC_PSCI_SMP)+ /*+ * With more than one processor: the others switch themselves off first, and the rest of+ * this is done by the boot processor, the one the loader gave us. This call comes back+ * on that processor only (on another one it has it call loader_return() in its turn).+ */+ psci_smp_stop_others();+#endif/** A panic's text is first collected in the panic buffer and only later* flushed to the console; if the console itself is what failed, that@@ -296,14 +331,37 @@ loader_checkpoint(uint64_t n)* after that long, whatever the kernel is doing. This is how the log gets out* when the kernel does not panic but simply waits (e.g. for a root device).*/+/*+ * For trying the ways out when there is more than one processor: boot-arg return_cpu=<n> has+ * that processor make the timed return, from an interrupt handler -- any but the boot processor+ * has to hand it over (psci_smp_stop_others()) --, and return_panic=1 makes a panic of it.+ */+static void+loader_return_test(void *as_panic)+{+ if (as_panic != (void *)1) {+ panic("return_panic: the panic that was asked for, on cpu %d", cpu_number());+ }+ loader_return();+}+static voidloader_return_timer(__unused thread_call_param_t p0, __unused thread_call_param_t p1){static const char banner[] = "\n--- loader_return_after expired ---\n";+ uint32_t cpu = 0, as_panic = 0;+for (const char *c = banner; *c; c++) {loader_log_putc(*c);}- loader_return();+ PE_parse_boot_argn("return_panic", &as_panic, sizeof(as_panic));+ if (PE_parse_boot_argn("return_cpu", &cpu, sizeof(cpu)) && cpu <= (uint32_t)ml_get_max_cpu_number() &&+ cpu_xcall((int)cpu, loader_return_test, (void *)(uintptr_t)(as_panic ? 2 : 1)) == KERN_SUCCESS) {+ for (;;) {+ delay_for_interval(1000, NSEC_PER_MSEC); /* that processor ends it */+ }+ }+ loader_return_test((void *)(uintptr_t)(as_panic ? 2 : 1));}__startup_funcdiff --git a/xnu/files/osfmk/arm64/psci_smp.c b/xnu/files/osfmk/arm64/psci_smp.cnew file mode 100644index 0000000..545165f--- /dev/null+++ b/xnu/files/osfmk/arm64/psci_smp.c@@ -0,0 +1,389 @@+/*+ * More than one processor on generic (non-Apple) ARMv8 boards.+ *+ * On Apple hardware the other cores are powered up by closed drivers. Here+ * the firmware does it, through the standard power interface of ARM systems+ * (PSCI): CPU_ON starts a core at an address of the caller's choice, CPU_OFF+ * stops the calling core for good. The address we give is the kernel's own+ * reset vector (LowResetVectorBase in start.s), so that a new core takes the+ * path Apple's cores take: it finds its cpu data by its MPIDR, turns the MMU+ * on and comes out in arm_init_cpu(). The calls are made with SMC or, under+ * a hypervisor that implements them itself, with HVC; the boot loader says+ * which (/chosen/psci-method).+ *+ * The platform expert (iokit/Kernel/GenericARMPE.cpp) registers the cores of+ * the device tree and starts them here, one after the other. Signals between+ * processors are interrupts of the GIC (gic_v3_irq.c).+ *+ * A new core begins with its MMU and caches off, and what it reads then it+ * reads from memory. On real hardware that is not the same as what the+ * running processors see: under Qualcomm's hypervisor (the phone this was+ * written for) a line that is dirty in another core's cache is simply not+ * there yet. QEMU has no cache and shows none of this. So before CPU_ON+ * everything that core will read before its MMU is on is written back to+ * memory (psci_smp_start_cpu()), and what it writes in that state is read+ * only after throwing away the reader's cached copy.+ *+ * The other half is the way out. The kernel ends by returning to the boot+ * loader (loader_return.c), and the loader gets back only what it started:+ * one core, the boot processor's. psci_smp_stop_others() makes every other+ * core switch itself off first, wherever it is.+ */+#include <mach/mach_types.h>+#include <kern/clock.h>+#include <kern/cpu_number.h>+#include <kern/debug.h>+#include <kern/kalloc.h>+#include <kern/misc_protos.h>+#include <libkern/kernel_mach_header.h>+#include <machine/atomic.h>+#include <arm/caches_internal.h>+#include <arm/cpu_data_internal.h>+#include <arm/cpu_internal.h>+#include <arm/machine_routines.h>+#include <arm64/proc_reg.h>+#include <arm64/psci_smp.h>+#include <pexpert/pexpert.h>+#include <pexpert/device_tree.h>+#include <pexpert/arm64/board_config.h>+#include <vm/pmap.h>++#if defined(GENERIC_PSCI_SMP)++#define PSCI_CPU_OFF 0x84000002u+#define PSCI_CPU_ON 0xC4000003u+#define PSCI_AFFINITY_INFO 0xC4000004u+#define PSCI_AFFINITY_OFF 1++#define PSCI_SMP_START_SECONDS 5 /* how long a started core is waited for */+#define PSCI_SMP_STOP_SECONDS 3 /* ... and the cores that were told to stop */++extern void loader_return(void);+extern void loader_log_putc(char c);+extern unsigned long gVirtBase, gPhysBase;++/* The firmware is called with HVC, not SMC. (start.s reads this too, at its physical address.) */+uint32_t psci_smp_hvc;++/*+ * Left by a core that took an exception between its first instruction and the kernel's vectors+ * (Lsecondary_early_exception in start.s). That core writes it with its cache off; it has a+ * cache line to itself so that looking at memory does not disturb anything else.+ */+struct psci_smp_start_fault {+ uint64_t valid, mpidr, esr, elr, far, lr, sp, unused;+} psci_smp_start_fault __attribute__((aligned(64)));+_Static_assert(sizeof(struct psci_smp_start_fault) == 64, "one cache line");++static uint32_t psci_smp_cpu_stage[MAX_CPUS]; /* PSCI_SMP_CPU_*, by cpu number */+static uint32_t psci_smp_started; /* a bit per core that CPU_ON was granted for */++static int psci_smp_stop_owner = -1; /* the processor that began the return to the boot loader */+static bool psci_smp_boot_wanted; /* it was not the boot processor: that one is to finish */+static bool psci_smp_boot_busy; /* ... and has begun to */+static bool psci_smp_stopping; /* every other core switches itself off */++static int64_t+psci_call(uint64_t function, uint64_t arg1, uint64_t arg2, uint64_t arg3)+{+ register uint64_t x0 __asm__("x0") = function;+ register uint64_t x1 __asm__("x1") = arg1;+ register uint64_t x2 __asm__("x2") = arg2;+ register uint64_t x3 __asm__("x3") = arg3;++ if (psci_smp_hvc) {+ __asm__ volatile ("hvc #0" : "+r" (x0), "+r" (x1), "+r" (x2), "+r" (x3) : :+ "x4", "x5", "x6", "x7", "x8", "x9", "x10", "x11", "x12", "x13", "x14", "x15", "x16", "x17");+ } else {+ __asm__ volatile ("smc #0" : "+r" (x0), "+r" (x1), "+r" (x2), "+r" (x3) : :+ "x4", "x5", "x6", "x7", "x8", "x9", "x10", "x11", "x12", "x13", "x14", "x15", "x16", "x17");+ }+ return (int64_t)x0;+}++static const char *+psci_error(int64_t status)+{+ static const char *const names[] = {+ "success", "not supported", "invalid parameters", "denied", "already on", "on pending",+ "internal failure", "not present", "disabled", "invalid address",+ };++ return (status <= 0 && status > -(int64_t)(sizeof(names) / sizeof(names[0]))) ? names[-status] : "?";+}++void+psci_smp_init(void)+{+ DTEntry chosen;+ void const *prop;+ unsigned int size;++ if (SecureDTLookupEntry(NULL, "/chosen", &chosen) == kSuccess &&+ SecureDTGetProperty(chosen, "psci-method", &prop, &size) == kSuccess &&+ size >= 3 && strncmp((const char *)prop, "hvc", 3) == 0) {+ psci_smp_hvc = 1;+ }+}++/* A processor other than the boot processor says how far it has come. */+void+psci_smp_cpu_reached(uint32_t stage)+{+ os_atomic_store(&psci_smp_cpu_stage[cpu_number()], stage, release);+}++/* ... all the way: from GenericARMCPU::initCPU(), where the scheduler takes it. */+void+psci_smp_cpu_running(void)+{+ psci_smp_cpu_reached(PSCI_SMP_CPU_RUNNING);+}++static void+psci_smp_clean_segment(const char *name)+{+ unsigned long size = 0;+ vm_offset_t start = (vm_offset_t)getsegdatafromheader(&_mh_execute_header, name, &size);++ if (start != 0 && size != 0) {+ CleanPoC_DcacheRegion(start, size);+ }+}++/*+ * Start a registered processor: the platform's half of cpu_start(). Waits until the core has+ * joined the scheduler, and says what became of it if it has not: on a phone the log is all+ * there is to go by.+ */+kern_return_t+psci_smp_start_cpu(int cpu)+{+ cpu_data_t *cdp = cpu_datap(cpu);+ uint32_t phys_id = cdp->cpu_phys_id, stage;+ uint64_t entry = ml_static_vtop((vm_offset_t)&LowResetVectorBase);+ uint64_t now, deadline;+ int64_t status;++ /*+ * What that core reads with its MMU off: the code and the page tables of start.s, and what+ * the reset vector finds its way by (ResetHandlerData, CpuDataEntries, the boot arguments,+ * cpu_ttep, psci_smp_hvc ...), all of it in the kernel's own segments; and the cpu data of+ * every processor, which the reset vector goes through looking for its own.+ * Clean, not flush: the processors that are running keep using all of it.+ */+ psci_smp_start_fault.valid = 0;+ psci_smp_clean_segment("__TEXT");+ psci_smp_clean_segment("__DATA_CONST");+ psci_smp_clean_segment("__TEXT_EXEC");+ psci_smp_clean_segment("__DATA");+ psci_smp_clean_segment("__BOOTDATA");+ for (int other = 0; other <= ml_get_max_cpu_number(); other++) {+ if (cpu_datap(other) != NULL) {+ CleanPoC_DcacheRegion((vm_offset_t)cpu_datap(other), sizeof(cpu_data_t));+ }+ }+ __builtin_arm_dsb(DSB_SY);++ os_atomic_store(&psci_smp_cpu_stage[cpu], PSCI_SMP_CPU_ASKED, release);+ status = psci_call(PSCI_CPU_ON, phys_id, entry, 0);+ if (status != 0) {+ os_atomic_store(&psci_smp_cpu_stage[cpu], 0, release);+ printf("psci: cpu %d (MPIDR 0x%x) was not started: the firmware answers %lld (%s)\n",+ cpu, phys_id, status, psci_error(status));+ return KERN_FAILURE;+ }+ os_atomic_or(&psci_smp_started, 1u << cpu, relaxed);++ clock_interval_to_deadline(PSCI_SMP_START_SECONDS, NSEC_PER_SEC, &deadline);+ do {+ stage = os_atomic_load(&psci_smp_cpu_stage[cpu], acquire);+ if (stage >= PSCI_SMP_CPU_RUNNING) {+ return KERN_SUCCESS;+ }+ /* memory, not this processor's copy of it */+ FlushPoC_DcacheRegion((vm_offset_t)&psci_smp_start_fault, sizeof(psci_smp_start_fault));+ if (psci_smp_start_fault.valid != 0) {+ break;+ }+ delay_for_interval(1, NSEC_PER_MSEC);+ now = mach_absolute_time();+ } while (now < deadline);++ if (psci_smp_start_fault.valid != 0) {+ struct psci_smp_start_fault *f = &psci_smp_start_fault;+ uint64_t to_virtual = gVirtBase - gPhysBase;++ printf("psci: cpu %d (MPIDR 0x%llx) took an exception on its way in and has switched itself off: "+ "ESR 0x%llx ELR 0x%llx FAR 0x%llx LR 0x%llx SP 0x%llx (ELR and LR as kernel addresses: 0x%llx 0x%llx)\n",+ cpu, f->mpidr, f->esr, f->elr, f->far, f->lr, f->sp, f->elr + to_virtual, f->lr + to_virtual);+ os_atomic_andnot(&psci_smp_started, 1u << cpu, relaxed); /* nothing of it is left to stop */+ } else {+ printf("psci: cpu %d (MPIDR 0x%x) was started %d seconds ago and has not joined: %s\n",+ cpu, phys_id, PSCI_SMP_START_SECONDS,+ stage >= PSCI_SMP_CPU_IN_KERNEL ? "it got as far as arm_init_cpu()" : "no sign of it since the firmware took the request");+ }+ return KERN_FAILURE;+}++/*+ * The calling processor switches itself off. Its interrupted work, if any, is abandoned where+ * it was: only for the end of the system.+ */+void+psci_smp_cpu_off(void)+{+ __builtin_arm_wsr("DAIFSet", DAIFSC_ALL);+ /* leave nothing behind that would interrupt a core that is no longer there */+ __builtin_arm_wsr64("CNTV_CTL_EL0", CNTV_CTL_EL0_IMASKED);+ gic_v3_irq_quiesce();+ __builtin_arm_wsr64("ICC_IGRPEN1_EL1", 0);+ __builtin_arm_isb(ISB_SY);+ os_atomic_store(&psci_smp_cpu_stage[cpu_number()], PSCI_SMP_CPU_OFF, release);+ __builtin_arm_dsb(DSB_SY);++ (void) psci_call(PSCI_CPU_OFF, 0, 0, 0);+ for (;;) {+ __builtin_arm_wfi(); /* the firmware refused: stay out of the way all the same */+ }+}++static void+psci_smp_note(const char *what, int cpu)+{+ static const char prefix[] = "\npsci: cpu ";++ for (const char *c = prefix; *c; c++) {+ loader_log_putc(*c);+ }+ loader_log_putc((char)('0' + cpu));+ for (const char *c = what; *c; c++) {+ loader_log_putc(*c);+ }+}++/* Tell every core but this one to switch itself off (psci_smp_stop_here() is where they hear it). */+static void+psci_smp_stop_rest(void)+{+ int me = cpu_number(), max_cpu = ml_get_max_cpu_number();++ os_atomic_store(&psci_smp_stopping, true, release);+ __builtin_arm_dsb(DSB_SY);+ for (int cpu = 0; cpu <= max_cpu; cpu++) {+ cpu_data_t *cdp = cpu_datap(cpu);++ if (cpu != me && cdp != NULL && (cpu == master_cpu || (psci_smp_started & (1u << cpu)))) {+ gic_v3_irq_signal_stop(cdp->cpu_phys_id);+ }+ }+ /* for those that wait with their interrupts off (wait_while_mp_kdp_trap(), after a panic) */+ __builtin_arm_sev();+}++/*+ * The system is going back to the boot loader (loader_return()). Returns on the boot processor+ * only, once the other cores are off -- or have been given up on. On any other processor it+ * does not return: that one hands the job to the boot processor, which the loader's side of+ * the return belongs to, and switches itself off like the rest.+ */+void+psci_smp_stop_others(void)+{+ int me, max_cpu;+ uint64_t now, deadline;++ if (psci_smp_started == 0) {+ return; /* there is only this one */+ }+ __builtin_arm_wsr("DAIFSet", DAIFSC_ALL);+ me = cpu_number();+ max_cpu = ml_get_max_cpu_number();+ if (!os_atomic_cmpxchg(&psci_smp_stop_owner, -1, me, acq_rel) && psci_smp_stop_owner != me && me != master_cpu) {+ psci_smp_cpu_off(); /* another processor is at it already */+ }++ if (me != master_cpu) {+ /*+ * Nobody is stopped before the boot processor has answered: a core that is switched+ * off while it holds a lock the boot processor is waiting for would take the return+ * with it.+ */+ psci_smp_note(" ends the system: the return to the boot loader is the boot processor's to make\n", me);+ os_atomic_store(&psci_smp_boot_wanted, true, release);+ __builtin_arm_dsb(DSB_SY);+ gic_v3_irq_signal_stop(cpu_datap(master_cpu)->cpu_phys_id);+ __builtin_arm_sev();+ now = mach_absolute_time();+ nanoseconds_to_absolutetime(PSCI_SMP_STOP_SECONDS * NSEC_PER_SEC, &deadline);+ deadline += now;+ while (!os_atomic_load(&psci_smp_stopping, acquire) && now < deadline) {+ now = mach_absolute_time();+ }+ if (!os_atomic_load(&psci_smp_stopping, acquire)) {+ /*+ * It does not hear (stuck with its interrupts off). There is no return without+ * it; a loader that watches from its own core will find the kernel silent and+ * take the log as it is, and so this goes into the log.+ */+ psci_smp_note(" cannot return to the boot loader and the boot processor does not answer: all cores stop here\n", me);+ psci_smp_stop_rest();+ }+ psci_smp_cpu_off();+ }++ psci_smp_stop_rest();+ now = mach_absolute_time();+ nanoseconds_to_absolutetime(PSCI_SMP_STOP_SECONDS * NSEC_PER_SEC, &deadline);+ deadline += now;+ for (int cpu = 0; cpu <= max_cpu; cpu++) {+ cpu_data_t *cdp = cpu_datap(cpu);++ if (cpu == me || cdp == NULL || !(psci_smp_started & (1u << cpu))) {+ continue;+ }+ while (now < deadline) {+ if (os_atomic_load(&psci_smp_cpu_stage[cpu], acquire) == PSCI_SMP_CPU_OFF) {+ /* it has said it is going; the firmware knows when it has gone (if it can tell at all) */+ int64_t state = psci_call(PSCI_AFFINITY_INFO, cdp->cpu_phys_id, 0, 0);++ if (state == PSCI_AFFINITY_OFF || state < 0) {+ break;+ }+ }+ now = mach_absolute_time();+ }+ if (os_atomic_load(&psci_smp_cpu_stage[cpu], acquire) != PSCI_SMP_CPU_OFF &&+ psci_call(PSCI_AFFINITY_INFO, cdp->cpu_phys_id, 0, 0) != PSCI_AFFINITY_OFF) {+ psci_smp_note(" did not stop: it is left running\n", cpu);+ }+ }+}++/*+ * Where a processor learns that the system is ending: the interrupt psci_smp_stop_rest() sends,+ * and the loop in which the processors wait while another one panics (they have their+ * interrupts off there). Comes back if there is nothing of the kind going on.+ */+void+psci_smp_stop_here(void)+{+ if (psci_smp_started == 0) {+ return;+ }+ if (cpu_number() != master_cpu) {+ if (os_atomic_load(&psci_smp_stopping, acquire)) {+ psci_smp_cpu_off();+ }+ return;+ }+ if (os_atomic_load(&psci_smp_boot_wanted, acquire) && !psci_smp_boot_busy) {+ psci_smp_boot_busy = true;+ loader_return(); /* stops the rest (psci_smp_stop_others()); back only if no loader listens */+ for (;;) {+ __builtin_arm_wfi();+ }+ }+}++#endif /* defined(GENERIC_PSCI_SMP) */diff --git a/xnu/files/osfmk/arm64/psci_smp.h b/xnu/files/osfmk/arm64/psci_smp.hnew file mode 100644index 0000000..62541cf--- /dev/null+++ b/xnu/files/osfmk/arm64/psci_smp.h@@ -0,0 +1,34 @@+/*+ * More than one processor on generic (non-Apple) ARMv8 boards: see psci_smp.c.+ */+#ifndef _ARM64_PSCI_SMP_H_+#define _ARM64_PSCI_SMP_H_++#include <mach/mach_types.h>+#include <sys/cdefs.h>++__BEGIN_DECLS++/* How far a processor other than the boot processor has come (psci_smp_cpu_reached()). */+#define PSCI_SMP_CPU_ASKED 1 /* the firmware has agreed to start it */+#define PSCI_SMP_CPU_IN_KERNEL 2 /* it runs C code on the kernel's page tables (arm_init_cpu()) */+#define PSCI_SMP_CPU_RUNNING 3 /* it has joined the scheduler (psci_smp_cpu_running()) */+#define PSCI_SMP_CPU_OFF 4 /* it has switched itself off, or is about to */++extern void psci_smp_init(void);+extern kern_return_t psci_smp_start_cpu(int cpu);+extern void psci_smp_cpu_reached(uint32_t stage);+extern void psci_smp_cpu_running(void);+extern void psci_smp_cpu_off(void) __dead2;++extern void psci_smp_stop_others(void);+extern void psci_smp_stop_here(void);++/* osfmk/arm64/gic_v3_irq.c */+extern void gic_v3_irq_signal(uint32_t phys_id);+extern void gic_v3_irq_signal_stop(uint32_t phys_id);+extern void gic_v3_irq_quiesce(void);++__END_DECLS++#endif /* _ARM64_PSCI_SMP_H_ */diff --git a/xnu/redwood.patch b/xnu/redwood.patchindex 658c845..d8955f9 100644--- a/xnu/redwood.patch+++ b/xnu/redwood.patch@@ -1465,10 +1465,20 @@ index 0316792a3f42..bbef0a4b26d4 100644# Assume LTO scaling by default, unless it is being explicitly passed on the command-lineLARGE_BUILD_FOOTPRINT := $(if $(BUILD_LTO),$(BUILD_LTO),1)diff --git a/osfmk/arm/arm_init.c b/osfmk/arm/arm_init.c-index e26a1d70f470..5bd6037e6b02 100644+index e26a1d70f470..f91095c98d26 100644--- a/osfmk/arm/arm_init.c+++ b/osfmk/arm/arm_init.c-@@ -335,7 +335,11 @@ arm_setup_pre_sign(void)+@@ -73,6 +73,9 @@+ #include <sys/kdebug.h>++ #include <pexpert/pexpert.h>++#if defined(__arm64__)++#include <arm64/psci_smp.h>++#endif++ #include <console/serial_protos.h>++@@ -335,7 +338,11 @@ arm_setup_pre_sign(void)*/__startup_func@@ -1480,7 +1490,7 @@ index e26a1d70f470..5bd6037e6b02 100644arm_init(boot_args *args){-@@ -354,6 +358,7 @@ arm_init(+@@ -354,6 +361,7 @@ arm_init(const_boot_args = *args;BootArgs = args = &const_boot_args;@@ -1488,7 +1498,7 @@ index e26a1d70f470..5bd6037e6b02 100644cpu_data_init(&BootCpuData);#if defined(HAS_APPLE_PAC)/* bootstrap cpu process dependent key for kernel has been loaded by start.s */-@@ -362,14 +367,19 @@ arm_init(+@@ -362,14 +370,19 @@ arm_init(#endif /* defined(HAS_APPLE_PAC) */PE_init_platform(FALSE, args); /* Get platform expert set up */@@ -1508,7 +1518,7 @@ index e26a1d70f470..5bd6037e6b02 100644#if (DEVELOPMENT || DEBUG)unsigned long const *platform_stall_ptr = NULL;-@@ -385,6 +395,7 @@ arm_init(+@@ -385,6 +398,7 @@ arm_init(}platform_stall_panic_or_spin(PLATFORM_STALL_XNU_LOCATION_ARM_INIT);@@ -1516,7 +1526,7 @@ index e26a1d70f470..5bd6037e6b02 100644chosen = NULL; // Force a re-lookup later on since VM addresses are not final at this pointdt_entry_size = 0;-@@ -422,10 +433,13 @@ arm_init(+@@ -422,10 +436,13 @@ arm_init(}#endif@@ -1530,7 +1540,7 @@ index e26a1d70f470..5bd6037e6b02 100644assert(master_cpu >= 0 && master_cpu <= ml_get_max_cpu_number());BootCpuData.cpu_number = (unsigned short)master_cpu;-@@ -439,11 +453,14 @@ arm_init(+@@ -439,11 +456,14 @@ arm_init(CpuDataEntries[master_cpu].cpu_data_paddr = (void *)((uintptr_t)(args->physBase)+ ((uintptr_t)&BootCpuData- (uintptr_t)(args->virtBase)));@@ -1545,7 +1555,7 @@ index e26a1d70f470..5bd6037e6b02 100644/** Preemption is enabled for this thread so that it can lock mutexes without-@@ -452,12 +469,16 @@ arm_init(+@@ -452,12 +472,16 @@ arm_init(* preemption level is not really meaningful for the bootstrap thread.*/thread->machine.preemption_count = 0;@@ -1562,7 +1572,7 @@ index e26a1d70f470..5bd6037e6b02 100644/** Initialize the timer callout world-@@ -465,6 +486,7 @@ arm_init(+@@ -465,6 +489,7 @@ arm_init(timer_call_init();cpu_init();@@ -1570,7 +1580,7 @@ index e26a1d70f470..5bd6037e6b02 100644processor_bootstrap();-@@ -514,6 +536,7 @@ arm_init(+@@ -514,6 +539,7 @@ arm_init(#endif /* __ARM_PAN_AVAILABLE__ */arm_vm_init(xmaxmem, args);@@ -1578,7 +1588,7 @@ index e26a1d70f470..5bd6037e6b02 100644if (debug_boot_arg) {patch_low_glo();-@@ -527,7 +550,9 @@ arm_init(+@@ -527,7 +553,9 @@ arm_init(/* Setup debugging output. */const unsigned int serial_exists = serial_init();@@ -1588,7 +1598,7 @@ index e26a1d70f470..5bd6037e6b02 100644kprintf("kprintf initialized\n");serialmode = 0;-@@ -569,6 +594,7 @@ arm_init(+@@ -569,6 +597,7 @@ arm_init(disableConsoleOutput = FALSE; /* Allow printfs to happen */}PE_create_console();@@ -1596,7 +1606,7 @@ index e26a1d70f470..5bd6037e6b02 100644/* setup console output */PE_init_printf(FALSE);-@@ -647,6 +673,7 @@ arm_init(+@@ -647,6 +676,7 @@ arm_init(* against string vulnerabilities*/__stack_chk_guard &= ~(0xFFULL << 8);@@ -1604,6 +1614,44 @@ index e26a1d70f470..5bd6037e6b02 100644machine_startup(args);}+@@ -673,6 +703,9 @@ arm_init_cpu(+++ machine_set_current_thread(cpu_data_ptr->cpu_active_thread);++#if defined(GENERIC_PSCI_SMP)++ psci_smp_cpu_reached(PSCI_SMP_CPU_IN_KERNEL);++#endif++ #if APPLE_ARM64_ARCH_FAMILY+ configure_late_apple_regs();+diff --git a/osfmk/arm/model_dep.c b/osfmk/arm/model_dep.c+index 39daaf8db949..64ceb1a5f201 100644+--- a/osfmk/arm/model_dep.c++++ b/osfmk/arm/model_dep.c+@@ -79,6 +79,9 @@+ #include <arm/cpu_data_internal.h>+ #include <arm/cpu_internal.h>+ #include <arm/misc_protos.h>++#if defined(__arm64__)++#include <arm64/psci_smp.h>++#endif+ #include <libkern/OSKextLibPrivate.h>+ #include <vm/vm_kern.h>+ #include <kern/kern_cdata.h>+@@ -1156,6 +1159,13 @@ wait_while_mp_kdp_trap(bool check_SIGPdebug)+ found_SIGPdebug = true;+ break;+ }++#if defined(GENERIC_PSCI_SMP)++ /*++ * The panic this processor is waiting out ends in a return to the boot loader:++ * its interrupts are off here, so this is where it is told (psci_smp.c).++ */++ psci_smp_stop_here();++#endif+ __builtin_arm_wfe();+ }+ os_atomic_clear_exclusive();diff --git a/osfmk/arm/pmap/pmap.c b/osfmk/arm/pmap/pmap.cindex fc2096fa0010..d71b2640cb8c 100644--- a/osfmk/arm/pmap/pmap.c@@ -1689,6 +1737,24 @@ index b9549da357b4..cca31ea32502 100644#define __USES_V_CRYPTO_INTRINSICS 1#else#define __USES_V_CRYPTO_INTRINSICS 0+diff --git a/osfmk/arm64/cpu.c b/osfmk/arm64/cpu.c+index 94e91306b143..0ec1323086b7 100644+--- a/osfmk/arm64/cpu.c++++ b/osfmk/arm64/cpu.c+@@ -568,7 +568,12 @@ cpu_idle(void)+ #endif /* MONOTONIC */++ if (wfi) {+-#if !defined(APPLE_ARM64_ARCH_FAMILY)++#if !defined(APPLE_ARM64_ARCH_FAMILY) && !defined(GENERIC_PSCI_SMP)++ /*++ * (Not on the generic boards either. There a core keeps its cache while it waits,++ * and this would empty it by set and way every time: slow, wrong among several++ * processors, and under a hypervisor every one of those instructions is a trap.)++ */+ platform_cache_idle_enter();+ #endif+diff --git a/osfmk/arm64/machine_routines.c b/osfmk/arm64/machine_routines.cindex e76e7e70ab9c..d702d171e3d1 100644--- a/osfmk/arm64/machine_routines.c@@ -1729,10 +1795,57 @@ index e76e7e70ab9c..d702d171e3d1 100644voiddiff --git a/osfmk/arm64/start.s b/osfmk/arm64/start.s-index e5336e5a1cce..df132aa3c772 100644+index e5336e5a1cce..a54e35035cde 100644--- a/osfmk/arm64/start.s+++ b/osfmk/arm64/start.s-@@ -233,40 +233,88 @@ LEXT(_start)+@@ -126,6 +126,27 @@ LEXT(LowResetVectorBase)+ .globl EXT(reset_vector)+ LEXT(reset_vector)+ // Preserve x0 for start_first_cpu, if called++#if defined(GENERIC_PSCI_SMP)++ /*++ * A core that the firmware has just started for us (PSCI CPU_ON, see++ * psci_smp.c) has no vectors at all, and under a third-party hypervisor++ * even the OS lock write can trap: vectors first. Not the boot++ * processor's early ones, which hand the exception to the boot loader:++ * that is not for this core to do.++ */++ msr DAIFSet, #(DAIFSC_ALL) // Disable all interrupts++ adrp x0, EXT(LowSecondaryExceptionVectorBase)@page++ add x0, x0, EXT(LowSecondaryExceptionVectorBase)@pageoff++ msr VBAR_EL1, x0++ isb++ // The MMU and the caches are off, says PSCI; of the rest of SCTLR it++ // says nothing. Only the bits that must be set, until common_start.++ MOV64 x0, 0x30D00800++ msr SCTLR_EL1, x0++ isb++ // Unlock the core for debugging++ msr OSLAR_EL1, xzr++#else /* defined(GENERIC_PSCI_SMP) */+ // Unlock the core for debugging+ msr OSLAR_EL1, xzr+ msr DAIFSet, #(DAIFSC_ALL) // Disable all interrupts+@@ -136,6 +157,7 @@ LEXT(reset_vector)+ add x0, x0, EXT(LowExceptionVectorBase)@pageoff+ msr VBAR_EL1, x0+ #endif++#endif /* defined(GENERIC_PSCI_SMP) */++++@@ -143,7 +165,9 @@ LEXT(reset_vector)+ adrp x19, EXT(ResetHandlerData)@page // Get address of the reset handler data+ add x19, x19, EXT(ResetHandlerData)@pageoff+ mrs x15, MPIDR_EL1 // Load MPIDR to get CPU number+-#if HAS_CLUSTER++#if HAS_CLUSTER || defined(GENERIC_PSCI_SMP)++ // (generic boards: some number their cores in Affinity1 and leave Affinity0 at zero;++ // a cpu data's phys id is both fields, as the device tree's "reg" has them)+ and x0, x15, #0xFFFF // CPU number in Affinity0, cluster ID in Affinity1+ #else+ and x0, x15, #0xFF // CPU number is in MPIDR Affinity Level 0+@@ -233,40 +257,175 @@ LEXT(_start).global EXT(LowExceptionVectorBase)LEXT(LowExceptionVectorBase)/* EL1 SP 0 */@@ -1834,10 +1947,97 @@ index e5336e5a1cce..df132aa3c772 100644+ .quad 0 // PA of the loader's return stub+ .quad 0 // checkpoint number to stop at (0 = none)+ .quad 0 // (physical - virtual) offset of the static kernel image++++#if defined(GENERIC_PSCI_SMP)++/*++ * The same for a core other than the boot processor, from its first++ * instruction (reset_vector) until common_start gives it the kernel's++ * vectors. The boot loader is not this core's to return to; it leaves a note++ * of what happened where the processor that is waiting for it looks++ * (psci_smp_start_cpu()) and switches itself off again.++ *++ * VBAR holds a physical address here too, so the note is addressed++ * physically; the store goes straight to memory when the MMU is still off,++ * and is sent there when it is not.++ */++ .align 11++ .globl EXT(LowSecondaryExceptionVectorBase)++LEXT(LowSecondaryExceptionVectorBase)++ /* EL1 SP 0 */++ b Lsecondary_early_exception++ .align 7++ b Lsecondary_early_exception++ .align 7++ b Lsecondary_early_exception++ .align 7++ b Lsecondary_early_exception++ /* EL1 SP1 */++ .align 7++ b Lsecondary_early_exception++ .align 7++ b Lsecondary_early_exception++ .align 7++ b Lsecondary_early_exception++ .align 7++ b Lsecondary_early_exception++ /* EL0 64 */++ .align 7++ b Lsecondary_early_exception++ .align 7++ b Lsecondary_early_exception++ .align 7++ b Lsecondary_early_exception++ .align 7++ b Lsecondary_early_exception++ /* EL0 32 */++ .align 7++ b Lsecondary_early_exception++ .align 7++ b Lsecondary_early_exception++ .align 7++ b Lsecondary_early_exception++ .align 7++ b Lsecondary_early_exception++++ .align 3++Lsecondary_early_exception:++ // struct psci_smp_start_fault: { valid, MPIDR, ESR, ELR, FAR, LR, SP }++ adrp x9, EXT(psci_smp_start_fault)@page++ add x9, x9, EXT(psci_smp_start_fault)@pageoff++ mrs x10, MPIDR_EL1++ str x10, [x9, #8]++ mrs x10, ESR_EL1++ str x10, [x9, #16]++ mrs x10, ELR_EL1++ str x10, [x9, #24]++ mrs x10, FAR_EL1++ str x10, [x9, #32]++ str lr, [x9, #40]++ mov x10, sp++ str x10, [x9, #48]++ mov x10, #1++ str x10, [x9]++ dc cvac, x9++ dsb sy++ // PSCI CPU_OFF, by the firmware's calling convention (psci_smp_hvc)++ adrp x9, EXT(psci_smp_hvc)@page++ add x9, x9, EXT(psci_smp_hvc)@pageoff++ ldr w9, [x9]++ mov x0, #0x0002++ movk x0, #0x8400, lsl #16++ cbnz w9, 1f++ smc #0++ b 2f++1:++ hvc #0++2:++ wfi // it does not return; if it does, stay here++ b 2b++#endif /* defined(GENERIC_PSCI_SMP) */.align 12, 0#if defined(KERNEL_INTEGRITY_KTRR) || defined(KERNEL_INTEGRITY_CTRR)-@@ -452,22 +500,51 @@ start_cpu:+@@ -452,22 +611,51 @@ start_cpu:* Cold boot init routine. Called from __start* x0 - Boot args*/@@ -1892,7 +2092,7 @@ index e5336e5a1cce..df132aa3c772 100644// Get the kernel memory parameters from the boot argsldr x22, [x20, BA_VIRT_BASE] // Get the kernel virt base-@@ -612,6 +689,7 @@ Lkernelcache_base_found:+@@ -612,6 +800,7 @@ Lkernelcache_base_found:/* Ensure TTEs are visible */dsb ish@@ -1900,7 +2100,7 @@ index e5336e5a1cce..df132aa3c772 100644b common_start-@@ -686,7 +764,10 @@ common_start:+@@ -686,7 +875,10 @@ common_start:dsb ish@@ -1912,7 +2112,7 @@ index e5336e5a1cce..df132aa3c772 100644// Setup timer interrupt routing; must be done before MMU is enabledmrs x15, MPIDR_EL1 // Load MPIDR to get CPU numberand x15, x15, #0xFF // CPU number is in MPIDR Affinity Level 0-@@ -740,10 +821,17 @@ common_start:+@@ -740,10 +932,17 @@ common_start:PAC_INIT_KEY_STATE tmp=x0, tmp2=x1#endif /* HAS_APPLE_PAC */@@ -1942,7 +2142,7 @@ index 9d98c50094a0..9e3476124e54 100644+osfmk/minicrypto/mc_provider.c standard+osfmk/minicrypto/mc_aes.c standarddiff --git a/osfmk/conf/files.arm64 b/osfmk/conf/files.arm64-index c40d57bcc677..6e1041216be1 100644+index c40d57bcc677..1b7a1fcdfcdf 100644--- a/osfmk/conf/files.arm64+++ b/osfmk/conf/files.arm64@@ -25,8 +25,8 @@ osfmk/arm64/WKdmCompress_4k.s standard@@ -1956,7 +2156,7 @@ index c40d57bcc677..6e1041216be1 100644osfmk/arm64/bcopy.s standardosfmk/arm64/bzero.s standardosfmk/arm/caches.c standard-@@ -104,3 +104,7 @@ osfmk/arm64/machine_remote_time.c optional config_mach_bridge_recv_time+@@ -104,3 +104,8 @@ osfmk/arm64/machine_remote_time.c optional config_mach_bridge_recv_timeosfmk/arm64/corecrypto/sha256_compress_arm64.s standardosfmk/arm/counter.c standard@@ -1964,6 +2164,7 @@ index c40d57bcc677..6e1041216be1 100644+osfmk/arm64/loader_return.c optional nos_arm_asm+osfmk/arm64/user_exception_trace.c standard+osfmk/arm64/gic_v3_irq.c optional nos_arm_asm++osfmk/arm64/psci_smp.c optional nos_arm_asmdiff --git a/osfmk/console/video_console.c b/osfmk/console/video_console.cindex 384118e8d7a9..2573d2ebd4e6 100644--- a/osfmk/console/video_console.c@@ -2151,14 +2352,15 @@ index 65144c74239c..ab6260d52d84 100644}diff --git a/pexpert/pexpert/arm64/BCM2837.h b/pexpert/pexpert/arm64/BCM2837.h-index d9f0723244e5..e78fb263d98a 100644+index d9f0723244e5..53fe4f371d7f 100644--- a/pexpert/pexpert/arm64/BCM2837.h+++ b/pexpert/pexpert/arm64/BCM2837.h-@@ -11,6 +11,14 @@+@@ -11,6 +11,15 @@#define BCM2837#define BCM2837_BRINGUP#define ARM_ARCH_TIMER+#define GENERIC_GIC_V3_IRQ 1 /* interrupts via GICv3 Group 1, see osfmk/arm64/gic_v3_irq.c */++#define GENERIC_PSCI_SMP 1 /* more cores are started through PSCI, see osfmk/arm64/psci_smp.c */++/*+ * The cores this kernel really runs on (Cortex-A55/A78, QEMU cortex-a76) are@@ -2169,7 +2371,7 @@ index d9f0723244e5..e78fb263d98a 100644#define __ARM_ARCH__ 8#define __ARM_VMSA__ 8-@@ -22,6 +30,7 @@+@@ -22,6 +31,7 @@#ifndef ASSEMBLER#define PI3_UART@@ -2177,7 +2379,7 @@ index d9f0723244e5..e78fb263d98a 100644#define PI3_BREAK asm volatile("brk #0");-@@ -60,8 +69,11 @@+@@ -60,8 +70,11 @@#define BCM2837_PUT32(addr, value) do { *((volatile uint32_t *) addr) = value; } while(0)#define BCM2837_GET32(addr) *((volatile uint32_t *) addr)@@ -2191,6 +2393,19 @@ index d9f0723244e5..e78fb263d98a 100644#endif /* ! ASSEMBLER */#endif /* ! _PEXPERT_ARM_BCM2837_H */+diff --git a/pexpert/pexpert/arm64/board_config.h b/pexpert/pexpert/arm64/board_config.h+index c84b2100bc19..aaad5cd2e8c6 100644+--- a/pexpert/pexpert/arm64/board_config.h++++ b/pexpert/pexpert/arm64/board_config.h+@@ -91,7 +91,7 @@+ #include <pexpert/arm64/BCM2837.h>++ #define MAX_L2_CLINE 6+-#define MAX_CPUS 4++#define MAX_CPUS 8 /* the Raspberry Pi has four; the boards this runs on now have up to eight */+ #define MAX_CPU_CLUSTERS 1++ #define CORE_NCTRS 8 /* Placeholder; KPC is not enabled for this target */diff --git a/security/mac_vfs_subr.c b/security/mac_vfs_subr.cindex 97028c06bb92..0daad830d0c0 100644--- a/security/mac_vfs_subr.c