Skip to content

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

C

Add pure-EL0 AArch64 host support for running XNU and macOS 27 (#11)

CommaBot9a92b5ffe96d
diff --git a/docs/smp.md b/docs/smp.md
index d43e1b6..0198001 100644
--- a/docs/smp.md
+++ b/docs/smp.md
@@ -1,3 +1,4 @@
+<!-- SPDX-License-Identifier: GPL-2.0-only -->
# Hosted XNU on several CPUs
Today the hosted XNU runs on one CPU: xnu.ko's loading task, bound to Linux CPU 0, enters the XNU world and stays
@@ -8,7 +9,7 @@ decoder in the hosted system), which needs several cores. This is the plan for N
| Where | State | For N CPUs |
|---|---|---|
-| 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 current thread (on hardware `TPIDR_EL1`, which is Linux's per-CPU base while hosted) | A global (`linux64_tpidr`) | Done: `TPIDR_EL0` in XNU's kernel (user `TPIDR_EL0` is swapped on EL0 entry/exit and persisted per thread in `linux64_user_tpidr`; user `TPIDRRO_EL0` holds `cthread_self`), 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`, 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) |
diff --git a/fki-ko/Makefile b/fki-ko/Makefile
index 99fb500..32adc02 100644
--- a/fki-ko/Makefile
+++ b/fki-ko/Makefile
@@ -1,3 +1,8 @@
# SPDX-License-Identifier: GPL-2.0-only
obj-m += fki.o
-fki-y := fki_mod.o fki_hostcall.o
+fki-y := fki_common.o fki_hostcall.o
+ifeq ($(CONFIG_L4H),y)
+fki-y += fki_l4h.o
+else
+fki-$(CONFIG_ARM64) += fki_arm64.o
+endif
diff --git a/fki-ko/fki.h b/fki-ko/fki.h
index 9a5f215..6fb84f9 100644
--- a/fki-ko/fki.h
+++ b/fki-ko/fki.h
@@ -1,6 +1,6 @@
/* SPDX-License-Identifier: GPL-2.0-only WITH Linux-syscall-note */
/*
- * Foreign kernel interface (FKI), version 0.
+ * Foreign kernel interface (FKI), version 2.
*
* The only interface between Linux and a foreign-kernel module. It is
* semantic and shaped like a hypervisor interface: plain integer types and
@@ -10,7 +10,7 @@
#ifndef _LINUX_FKI_H
#define _LINUX_FKI_H
-#define FKI_VERSION 0
+#define FKI_VERSION 2
#ifndef __KERNEL__
#include <stdint.h>
@@ -20,6 +20,17 @@ typedef uint64_t fki_u64;
typedef u64 fki_u64;
#endif
+/* Host capability bits returned by fki_caps(). */
+#define FKI_CAP_EL0 (1UL << 0) /* hosted kernel runs at EL0 */
+#define FKI_CAP_HIGH_WINDOW (1UL << 1) /* host manages TTBR1 high window */
+#define FKI_CAP_PAC (1UL << 2) /* per-context PAC keys supported */
+#define FKI_CAP_EXEC_ONLY (1UL << 3) /* execute-only (--x) user mappings supported */
+
+/* Page mapping protection bits for fki_high_map() and fki_as_map(). */
+#define FKI_PROT_READ (1 << 0)
+#define FKI_PROT_WRITE (1 << 1)
+#define FKI_PROT_EXEC (1 << 2)
+
/* Physically contiguous memory, mapped contiguously and executable. */
struct fki_region {
void *va;
@@ -34,10 +45,30 @@ struct fki_pac_keys {
fki_u64 sctlr_en; /* SCTLR_EL1 EnIA|EnIB|EnDA|EnDB bits */
};
+/* User-context register state and stop info (FKI_CAP_EL0 hosts). */
+struct fki_utcb_regs {
+ fki_u64 x[31];
+ fki_u64 sp, pc, pstate, tpidr, tpidrro;
+};
+
+enum {
+ FKI_STOP_SYSCALL = 1,
+ FKI_STOP_PAGEFAULT = 2,
+ FKI_STOP_EXCEPTION = 3,
+ FKI_STOP_INTERRUPT = 4,
+};
+
+struct fki_utcb_stop {
+ int kind;
+ fki_u64 fault_addr, fault_ip, esr;
+};
+
#ifdef __cplusplus
extern "C" {
#endif
int fki_version(void);
+unsigned long fki_caps(void);
+int fki_cpu_id(void);
void fki_log(const char *s, unsigned long len);
void fki_log_alert(const char *s, unsigned long len); /* KERN_ALERT: on the console even when it is quiet */
int fki_region_alloc(unsigned long size, struct fki_region *r);
@@ -50,7 +81,7 @@ void fki_blob_put(void *handle);
unsigned long fki_enter(const struct fki_pac_keys *foreign, struct fki_pac_keys *saved);
void fki_leave(unsigned long cookie, const struct fki_pac_keys *saved);
/* Swap PAC keys only (caller already in a foreign context): save current into *save, load *load. */
-void fki_pac_swap(const struct fki_pac_keys *load, struct fki_pac_keys *save);
+int fki_pac_swap(const struct fki_pac_keys *load, struct fki_pac_keys *save);
fki_u64 fki_counter_frequency(void);
fki_u64 fki_counter(void);
void fki_random(void *buf, unsigned long len);
@@ -68,6 +99,43 @@ void fki_contig_free(struct fki_region *r);
*/
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);
+/*
+ * Host-managed foreign kernel memory and high-window mappings (FKI_CAP_HIGH_WINDOW):
+ * fki_kmem_alloc allocates backing memory (no multi-GB physical contiguity required), maps it at high_va
+ * as RWX, associates synthetic physical addresses starting at pa_base, and binds the high window on all CPUs.
+ * fki_high_map/unmap/flush mirror additional kernel-VA mappings backed by xpa in [pa_base, pa_base + size).
+ * fki_high_map only supports new mappings or in-place same-PFN re-protection; cross-PFN replacement
+ * returns -EBUSY and requires the caller to fki_high_unmap while quiescent first.
+ */
+int fki_kmem_alloc(unsigned long size, unsigned long high_va, fki_u64 pa_base, struct fki_region *r);
+void fki_kmem_free(struct fki_region *r);
+int fki_high_map(unsigned long va, fki_u64 xpa, unsigned long size, int prot);
+void fki_high_unmap(unsigned long va, unsigned long size);
+void fki_high_flush(void);
+int fki_high_txn_begin(unsigned long va, unsigned long size, void **handle_out);
+void fki_high_txn_restore(void *txn);
+void fki_high_txn_end(void *txn);
+int fki_high_read_u64x2(unsigned long va, fki_u64 *out0, fki_u64 *out1);
+void fki_icache_flush(unsigned long va, unsigned long size);
+/*
+ * Host-managed user address spaces and user execution contexts (FKI_CAP_EL0).
+ * Passing as == NULL to fki_as_unmap() broadcasts the unmap of [va, va + size)
+ * across all active user address spaces (for shared/nested page tables).
+ */
+void *fki_as_create(void);
+void fki_as_destroy(void *as);
+int fki_as_map(void *as, unsigned long va, fki_u64 xpa, unsigned long size, int prot);
+void fki_as_unmap(void *as, unsigned long va, unsigned long size);
+void fki_as_flush(void *as);
+void *fki_utcb_create(void *as);
+void fki_utcb_destroy(void *utcb);
+int fki_utcb_set_as(void *utcb, void *as);
+int fki_utcb_set_pac(void *utcb, const struct fki_pac_keys *keys);
+int fki_utcb_run(void *utcb, struct fki_utcb_regs *regs, struct fki_utcb_stop *stop);
+int fki_utcb_resume(void *utcb, struct fki_utcb_regs *regs, struct fki_utcb_stop *stop);
+int fki_utcb_sync_regs(void *utcb, struct fki_utcb_regs *regs);
+int fki_utcb_fpu_read(void *utcb, void *buf, unsigned long len);
+int fki_utcb_fpu_write(void *utcb, const void *buf, unsigned long len);
/*
* 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, or fki_kick_cpu() is called for this CPU, then return with them off
diff --git a/fki-ko/fki_arm64.c b/fki-ko/fki_arm64.c
new file mode 100644
index 0000000..773a15b
--- /dev/null
+++ b/fki-ko/fki_arm64.c
@@ -0,0 +1,647 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * Foreign kernel interface, version 1: native arm64 (EL1) backend.
+ */
+#include "fki.h"
+#include "fki_internal.h"
+#include <linux/efi.h>
+#include <linux/gfp.h>
+#include <linux/io.h>
+#include <linux/ioport.h>
+#include <linux/irqflags.h>
+#include <linux/kprobes.h>
+#include <linux/mm.h>
+#include <linux/module.h>
+#include <linux/preempt.h>
+#include <linux/printk.h>
+#include <linux/sched.h>
+#include <linux/smp.h>
+#include <linux/uaccess.h>
+#include <linux/vmalloc.h>
+#include <asm/arch_timer.h>
+#include <asm/barrier.h>
+#include <asm/cpufeature.h>
+#include <asm/neon.h>
+#include <asm/stacktrace.h>
+#include <asm/sysreg.h>
+#include <asm/tlbflush.h>
+
+unsigned long fki_caps(void)
+{
+ unsigned long caps = FKI_CAP_EXEC_ONLY;
+
+ if (system_supports_address_auth())
+ caps |= FKI_CAP_PAC;
+ return caps;
+}
+EXPORT_SYMBOL(fki_caps);
+
+int fki_cpu_id(void)
+{
+ return smp_processor_id();
+}
+EXPORT_SYMBOL(fki_cpu_id);
+
+/*
+ * Out-of-tree form only: stock kernels do not export set_memory_x(). The in-tree FKI
+ * patch calls it directly; here it is found once through kallsyms (via a kprobe).
+ */
+typedef int (*set_memory_fn)(unsigned long addr, int numpages);
+typedef struct page *(*alloc_contig_fn)(unsigned long nr_pages, gfp_t gfp, int nid, nodemask_t *nodemask);
+typedef void (*free_contig_fn)(unsigned long pfn, unsigned long nr_pages);
+static alloc_contig_fn p_alloc_contig;
+static free_contig_fn p_free_contig;
+struct cma;
+static struct cma **p_cma_area; /* the default CMA area (cma= on the command line), if any */
+static struct page *(*p_cma_alloc)(struct cma *, unsigned long, unsigned int, bool); /* not exported on every kernel */
+static bool (*p_cma_release)(struct cma *, const struct page *, unsigned long);
+static set_memory_fn p_set_memory_x, p_set_memory_nx;
+static unsigned long p_stext, p_end;
+static u64 *p_kimage_voffset;
+static int (*p_efi_mem_type)(unsigned long); /* the firmware's memory map: is the carve-out RAM at all */
+
+static int fki_resolve(void)
+{
+ static unsigned long (*lookup)(const char *);
+ struct kprobe kp = { .symbol_name = "kallsyms_lookup_name" };
+
+ if (p_set_memory_x)
+ return 0;
+ if (!lookup) {
+ if (register_kprobe(&kp))
+ return -ENOENT;
+ lookup = (void *)kp.addr;
+ unregister_kprobe(&kp);
+ }
+ p_set_memory_x = (set_memory_fn)lookup("set_memory_x");
+ p_alloc_contig = (alloc_contig_fn)lookup("alloc_contig_pages_noprof");
+ if (!p_alloc_contig)
+ p_alloc_contig = (alloc_contig_fn)lookup("alloc_contig_pages");
+ p_free_contig = (free_contig_fn)lookup("free_contig_range");
+ p_cma_area = (struct cma **)lookup("dma_contiguous_default_area");
+ p_cma_alloc = (void *)lookup("cma_alloc");
+ p_cma_release = (void *)lookup("cma_release");
+ p_set_memory_nx = (set_memory_fn)lookup("set_memory_nx");
+ p_stext = lookup("_stext");
+ p_end = lookup("_end");
+ p_kimage_voffset = (u64 *)lookup("kimage_voffset");
+ p_efi_mem_type = (void *)lookup("efi_mem_type");
+ return p_set_memory_x && p_set_memory_nx ? 0 : -ENOENT;
+}
+
+int fki_region_alloc(unsigned long size, struct fki_region *r)
+{
+ unsigned long n = PAGE_ALIGN(size) >> PAGE_SHIFT;
+ void *va;
+ int err;
+
+ /* vmap() memory is never executable on current kernels; vmalloc + set_memory_x is (out-of-tree form). */
+ err = fki_resolve();
+ if (err)
+ return err;
+ va = vzalloc(n << PAGE_SHIFT);
+ if (!va)
+ return -ENOMEM;
+ err = p_set_memory_x((unsigned long)va, n);
+ if (err) {
+ vfree(va);
+ return err;
+ }
+ r->va = va;
+ r->pa = page_to_phys(vmalloc_to_page(va));
+ r->size = n << PAGE_SHIFT;
+ r->handle = NULL;
+ return 0;
+}
+EXPORT_SYMBOL(fki_region_alloc);
+
+void fki_region_free(struct fki_region *r)
+{
+ p_set_memory_nx((unsigned long)r->va, r->size >> PAGE_SHIFT);
+ vfree(r->va);
+}
+EXPORT_SYMBOL(fki_region_free);
+
+#define FKI_SCTLR_EN (SCTLR_ELx_ENIA | SCTLR_ELx_ENIB | SCTLR_ELx_ENDA | SCTLR_ELx_ENDB)
+
+static __always_inline void keys_read(struct fki_pac_keys *k)
+{
+ k->ia[0] = read_sysreg_s(SYS_APIAKEYLO_EL1); k->ia[1] = read_sysreg_s(SYS_APIAKEYHI_EL1);
+ k->ib[0] = read_sysreg_s(SYS_APIBKEYLO_EL1); k->ib[1] = read_sysreg_s(SYS_APIBKEYHI_EL1);
+ k->da[0] = read_sysreg_s(SYS_APDAKEYLO_EL1); k->da[1] = read_sysreg_s(SYS_APDAKEYHI_EL1);
+ k->db[0] = read_sysreg_s(SYS_APDBKEYLO_EL1); k->db[1] = read_sysreg_s(SYS_APDBKEYHI_EL1);
+ k->ga[0] = read_sysreg_s(SYS_APGAKEYLO_EL1); k->ga[1] = read_sysreg_s(SYS_APGAKEYHI_EL1);
+ k->sctlr_en = read_sysreg(sctlr_el1) & FKI_SCTLR_EN;
+}
+
+static __always_inline void keys_write(const struct fki_pac_keys *k)
+{
+ write_sysreg_s(k->ia[0], SYS_APIAKEYLO_EL1); write_sysreg_s(k->ia[1], SYS_APIAKEYHI_EL1);
+ write_sysreg_s(k->ib[0], SYS_APIBKEYLO_EL1); write_sysreg_s(k->ib[1], SYS_APIBKEYHI_EL1);
+ write_sysreg_s(k->da[0], SYS_APDAKEYLO_EL1); write_sysreg_s(k->da[1], SYS_APDAKEYHI_EL1);
+ write_sysreg_s(k->db[0], SYS_APDBKEYLO_EL1); write_sysreg_s(k->db[1], SYS_APDBKEYHI_EL1);
+ write_sysreg_s(k->ga[0], SYS_APGAKEYLO_EL1); write_sysreg_s(k->ga[1], SYS_APGAKEYHI_EL1);
+ sysreg_clear_set(sctlr_el1, FKI_SCTLR_EN, k->sctlr_en & FKI_SCTLR_EN);
+ isb();
+}
+
+void fki_fpsimd_forget(void)
+{
+ struct user_fpsimd_state scratch; /* where Linux would save a kernel-mode state over a context switch: none here */
+
+ kernel_neon_begin(&scratch);
+ kernel_neon_end(&scratch);
+}
+
+__attribute__((target("branch-protection=none"))) unsigned long fki_enter(const struct fki_pac_keys *foreign, struct fki_pac_keys *saved)
+{
+ unsigned long flags;
+
+ fki_fpsimd_forget();
+ preempt_disable();
+ local_irq_save(flags);
+ keys_read(saved);
+ keys_write(foreign);
+ return flags;
+}
+EXPORT_SYMBOL(fki_enter);
+
+__attribute__((target("branch-protection=none"))) void fki_leave(unsigned long cookie, const struct fki_pac_keys *saved)
+{
+ keys_write(saved);
+ local_irq_restore(cookie);
+ preempt_enable();
+}
+EXPORT_SYMBOL(fki_leave);
+
+__attribute__((target("branch-protection=none"))) int fki_pac_swap(const struct fki_pac_keys *load, struct fki_pac_keys *save)
+{
+ keys_read(save);
+ keys_write(load);
+ return 0;
+}
+EXPORT_SYMBOL(fki_pac_swap);
+
+fki_u64 fki_counter_frequency(void)
+{
+ return arch_timer_get_cntfrq();
+}
+EXPORT_SYMBOL(fki_counter_frequency);
+
+fki_u64 fki_counter(void)
+{
+ return __arch_counter_get_cntvct();
+}
+EXPORT_SYMBOL(fki_counter);
+
+/* ---- foreign kernel faults ---- */
+
+static unsigned long fki_fault_lo, fki_fault_hi;
+static int (*fki_fault_handler)(unsigned long far, unsigned long esr, void *regs);
+
+static int fki_fault_pre(struct kprobe *p, struct pt_regs *kregs)
+{
+ unsigned long far = kregs->regs[0], esr = kregs->regs[1];
+ struct pt_regs *regs = (struct pt_regs *)kregs->regs[2];
+ int (*h)(unsigned long, unsigned long, void *) = READ_ONCE(fki_fault_handler);
+
+ if (!h || user_mode(regs))
+ return 0;
+ if ((far < fki_fault_lo || far >= fki_fault_hi) &&
+ (instruction_pointer(regs) < fki_fault_lo || instruction_pointer(regs) >= fki_fault_hi))
+ return 0;
+ if (h(far, esr, regs))
+ return 0;
+ instruction_pointer_set(kregs, kregs->regs[30]); /* __do_kernel_fault returns at once */
+ return 1;
+}
+NOKPROBE_SYMBOL(fki_fault_pre);
+
+unsigned long fki_regs_pc(void *regs) { return instruction_pointer((struct pt_regs *)regs); }
+EXPORT_SYMBOL(fki_regs_pc);
+unsigned long fki_regs_lr(void *regs) { return ((struct pt_regs *)regs)->regs[30]; }
+EXPORT_SYMBOL(fki_regs_lr);
+unsigned long fki_regs_pstate(void *regs) { return ((struct pt_regs *)regs)->pstate; }
+EXPORT_SYMBOL(fki_regs_pstate);
+void fki_regs_set_pc(void *regs, unsigned long pc) { instruction_pointer_set((struct pt_regs *)regs, pc); }
+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;
+
+static int fki_die_pre(struct kprobe *p, struct pt_regs *kregs)
+{
+ struct pt_regs *regs = (struct pt_regs *)kregs->regs[1];
+ unsigned long esr = kregs->regs[2];
+ int (*h)(unsigned long, unsigned long, void *) = READ_ONCE(fki_fault_handler);
+
+ if (!h || !regs || user_mode(regs))
+ return 0;
+ if (instruction_pointer(regs) < fki_fault_lo || instruction_pointer(regs) >= fki_fault_hi)
+ return 0;
+ if (h(0, esr, regs))
+ return 0;
+ instruction_pointer_set(kregs, kregs->regs[30]); /* die returns at once */
+ return 1;
+}
+NOKPROBE_SYMBOL(fki_die_pre);
+static struct kprobe fki_die_kp = { .symbol_name = "die", .pre_handler = fki_die_pre };
+static int fki_die_registered;
+
+int fki_fault_register(unsigned long lo, unsigned long hi, int (*handler)(unsigned long far, unsigned long esr, void *regs))
+{
+ int err;
+
+ if (fki_fault_registered)
+ return -EBUSY;
+ fki_fault_lo = lo;
+ fki_fault_hi = hi;
+ WRITE_ONCE(fki_fault_handler, handler);
+ err = register_kprobe(&fki_fault_kp);
+ if (err) {
+ WRITE_ONCE(fki_fault_handler, NULL);
+ return err;
+ }
+ fki_fault_registered = 1;
+ fki_die_registered = register_kprobe(&fki_die_kp) == 0; /* best effort */
+ if (!fki_die_registered)
+ pr_warn("fki: no die() probe: foreign non-abort exceptions oops\n");
+ return 0;
+}
+EXPORT_SYMBOL(fki_fault_register);
+
+void fki_fault_unregister(void)
+{
+ if (!fki_fault_registered)
+ return;
+ unregister_kprobe(&fki_fault_kp);
+ if (fki_die_registered) {
+ unregister_kprobe(&fki_die_kp);
+ fki_die_registered = 0;
+ memset(&fki_die_kp, 0, sizeof(fki_die_kp));
+ fki_die_kp.symbol_name = "die";
+ fki_die_kp.pre_handler = fki_die_pre;
+ }
+ WRITE_ONCE(fki_fault_handler, NULL);
+ fki_fault_registered = 0;
+ memset(&fki_fault_kp, 0, sizeof(fki_fault_kp));
+ fki_fault_kp.symbol_name = "__do_kernel_fault";
+ fki_fault_kp.pre_handler = fki_fault_pre;
+}
+EXPORT_SYMBOL(fki_fault_unregister);
+
+fki_u64 fki_phys_peek(fki_u64 pa)
+{
+ if (!pfn_valid(PHYS_PFN(pa)))
+ return ~0ULL;
+ return READ_ONCE(*(u64 *)phys_to_virt(pa & ~7ULL));
+}
+EXPORT_SYMBOL(fki_phys_peek);
+
+/* ---- contiguous memory and the top foreign window ---- */
+
+static unsigned long carve_base, carve_mb, reserve_mb;
+module_param(carve_base, ulong, 0444);
+module_param(carve_mb, ulong, 0444);
+module_param(reserve_mb, ulong, 0444);
+static struct page *resv_pg;
+static unsigned long resv_cnt;
+static bool resv_used, carve_used;
+
+static void fki_reserve(void)
+{
+ unsigned long cnt = ALIGN(reserve_mb << 20, SZ_2M) >> PAGE_SHIFT;
+
+ if (carve_mb)
+ pr_info("fki: %lu MiB at %#lx for the foreign kernel's DRAM (outside the host's memory)\n", carve_mb, carve_base);
+ if (!reserve_mb || fki_resolve() || !p_cma_area || !*p_cma_area || !p_cma_alloc)
+ return;
+ resv_pg = p_cma_alloc(*p_cma_area, cnt, get_order(SZ_2M), true);
+ if (resv_pg)
+ resv_cnt = cnt;
+ pr_info("fki: %lu MiB for the foreign kernel's DRAM %s\n", reserve_mb, resv_pg ? "reserved" : "NOT reserved (CMA)");
+}
+
+static int fki_carve_check(unsigned long base, unsigned long len)
+{
+ unsigned long end = base + len;
+
+ if (end < base) {
+ pr_err("fki: carve-out [%#lx, %#lx) overflows physical address space\n", base, end);
+ return -EINVAL;
+ }
+ if (p_efi_mem_type && p_efi_mem_type(base) >= 0) {
+ unsigned long a;
+
+ for (a = base; a < end; a += SZ_2M) {
+ int t = p_efi_mem_type(a);
+
+ if (t != EFI_LOADER_CODE && t != EFI_LOADER_DATA && t != EFI_BOOT_SERVICES_CODE &&
+ t != EFI_BOOT_SERVICES_DATA && t != EFI_CONVENTIONAL_MEMORY) {
+ pr_err("fki: carve-out [%#lx, %#lx) is not all RAM (EFI type %d at %#lx); refusing to map (check carve_base, carve_mb and the VM's memory size)\n",
+ base, end, t, a);
+ return -EINVAL;
+ }
+ }
+ }
+ if (p_stext && p_end && p_kimage_voffset) {
+ unsigned long k_start = p_stext - *p_kimage_voffset;
+ unsigned long k_end = p_end - *p_kimage_voffset;
+
+ if (base < k_end && k_start < end) {
+ pr_err("fki: carve-out [%#lx, %#lx) overlaps Linux kernel image [%#lx, %#lx); refusing to map (boot with nokaslr or adjust carve_base)\n",
+ base, end, k_start, k_end);
+ return -EBUSY;
+ }
+ }
+ if (region_intersects(base, len, IORESOURCE_SYSTEM_RAM, IORES_DESC_NONE) != REGION_DISJOINT) {
+ pr_err("fki: carve-out [%#lx, %#lx) overlaps IORESOURCE_SYSTEM_RAM; refusing to map (check mem= and carve_base)\n",
+ base, end);
+ return -EBUSY;
+ }
+ if (region_intersects(base, len, IORESOURCE_MEM, IORES_DESC_NONE) != REGION_DISJOINT) {
+ pr_err("fki: carve-out [%#lx, %#lx) overlaps busy/reserved IORESOURCE_MEM; refusing to map (check /proc/iomem and carve_base)\n",
+ base, end);
+ return -EBUSY;
+ }
+ return 0;
+}
+
+int fki_contig_alloc(unsigned long size, struct fki_region *r)
+{
+ unsigned long n = 1;
+ struct page *pg;
+ int err = fki_resolve();
+
+ if (err)
+ return err;
+ if (carve_mb && !carve_used && ALIGN(size, SZ_2M) <= carve_mb << 20 && !(carve_base & (SZ_2M - 1))) {
+ unsigned long clen = ALIGN(size, SZ_2M);
+ void *va;
+
+ err = fki_carve_check(carve_base, clen);
+ if (err)
+ return err;
+ va = memremap(carve_base, clen, MEMREMAP_WB);
+ if (va) {
+ carve_used = true;
+ r->va = va;
+ r->size = clen;
+ memset(r->va, 0, r->size);
+ r->pa = carve_base;
+ r->handle = (void *)4UL; /* bit 2: the carve-out */
+ return 0;
+ }
+ pr_warn("fki: carve-out at %#lx not mappable\n", carve_base);
+ }
+ if (resv_pg && !resv_used && ALIGN(size, SZ_2M) >> PAGE_SHIFT <= resv_cnt) {
+ resv_used = true;
+ r->va = page_address(resv_pg);
+ r->size = ALIGN(size, SZ_2M);
+ memset(r->va, 0, r->size);
+ r->pa = page_to_phys(resv_pg);
+ r->handle = (void *)((unsigned long)resv_pg | 2); /* bit 1: the reservation, kept when freed */
+ return 0;
+ }
+ if (size >= (64UL << 20) && p_cma_area && *p_cma_area && p_cma_alloc && p_cma_release) {
+ unsigned long cnt = ALIGN(size, SZ_2M) >> PAGE_SHIFT;
+ pg = p_cma_alloc(*p_cma_area, cnt, get_order(SZ_2M), true);
+ if (pg) {
+ r->va = page_address(pg);
+ memset(r->va, 0, cnt << PAGE_SHIFT);
+ r->pa = page_to_phys(pg);
+ r->size = cnt << PAGE_SHIFT;
+ r->handle = (void *)((unsigned long)pg | 1);
+ return 0;
+ }
+ }
+ if (!p_alloc_contig)
+ return -ENOENT;
+ while ((n << PAGE_SHIFT) < size)
+ n <<= 1;
+ pg = p_alloc_contig(n, GFP_KERNEL | __GFP_NOWARN, numa_node_id(), NULL);
+ if (!pg)
+ return -ENOMEM;
+ r->va = page_address(pg);
+ memset(r->va, 0, n << PAGE_SHIFT);
+ r->pa = page_to_phys(pg);
+ r->size = n << PAGE_SHIFT;
+ r->handle = pg;
+ return 0;
+}
+EXPORT_SYMBOL(fki_contig_alloc);
+
+void fki_contig_free(struct fki_region *r)
+{
+ if ((unsigned long)r->handle == 4) {
+ memunmap(r->va);
+ carve_used = false;
+ return;
+ }
+ if ((unsigned long)r->handle & 2) {
+ resv_used = false; /* back to the reservation, for the next run */
+ return;
+ }
+ if ((unsigned long)r->handle & 1) {
+ p_cma_release(*p_cma_area, (struct page *)((unsigned long)r->handle & ~1UL), r->size >> PAGE_SHIFT);
+ return;
+ }
+ if (p_free_contig)
+ p_free_contig(page_to_pfn((struct page *)r->handle), r->size >> PAGE_SHIFT);
+}
+EXPORT_SYMBOL(fki_contig_free);
+
+int fki_window_l1(unsigned long va, unsigned long long **l1_va, fki_u64 *l1_pa)
+{
+ u64 ttbr1 = read_sysreg(ttbr1_el1) & GENMASK_ULL(47, 1);
+ u64 *l0 = phys_to_virt(ttbr1 & ~0xfffULL);
+ u64 e = READ_ONCE(l0[(va >> 39) & 511]);
+
+ if ((e & 3) != 3)
+ return -ENOENT;
+ *l1_pa = e & GENMASK_ULL(47, 12);
+ *l1_va = phys_to_virt(*l1_pa);
+ return 0;
+}
+EXPORT_SYMBOL(fki_window_l1);
+
+void fki_window_set(unsigned long long *slot, fki_u64 desc)
+{
+ WRITE_ONCE(*slot, desc);
+ dsb(ishst);
+ __tlbi(vmalle1is);
+ dsb(ish);
+ isb();
+}
+EXPORT_SYMBOL(fki_window_set);
+
+/* ---- Linux-compliant alternate stack & DAIF preservation ---- */
+
+static void *fki_alt_stack[NR_CPUS];
+#define FKI_ALT_STACK_ORDER get_order(2 * THREAD_SIZE)
+
+asm(
+" .pushsection .text\n"
+" .type fki_run_on_stack, %function\n"
+"fki_run_on_stack:\n"
+" hint #34\n"
+" stp x29, x30, [sp, #-16]!\n"
+" mov x29, sp\n"
+" mov x9, sp\n"
+" mov sp, x2\n"
+" stp x9, xzr, [sp, #-16]!\n"
+" mov x9, x0\n"
+" mov x0, x1\n"
+" blr x9\n"
+" ldp x9, xzr, [sp], #16\n"
+" mov sp, x9\n"
+" ldp x29, x30, [sp], #16\n"
+" ret\n"
+" .size fki_run_on_stack, . - fki_run_on_stack\n"
+" .popsection\n");
+void fki_run_on_stack(void (*fn)(void *), void *arg, void *top);
+
+void fki_arch_linux_runs(void (*fn)(void *), void *arg)
+{
+ unsigned long daif = read_sysreg(daif);
+ unsigned long sp = current_stack_pointer;
+ int cpu = smp_processor_id();
+
+ if (on_task_stack(current, sp, 1))
+ fn(arg);
+ else
+ fki_run_on_stack(fn, arg, (char *)fki_alt_stack[cpu] + THREAD_SIZE);
+ write_sysreg(daif, daif);
+}
+
+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;
+
+ cpu = fki_cpu_map(cpu);
+
+ 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);
+
+/* ---- FKI v1 EL0-host primitives (unsupported on native EL1 arm64) ---- */
+
+int fki_kmem_alloc(unsigned long size, unsigned long high_va, fki_u64 pa_base, struct fki_region *r) { return -EOPNOTSUPP; }
+EXPORT_SYMBOL(fki_kmem_alloc);
+void fki_kmem_free(struct fki_region *r) {}
+EXPORT_SYMBOL(fki_kmem_free);
+int fki_high_map(unsigned long va, fki_u64 xpa, unsigned long size, int prot) { return -EOPNOTSUPP; }
+EXPORT_SYMBOL(fki_high_map);
+void fki_high_unmap(unsigned long va, unsigned long size) {}
+EXPORT_SYMBOL(fki_high_unmap);
+void fki_high_flush(void) {}
+EXPORT_SYMBOL(fki_high_flush);
+int fki_high_txn_begin(unsigned long va, unsigned long size, void **handle_out)
+{
+ if (handle_out)
+ *handle_out = NULL;
+ return -EOPNOTSUPP;
+}
+EXPORT_SYMBOL(fki_high_txn_begin);
+void fki_high_txn_restore(void *txn) {}
+EXPORT_SYMBOL(fki_high_txn_restore);
+void fki_high_txn_end(void *txn) {}
+EXPORT_SYMBOL(fki_high_txn_end);
+int fki_high_read_u64x2(unsigned long va, fki_u64 *out0, fki_u64 *out1)
+{
+ fki_u64 pair[2];
+
+ if (!out0 || !out1 || (va & 7UL) || va < 0xffffff8000000000UL || va > 0xfffffffc00000000UL - sizeof(pair))
+ return -EFAULT;
+ if (copy_from_kernel_nofault(pair, (const void *)va, sizeof(pair)) != 0)
+ return -EFAULT;
+ *out0 = pair[0];
+ *out1 = pair[1];
+ return 0;
+}
+EXPORT_SYMBOL(fki_high_read_u64x2);
+void fki_icache_flush(unsigned long va, unsigned long size)
+{
+ (void)va;
+ (void)size;
+ asm volatile("dsb ish; ic ialluis; dsb ish; isb" ::: "memory");
+}
+EXPORT_SYMBOL(fki_icache_flush);
+
+void *fki_as_create(void) { return NULL; }
+EXPORT_SYMBOL(fki_as_create);
+void fki_as_destroy(void *as) {}
+EXPORT_SYMBOL(fki_as_destroy);
+int fki_as_map(void *as, unsigned long va, fki_u64 xpa, unsigned long size, int prot) { return -EOPNOTSUPP; }
+EXPORT_SYMBOL(fki_as_map);
+void fki_as_unmap(void *as, unsigned long va, unsigned long size) {}
+EXPORT_SYMBOL(fki_as_unmap);
+void fki_as_flush(void *as) {}
+EXPORT_SYMBOL(fki_as_flush);
+
+void *fki_utcb_create(void *as) { return NULL; }
+EXPORT_SYMBOL(fki_utcb_create);
+void fki_utcb_destroy(void *utcb) {}
+EXPORT_SYMBOL(fki_utcb_destroy);
+int fki_utcb_set_as(void *utcb, void *as) { return -EOPNOTSUPP; }
+EXPORT_SYMBOL(fki_utcb_set_as);
+int fki_utcb_set_pac(void *utcb, const struct fki_pac_keys *keys) { return -EOPNOTSUPP; }
+EXPORT_SYMBOL(fki_utcb_set_pac);
+int fki_utcb_run(void *utcb, struct fki_utcb_regs *regs, struct fki_utcb_stop *stop) { return -EOPNOTSUPP; }
+EXPORT_SYMBOL(fki_utcb_run);
+int fki_utcb_resume(void *utcb, struct fki_utcb_regs *regs, struct fki_utcb_stop *stop) { return -ENOSYS; }
+EXPORT_SYMBOL(fki_utcb_resume);
+int fki_utcb_sync_regs(void *utcb, struct fki_utcb_regs *regs) { return -ENOSYS; }
+EXPORT_SYMBOL(fki_utcb_sync_regs);
+int fki_utcb_fpu_read(void *utcb, void *buf, unsigned long len) { return -EOPNOTSUPP; }
+EXPORT_SYMBOL(fki_utcb_fpu_read);
+int fki_utcb_fpu_write(void *utcb, const void *buf, unsigned long len) { return -EOPNOTSUPP; }
+EXPORT_SYMBOL(fki_utcb_fpu_write);
+
+/* ---- arch init / exit ---- */
+
+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;
+ }
+}
+
+int fki_arch_init(void)
+{
+ int 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);
+ }
+ fki_reserve();
+ return 0;
+}
+
+void fki_arch_exit(void)
+{
+ if (resv_pg && !resv_used)
+ p_cma_release(*p_cma_area, resv_pg, resv_cnt);
+ fki_free_alt_stacks();
+}
diff --git a/fki-ko/fki_common.c b/fki-ko/fki_common.c
new file mode 100644
index 0000000..3598b19
--- /dev/null
+++ b/fki-ko/fki_common.c
@@ -0,0 +1,546 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * Foreign kernel interface, version 1 (architecture-independent core).
+ * See fki.h.
+ *
+ * Exports are plain EXPORT_SYMBOL on purpose: this file defines a narrow,
+ * stable, semantic interface of its own, and nothing behind it is
+ * re-exported.
+ */
+#include "fki.h"
+#include "fki_internal.h"
+#include <linux/cpumask.h>
+#include <linux/delay.h>
+#include <linux/err.h>
+#include <linux/etherdevice.h>
+#include <linux/firmware.h>
+#include <linux/fs.h>
+#include <linux/hrtimer.h>
+#include <linux/irqflags.h>
+#include <linux/kthread.h>
+#include <linux/math64.h>
+#include <linux/mm.h>
+#include <linux/module.h>
+#include <linux/netdevice.h>
+#include <linux/preempt.h>
+#include <linux/printk.h>
+#include <linux/random.h>
+#include <linux/sched.h>
+#include <linux/skbuff.h>
+#include <linux/slab.h>
+#include <linux/smp.h>
+#include <linux/timekeeping.h>
+
+int fki_version(void)
+{
+ return FKI_VERSION;
+}
+EXPORT_SYMBOL(fki_version);
+
+void fki_log(const char *s, unsigned long len)
+{
+ pr_info("fki: %.*s\n", (int)len, s);
+}
+EXPORT_SYMBOL(fki_log);
+
+/* what an operator must see even with the console quiet (an XNU panic, a CPU gone silent): KERN_ALERT */
+void fki_log_alert(const char *s, unsigned long len)
+{
+ pr_alert("fki: %.*s\n", (int)len, s);
+}
+EXPORT_SYMBOL(fki_log_alert);
+
+int fki_blob_get(const char *name, const void **data, unsigned long *size, void **handle)
+{
+ const struct firmware *fw;
+ int err = request_firmware(&fw, name, NULL);
+
+ if (err)
+ return err;
+ *data = fw->data;
+ *size = fw->size;
+ *handle = (void *)fw;
+ return 0;
+}
+EXPORT_SYMBOL(fki_blob_get);
+
+void fki_blob_put(void *handle)
+{
+ release_firmware(handle);
+}
+EXPORT_SYMBOL(fki_blob_put);
+
+void fki_random(void *buf, unsigned long len)
+{
+ get_random_bytes(buf, len);
+}
+EXPORT_SYMBOL(fki_random);
+
+int fki_random_wait(void)
+{
+ return wait_for_random_bytes();
+}
+EXPORT_SYMBOL(fki_random_wait);
+
+static int cpu_list[NR_CPUS];
+static int cpu_list_n;
+module_param_array(cpu_list, int, &cpu_list_n, 0444);
+
+int fki_cpu_map(int cpu)
+{
+ if (!cpu_list_n)
+ return cpu;
+ return cpu >= 0 && cpu < cpu_list_n ? cpu_list[cpu] : -1;
+}
+
+int fki_bind_cpu(int cpu)
+{
+ cpu = fki_cpu_map(cpu);
+ if (cpu < 0 || cpu >= nr_cpu_ids || !cpu_online(cpu))
+ return -EINVAL;
+ return set_cpus_allowed_ptr(current, cpumask_of(cpu));
+}
+EXPORT_SYMBOL(fki_bind_cpu);
+
+int fki_num_cpus(void)
+{
+ return cpu_list_n ? cpu_list_n : num_online_cpus();
+}
+EXPORT_SYMBOL(fki_num_cpus);
+
+void *fki_thread_start(int (*fn)(void *), void *arg, int cpu, const char *name)
+{
+ struct task_struct *t;
+
+ cpu = fki_cpu_map(cpu);
+ if (cpu < 0 || cpu >= nr_cpu_ids || !cpu_online(cpu))
+ return NULL;
+ t = kthread_create(fn, arg, "%s", name);
+ if (IS_ERR(t))
+ return NULL;
+ kthread_bind(t, cpu);
+ get_task_struct(t);
+ wake_up_process(t);
+ return t;
+}
+EXPORT_SYMBOL(fki_thread_start);
+
+void fki_thread_stop(void *thread)
+{
+ if (thread) {
+ kthread_stop(thread);
+ put_task_struct(thread);
+ }
+}
+EXPORT_SYMBOL(fki_thread_stop);
+
+int fki_thread_should_stop(void)
+{
+ return kthread_should_stop();
+}
+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)
+{
+ unsigned long t = msecs_to_jiffies(ms) + 1;
+
+ while (t)
+ t = schedule_timeout_idle(t);
+}
+EXPORT_SYMBOL(fki_msleep);
+
+/* ---- running Linux from inside fki_enter() ---- */
+
+struct fki_runs {
+ void (*fn)(void *);
+ void *arg;
+};
+
+/* fn runs with interrupts on and turns them off again; then, before the foreign kernel resumes, fki_fpsimd_forget */
+static void fki_runs_then_forget(void *p)
+{
+ struct fki_runs *r = p;
+
+ r->fn(r->arg);
+ local_irq_enable();
+ fki_fpsimd_forget();
+ local_irq_disable();
+}
+
+static void fki_linux_runs(void (*fn)(void *), void *arg)
+{
+ struct fki_runs r = { fn, arg };
+
+ fki_arch_linux_runs(fki_runs_then_forget, &r);
+}
+
+void fki_linux_runs_ext(void (*fn)(void *), void *arg)
+{
+ fki_linux_runs(fn, arg);
+}
+
+struct fki_idle_args { fki_u64 ns; const volatile unsigned int *wake; };
+
+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)
+{
+ struct fki_idle_args *a = p;
+ ktime_t t = ns_to_ktime(a->ns);
+
+ local_irq_enable();
+ preempt_enable();
+ set_current_state(TASK_IDLE);
+ 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();
+}
+
+static void fki_yield_body(void *p)
+{
+ local_irq_enable();
+ preempt_enable();
+ cond_resched();
+ preempt_disable();
+ local_irq_disable();
+}
+
+void fki_idle_until(fki_u64 counter_deadline, fki_u64 max_ns, const volatile unsigned int *wake)
+{
+ u64 now = fki_counter(), freq = fki_counter_frequency(), ns;
+ struct fki_idle_args a;
+
+ if (counter_deadline <= now) {
+ /* already due: still let Linux take its interrupts and reschedule (an idle loop that never sleeps starves it) */
+ fki_linux_runs(fki_yield_body, NULL);
+ return;
+ }
+ ns = div64_u64((counter_deadline - now) * 1000000ULL, freq) * 1000ULL;
+ 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);
+
+void fki_yield(void)
+{
+ fki_linux_runs(fki_yield_body, NULL);
+}
+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 atomic_t fki_kick_claimed[NR_CPUS];
+static void fki_kick_fn(void *unused) { atomic_set_release(&fki_kick_claimed[smp_processor_id()], 0); }
+static DEFINE_PER_CPU(call_single_data_t, fki_kick_csd);
+
+void fki_kick_cpu(int cpu)
+{
+ struct task_struct *t;
+
+ cpu = fki_cpu_map(cpu);
+ 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() && atomic_cmpxchg_acquire(&fki_kick_claimed[cpu], 0, 1) == 0) {
+ /* irq_work_queue_on is not exported; an IPI already on its way (claimed) is just as good */
+ if (smp_call_function_single_async(cpu, per_cpu_ptr(&fki_kick_csd, cpu)))
+ atomic_set_release(&fki_kick_claimed[cpu], 0);
+ }
+}
+EXPORT_SYMBOL(fki_kick_cpu);
+
+void fki_realtime(fki_u64 *sec, fki_u64 *nsec)
+{
+ struct timespec64 ts;
+
+ ktime_get_real_ts64(&ts);
+ *sec = ts.tv_sec;
+ *nsec = ts.tv_nsec;
+}
+EXPORT_SYMBOL(fki_realtime);
+
+/*
+ * A virtual Ethernet link to the foreign kernel: the Linux netdev "xnu0". What Linux transmits on xnu0 is queued for
+ * the foreign kernel (fki_net_recv); what the foreign kernel sends (fki_net_send) arrives on xnu0 as received frames.
+ */
+#define FKI_NET_QLEN 1024
+static struct net_device *fki_netdev;
+static struct sk_buff_head fki_net_rxq; /* Linux -> foreign */
+
+static netdev_tx_t fki_net_xmit(struct sk_buff *skb, struct net_device *dev)
+{
+ struct task_struct *t;
+
+ if (skb_queue_len(&fki_net_rxq) >= FKI_NET_QLEN) {
+ dev->stats.tx_dropped++;
+ dev_kfree_skb_any(skb);
+ return NETDEV_TX_OK;
+ }
+ dev->stats.tx_packets++;
+ dev->stats.tx_bytes += skb->len;
+ skb_queue_tail(&fki_net_rxq, skb);
+ t = READ_ONCE(fki_idle_task[0]);
+ if (t)
+ wake_up_process(t); /* the foreign kernel's first CPU is idle: let it see the frame now */
+ return NETDEV_TX_OK;
+}
+
+static int fki_net_up(struct net_device *dev) { netif_start_queue(dev); return 0; }
+static int fki_net_down(struct net_device *dev) { netif_stop_queue(dev); return 0; }
+
+static const struct net_device_ops fki_net_ops = {
+ .ndo_open = fki_net_up,
+ .ndo_stop = fki_net_down,
+ .ndo_start_xmit = fki_net_xmit,
+ .ndo_set_mac_address = eth_mac_addr,
+ .ndo_validate_addr = eth_validate_addr,
+};
+
+struct fki_net_io { const void *in; void *out; unsigned long len; long result; };
+
+static void fki_net_send_body(void *p)
+{
+ struct fki_net_io *io = p;
+ struct sk_buff *skb;
+
+ io->result = -ENODEV;
+ if (!fki_netdev || io->len < ETH_HLEN || io->len > ETH_FRAME_LEN + 4)
+ return;
+ skb = netdev_alloc_skb(fki_netdev, io->len + NET_IP_ALIGN);
+ if (!skb) {
+ fki_netdev->stats.rx_dropped++;
+ io->result = -ENOMEM;
+ return;
+ }
+ skb_reserve(skb, NET_IP_ALIGN);
+ skb_put_data(skb, io->in, io->len);
+ skb->protocol = eth_type_trans(skb, fki_netdev);
+ fki_netdev->stats.rx_packets++;
+ fki_netdev->stats.rx_bytes += io->len;
+ local_irq_enable(); /* netif_rx re-enables bottom halves, which must not happen with interrupts off */
+ netif_rx(skb);
+ local_irq_disable();
+ io->result = io->len;
+}
+
+long fki_net_send(const void *frame, unsigned long len)
+{
+ struct fki_net_io io = { .in = frame, .len = len };
+
+ fki_linux_runs(fki_net_send_body, &io);
+ return io.result;
+}
+EXPORT_SYMBOL(fki_net_send);
+
+static void fki_net_recv_body(void *p)
+{
+ struct fki_net_io *io = p;
+ struct sk_buff *skb = skb_dequeue(&fki_net_rxq);
+
+ io->result = 0;
+ if (!skb)
+ return;
+ if (skb->len > io->len) {
+ io->result = -EMSGSIZE;
+ } else if (skb_copy_bits(skb, 0, io->out, skb->len) == 0) {
+ io->result = skb->len;
+ } else {
+ io->result = -EIO;
+ }
+ dev_consume_skb_any(skb);
+}
+
+long fki_net_recv(void *buf, unsigned long len)
+{
+ struct fki_net_io io = { .out = buf, .len = len };
+
+ fki_linux_runs(fki_net_recv_body, &io);
+ return io.result;
+}
+EXPORT_SYMBOL(fki_net_recv);
+
+long fki_net_pending(void)
+{
+ return skb_queue_len(&fki_net_rxq);
+}
+EXPORT_SYMBOL(fki_net_pending);
+
+/* ---- host file backing store ---- */
+
+void *fki_file_open(const char *path, int writable, fki_u64 *size)
+{
+ struct file *f = filp_open(path, (writable ? O_RDWR : O_RDONLY) | O_LARGEFILE, 0);
+
+ if (IS_ERR(f))
+ return NULL;
+ if (size) /* the mapping's host: a block device's own size (a device node's inode says 0) */
+ *size = i_size_read(f->f_mapping->host);
+ return f;
+}
+EXPORT_SYMBOL(fki_file_open);
+
+#define FKI_FILE_CHUNK (256UL << 10)
+
+static long fki_file_rw_body(void *file, int write, void *buf, unsigned long len, fki_u64 off);
+struct fki_file_args { void *file; int write; void *buf; unsigned long len; fki_u64 off; long ret; };
+static void fki_file_rw_thunk(void *p)
+{
+ struct fki_file_args *a = p;
+ a->ret = fki_file_rw_body(a->file, a->write, a->buf, a->len, a->off);
+}
+
+long fki_file_rw(void *file, int write, void *buf, unsigned long len, fki_u64 off)
+{
+ struct fki_file_args a = { file, write, buf, len, off, -EIO };
+
+ if (!file)
+ return -EBADF;
+ fki_linux_runs(fki_file_rw_thunk, &a);
+ return a.ret;
+}
+EXPORT_SYMBOL(fki_file_rw);
+
+static long fki_file_rw_body(void *file, int write, void *buf, unsigned long len, fki_u64 off)
+{
+ struct file *f = file;
+ unsigned long done = 0;
+ long ret = 0;
+ void *bounce;
+
+ local_irq_enable();
+ preempt_enable();
+ bounce = kvmalloc(min(len, FKI_FILE_CHUNK), GFP_KERNEL);
+ if (!bounce)
+ ret = -ENOMEM;
+ while (bounce && done < len) {
+ unsigned long n = min(len - done, FKI_FILE_CHUNK);
+ loff_t pos = off + done;
+ ssize_t r;
+
+ if (write) {
+ preempt_disable(); local_irq_disable();
+ memcpy(bounce, (char *)buf + done, n);
+ local_irq_enable(); preempt_enable();
+ r = kernel_write(f, bounce, n, &pos);
+ } else {
+ r = kernel_read(f, bounce, n, &pos);
+ if (r > 0) {
+ preempt_disable(); local_irq_disable();
+ memcpy((char *)buf + done, bounce, r);
+ local_irq_enable(); preempt_enable();
+ }
+ }
+ if (r < 0) {
+ ret = r;
+ break;
+ }
+ done += r;
+ if ((unsigned long)r < n)
+ break;
+ }
+ kvfree(bounce);
+ preempt_disable();
+ local_irq_disable();
+ return ret < 0 && !done ? ret : (long)done;
+}
+
+long fki_file_pwrite(void *file, const void *buf, unsigned long len, fki_u64 off)
+{
+ loff_t pos = off;
+
+ if (!file)
+ return -EBADF;
+ return kernel_write(file, buf, len, &pos);
+}
+EXPORT_SYMBOL(fki_file_pwrite);
+
+void fki_file_close(void *file)
+{
+ if (file)
+ filp_close(file, NULL);
+}
+EXPORT_SYMBOL(fki_file_close);
+
+/* ---- module init / exit ---- */
+
+static int __init fki_init(void)
+{
+ struct net_device *dev;
+ int err, cpu;
+
+ for_each_possible_cpu(cpu)
+ INIT_CSD(per_cpu_ptr(&fki_kick_csd, cpu), fki_kick_fn, NULL);
+ err = fki_arch_init();
+ if (err)
+ return err;
+ skb_queue_head_init(&fki_net_rxq);
+ err = fki_hostcall_init();
+ if (err)
+ pr_warn("fki: no /dev/xnu-hostcall (%d)\n", err);
+ dev = alloc_etherdev(0);
+ if (!dev)
+ return 0; /* no link; the rest of fki still works */
+ strscpy(dev->name, "xnu0", IFNAMSIZ);
+ dev->netdev_ops = &fki_net_ops;
+ eth_hw_addr_random(dev);
+ dev->min_mtu = 68;
+ dev->max_mtu = ETH_DATA_LEN;
+ err = register_netdev(dev);
+ if (err) {
+ free_netdev(dev);
+ pr_warn("fki: no xnu0 link (%d)\n", err);
+ return 0;
+ }
+ fki_netdev = dev;
+ return 0;
+}
+
+static void __exit fki_exit(void)
+{
+ fki_hostcall_exit();
+ if (fki_netdev) {
+ unregister_netdev(fki_netdev);
+ free_netdev(fki_netdev);
+ fki_netdev = NULL;
+ }
+ skb_queue_purge(&fki_net_rxq);
+ fki_arch_exit();
+}
+module_init(fki_init);
+module_exit(fki_exit);
+
+MODULE_LICENSE("GPL");
+MODULE_DESCRIPTION("Foreign kernel interface v1");
diff --git a/fki-ko/fki_internal.h b/fki-ko/fki_internal.h
index 6410aba..a505df5 100644
--- a/fki-ko/fki_internal.h
+++ b/fki-ko/fki_internal.h
@@ -2,8 +2,17 @@
/* Shared between fki's own files (not part of the interface in fki.h). */
#ifndef FKI_INTERNAL_H
#define FKI_INTERNAL_H
+
/* Run fn(arg) where Linux may run it (a Linux-compliant stack), keeping the caller's exception mask. */
void fki_linux_runs_ext(void (*fn)(void *), void *arg);
+
+/* Architecture backend hooks (fki_arm64.c / fki_l4h.c). */
+int fki_arch_init(void);
+void fki_arch_exit(void);
+void fki_arch_linux_runs(void (*fn)(void *), void *arg);
+void fki_fpsimd_forget(void);
+
+int fki_cpu_map(int cpu);
int fki_hostcall_init(void);
void fki_hostcall_exit(void);
#endif
diff --git a/fki-ko/fki_l4h.c b/fki-ko/fki_l4h.c
new file mode 100644
index 0000000..2ff724f
--- /dev/null
+++ b/fki-ko/fki_l4h.c
@@ -0,0 +1,2450 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * Foreign kernel interface, version 1: L4H AArch64 (EL0) backend.
+ */
+#include "fki.h"
+#include "fki_internal.h"
+#include <linux/atomic.h>
+#include <linux/completion.h>
+#include <linux/errno.h>
+#include <linux/gfp.h>
+#include <linux/io.h>
+#include <linux/irqflags.h>
+#include <linux/list.h>
+#include <linux/minmax.h>
+#include <linux/mm.h>
+#include <linux/module.h>
+#include <linux/mutex.h>
+#include <linux/overflow.h>
+#include <linux/percpu-refcount.h>
+#include <linux/preempt.h>
+#include <linux/printk.h>
+#include <linux/rcupdate.h>
+#include <linux/refcount.h>
+#include <linux/sched.h>
+#include <linux/slab.h>
+#include <linux/smp.h>
+#include <linux/spinlock.h>
+#include <linux/string.h>
+#include <linux/xarray.h>
+#include <asm/neon.h>
+#include <l4h_sys.h>
+#include <l4h_caps.h>
+#include <l4h_vspace.h>
+#include <l4h/provider-registers.h>
+
+#define FKI_L4H_ERR_ILLEGAL_OP 3
+#define FKI_L4H_REGION_VA 0xffffffe000000000ULL
+#define FKI_L4H_REGION_PA 0x800000000ULL
+
+/* SCTLR_EL1 PAC enable bit positions (ABI of struct fki_pac_keys.sctlr_en). */
+#define FKI_SCTLR_ENIA (1ULL << 31)
+#define FKI_SCTLR_ENIB (1ULL << 30)
+#define FKI_SCTLR_ENDA (1ULL << 27)
+#define FKI_SCTLR_ENDB (1ULL << 13)
+
+static DEFINE_PER_CPU(struct fki_pac_keys, l4h_cur_pac);
+static DEFINE_PER_CPU(struct fki_pac_keys, l4h_hw_pac);
+static DEFINE_PER_CPU(bool, l4h_hw_pac_valid);
+static DEFINE_PER_CPU(struct l4h_uctx *, fki_cur_utcb);
+
+static void fki_utcb_release_sc(void)
+{
+ struct l4h_uctx *u = this_cpu_read(fki_cur_utcb);
+
+ if (u) {
+ if (u->sc_vcpu >= 0)
+ l4h_user_deschedule(u);
+ this_cpu_write(fki_cur_utcb, NULL);
+ }
+}
+
+unsigned long fki_caps(void)
+{
+ unsigned long features = l4h_provider_features();
+ unsigned long caps = FKI_CAP_EL0;
+
+ if ((features & L4H_PROVIDER_ARM_HIGH_VSPACE) &&
+ (l4h_bootinfo->flags & L4H_BOOT_HIGH_VSPACE))
+ caps |= FKI_CAP_HIGH_WINDOW;
+ if (features & L4H_PROVIDER_ARM_PAC)
+ caps |= FKI_CAP_PAC;
+ return caps;
+}
+EXPORT_SYMBOL(fki_caps);
+
+int fki_cpu_id(void)
+{
+ return smp_processor_id();
+}
+EXPORT_SYMBOL(fki_cpu_id);
+
+int fki_cpu_mpidr(int cpu, fki_u64 *mpidr)
+{
+ cpu = fki_cpu_map(cpu);
+ if (cpu < 0 || cpu >= nr_cpu_ids || !cpu_online(cpu))
+ return -EINVAL;
+ /* Encodes Aff1:Aff0 so LINUX64_CPU_SLOT(mpidr) == cpu. */
+ *mpidr = ((u64)(cpu & 0xf)) | (((u64)((cpu >> 4) & 0xf)) << 8);
+ return 0;
+}
+EXPORT_SYMBOL(fki_cpu_mpidr);
+
+fki_u64 fki_counter_frequency(void)
+{
+ u64 v;
+
+ asm volatile("mrs %0, cntfrq_el0" : "=r"(v));
+ return v;
+}
+EXPORT_SYMBOL(fki_counter_frequency);
+
+fki_u64 fki_counter(void)
+{
+ u64 v;
+
+ asm volatile("isb\n\tmrs %0, cntvct_el0" : "=r"(v));
+ return v;
+}
+EXPORT_SYMBOL(fki_counter);
+
+void fki_fpsimd_forget(void)
+{
+ if (l4h_neon_usable()) {
+ kernel_neon_begin();
+ kernel_neon_end();
+ }
+}
+
+static unsigned long sctlr_to_l4h_pac_en(fki_u64 sctlr_en)
+{
+ unsigned long en = 0;
+
+ if (sctlr_en & FKI_SCTLR_ENIA)
+ en |= L4H_PAC_EN_IA;
+ if (sctlr_en & FKI_SCTLR_ENIB)
+ en |= L4H_PAC_EN_IB;
+ if (sctlr_en & FKI_SCTLR_ENDA)
+ en |= L4H_PAC_EN_DA;
+ if (sctlr_en & FKI_SCTLR_ENDB)
+ en |= L4H_PAC_EN_DB;
+ return en;
+}
+
+static int keys_apply(const struct fki_pac_keys *k, bool force_disable)
+{
+ unsigned long words[L4H_PAC_KEY_WORDS];
+ unsigned long en;
+ int err;
+
+ en = sctlr_to_l4h_pac_en(k->sctlr_en);
+ if (!(l4h_provider_features() & L4H_PROVIDER_ARM_PAC)) {
+ if (en)
+ return -EOPNOTSUPP;
+ *this_cpu_ptr(&l4h_cur_pac) = *k;
+ return 0;
+ }
+ if (!en && !force_disable && !IS_ENABLED(CONFIG_ARM64_PTR_AUTH_KERNEL)) {
+ *this_cpu_ptr(&l4h_cur_pac) = *k;
+ return 0;
+ }
+ if (*this_cpu_ptr(&l4h_hw_pac_valid) &&
+ memcmp(this_cpu_ptr(&l4h_hw_pac), k, sizeof(*k)) == 0) {
+ *this_cpu_ptr(&l4h_cur_pac) = *k;
+ return 0;
+ }
+ if (en) {
+ words[0] = k->ia[0]; words[1] = k->ia[1];
+ words[2] = k->ib[0]; words[3] = k->ib[1];
+ words[4] = k->da[0]; words[5] = k->da[1];
+ words[6] = k->db[0]; words[7] = k->db[1];
+ words[8] = k->ga[0]; words[9] = k->ga[1];
+ }
+ err = l4h_tcb_set_pac(0, en, en ? words : NULL);
+ if (err == FKI_L4H_ERR_ILLEGAL_OP) {
+ pr_err_ratelimited("fki: l4h_tcb_set_pac illegal op despite L4H_PROVIDER_ARM_PAC\n");
+ return -EOPNOTSUPP;
+ }
+ if (err) {
+ pr_err_ratelimited("fki: l4h_tcb_set_pac failed: %d\n", err);
+ return -EIO;
+ }
+ *this_cpu_ptr(&l4h_hw_pac) = *k;
+ *this_cpu_ptr(&l4h_hw_pac_valid) = true;
+ *this_cpu_ptr(&l4h_cur_pac) = *k;
+ return 0;
+}
+
+unsigned long fki_enter(const struct fki_pac_keys *foreign, struct fki_pac_keys *saved)
+{
+ unsigned long flags;
+ int err;
+
+ fki_fpsimd_forget();
+ preempt_disable();
+ local_irq_save(flags);
+ *saved = *this_cpu_ptr(&l4h_cur_pac);
+ err = keys_apply(foreign, false);
+ BUG_ON(err);
+ return flags;
+}
+EXPORT_SYMBOL(fki_enter);
+
+void fki_leave(unsigned long cookie, const struct fki_pac_keys *saved)
+{
+ int err;
+
+ fki_utcb_release_sc();
+ err = keys_apply(saved, true);
+ BUG_ON(err);
+ local_irq_restore(cookie);
+ preempt_enable();
+}
+EXPORT_SYMBOL(fki_leave);
+
+int fki_pac_swap(const struct fki_pac_keys *load, struct fki_pac_keys *save)
+{
+ *save = *this_cpu_ptr(&l4h_cur_pac);
+ return keys_apply(load, false);
+}
+EXPORT_SYMBOL(fki_pac_swap);
+
+/* ---- alternate stack for Linux calls from hosted kernel stacks ---- */
+
+static void *fki_alt_stack[NR_CPUS];
+#define FKI_ALT_STACK_ORDER get_order(2 * THREAD_SIZE)
+
+asm(
+" .pushsection .text\n"
+" .type fki_run_on_stack, %function\n"
+"fki_run_on_stack:\n"
+" stp x29, x30, [sp, #-16]!\n"
+" mov x29, sp\n"
+" mov x9, sp\n"
+" mov sp, x2\n"
+" stp x9, xzr, [sp, #-16]!\n"
+" mov x9, x0\n"
+" mov x0, x1\n"
+" blr x9\n"
+" ldp x9, xzr, [sp], #16\n"
+" mov sp, x9\n"
+" ldp x29, x30, [sp], #16\n"
+" ret\n"
+" .size fki_run_on_stack, . - fki_run_on_stack\n"
+" .popsection\n");
+void fki_run_on_stack(void (*fn)(void *), void *arg, void *top);
+
+void fki_arch_linux_runs(void (*fn)(void *), void *arg)
+{
+ unsigned long sp;
+ int cpu = smp_processor_id();
+
+ fki_utcb_release_sc();
+ asm volatile("mov %0, sp" : "=r"(sp));
+ if (sp >= 0xffffffe000000000ULL && fki_alt_stack[cpu])
+ fki_run_on_stack(fn, arg, (char *)fki_alt_stack[cpu] + THREAD_SIZE);
+ else
+ fn(arg);
+}
+
+/* ---- high-window kernel memory & dynamic 4 KiB mappings ---- */
+
+struct fki_pt_node {
+ struct list_head list;
+ struct l4h_obj pt;
+};
+
+struct fki_kmem_chunk {
+ bool is_large;
+ struct page *large_pg;
+ unsigned long large_gpa;
+ unsigned long large_slot;
+ struct page **small_pgs; /* 512 entries when !is_large */
+ unsigned long *small_slots; /* 512 entries when !is_large */
+};
+
+#define FKI_AS_SLOT_BITS 30
+#define FKI_AS_SLOT_MASK ((1UL << FKI_AS_SLOT_BITS) - 1)
+#define FKI_AS_PROT_SHIFT FKI_AS_SLOT_BITS
+#define FKI_AS_PROT_MASK 7UL
+#define FKI_AS_PFN_SHIFT (FKI_AS_SLOT_BITS + 3)
+
+static inline unsigned long fki_eff_prot(int lprot)
+{
+ lprot &= FKI_AS_PROT_MASK;
+ return (lprot & L4H_PROT_WRITE) ? (lprot | L4H_PROT_READ) : lprot;
+}
+
+static inline void *fki_as_mk_entry(unsigned long cptr, unsigned long pfn, unsigned long lprot)
+{
+ return xa_mk_value((pfn << FKI_AS_PFN_SHIFT) |
+ ((lprot & FKI_AS_PROT_MASK) << FKI_AS_PROT_SHIFT) |
+ (cptr & FKI_AS_SLOT_MASK));
+}
+
+static inline unsigned long fki_as_entry_cptr(void *e)
+{
+ return xa_to_value(e) & FKI_AS_SLOT_MASK;
+}
+
+static inline unsigned long fki_as_entry_pfn(void *e)
+{
+ return xa_to_value(e) >> FKI_AS_PFN_SHIFT;
+}
+
+static inline unsigned long fki_as_entry_prot(void *e)
+{
+ return (xa_to_value(e) >> FKI_AS_PROT_SHIFT) & FKI_AS_PROT_MASK;
+}
+
+struct fki_high_txn_page {
+ unsigned long cptr;
+ unsigned long pfn;
+ u8 prot;
+ bool stashed;
+};
+
+struct fki_high_txn {
+ struct list_head list;
+ struct fki_kmem *km;
+ unsigned long va;
+ unsigned long size;
+ unsigned long npages;
+ bool restoring;
+ struct fki_high_txn_page pages[];
+};
+
+struct fki_kmem {
+ unsigned long high_va;
+ fki_u64 pa_base;
+ unsigned long size;
+ unsigned long nchunks;
+ struct fki_kmem_chunk *chunks;
+ struct list_head pts;
+ struct list_head as_list; /* protected by fki_vs_lock */
+ struct list_head high_txns; /* protected by km->lock */
+ struct xarray dyn_slots; /* (va >> PAGE_SHIFT) -> fki_as_mk_entry(cptr, pfn, lprot) */
+ struct xarray pt_ready; /* (va >> 21) -> xa_mk_value(1) when L1..L3 PTs exist */
+ spinlock_t lock;
+ struct percpu_ref ops_ref;
+ struct completion ops_zero;
+ bool ops_ref_inited;
+ bool dead;
+};
+
+static struct fki_kmem __rcu *active_kmem;
+static DEFINE_MUTEX(fki_kmem_mutex);
+
+static void fki_kmem_ops_release(struct percpu_ref *ref)
+{
+ struct fki_kmem *km = container_of(ref, struct fki_kmem, ops_ref);
+
+ complete(&km->ops_zero);
+}
+
+static struct fki_kmem *fki_kmem_get(void)
+{
+ struct fki_kmem *km;
+
+ rcu_read_lock();
+ km = rcu_dereference(active_kmem);
+ if (!km || READ_ONCE(km->dead) || !percpu_ref_tryget_live(&km->ops_ref))
+ km = NULL;
+ rcu_read_unlock();
+ return km;
+}
+
+static void fki_kmem_put(struct fki_kmem *km)
+{
+ if (km)
+ percpu_ref_put(&km->ops_ref);
+}
+
+static int fki_vs_pool_init(void);
+static void fki_vs_pool_fini(void);
+
+struct fki_bind_ctx {
+ unsigned long vs;
+ int errs[NR_CPUS];
+};
+
+static void bind_high_vspace_cpu(void *arg)
+{
+ struct fki_bind_ctx *ctx = arg;
+ int cpu = smp_processor_id();
+ int err = l4h_tcb_set_high_vspace(0, ctx->vs);
+
+ if (cpu < NR_CPUS)
+ ctx->errs[cpu] = err;
+ if (err)
+ pr_err("fki: cpu %d: l4h_tcb_set_high_vspace(%#lx) failed: %d\n",
+ cpu, ctx->vs, err);
+}
+
+static int map_high_frame(struct fki_kmem *km, unsigned long frame_slot,
+ unsigned long va, int prot)
+{
+ unsigned long high_vs = L4H_CPTR(L4H_SLOT_HIGH_VSPACE);
+ int err;
+
+ while ((err = l4h_page_map(frame_slot, high_vs, va, prot)) == L4H_ERR_FAILED_LOOKUP) {
+ struct fki_pt_node *node = kzalloc(sizeof(*node), GFP_ATOMIC);
+
+ if (!node)
+ return -ENOMEM;
+ if (l4h_obj_alloc(L4H_OBJ_PT, 0, &node->pt)) {
+ kfree(node);
+ return -ENOMEM;
+ }
+ err = l4h_pt_map(L4H_OBJ_PT, node->pt.cptr, high_vs, va);
+ if (err) {
+ l4h_obj_free(&node->pt);
+ kfree(node);
+ return -EIO;
+ }
+ list_add(&node->list, &km->pts);
+ }
+ if (err)
+ return -EIO;
+ /* Leaf 4 KiB mapping succeeded: leaf PT for this 2 MiB block is proven present. */
+ if (!(prot & L4H_PROT_LARGE))
+ (void)xa_store(&km->pt_ready, va >> 21, xa_mk_value(1), GFP_ATOMIC);
+ return 0;
+}
+
+static int xpa_to_gpa(struct fki_kmem *km, fki_u64 xpa, unsigned long *gpa_out)
+{
+ unsigned long off, ci, coff;
+ fki_u64 pa_end;
+ struct fki_kmem_chunk *ch;
+
+ if (!km || check_add_overflow(km->pa_base, (fki_u64)km->size, &pa_end))
+ return -EINVAL;
+ if (xpa < km->pa_base || xpa >= pa_end)
+ return -EINVAL;
+ off = (unsigned long)(xpa - km->pa_base);
+ ci = off >> 21;
+ if (ci >= km->nchunks)
+ return -EINVAL;
+ coff = off & (SZ_2M - 1);
+ ch = &km->chunks[ci];
+ if (ch->is_large) {
+ *gpa_out = ch->large_gpa + coff;
+ return 0;
+ }
+ *gpa_out = page_to_phys(ch->small_pgs[coff >> PAGE_SHIFT]) + (coff & ~PAGE_MASK);
+ return 0;
+}
+
+static void kmem_cleanup(struct fki_kmem *km)
+{
+ struct fki_pt_node *node, *tmp;
+ unsigned long idx;
+ void *entry;
+ unsigned long i, j;
+
+ if (!km)
+ return;
+ xa_for_each(&km->dyn_slots, idx, entry) {
+ unsigned long slot = fki_as_entry_cptr(entry);
+
+ if (slot)
+ l4h_slot_delete(slot);
+ }
+ xa_destroy(&km->dyn_slots);
+ xa_destroy(&km->pt_ready);
+
+ if (km->chunks) {
+ for (i = 0; i < km->nchunks; i++) {
+ struct fki_kmem_chunk *ch = &km->chunks[i];
+
+ if (ch->is_large) {
+ if (ch->large_slot)
+ l4h_slot_delete(ch->large_slot);
+ if (ch->large_pg)
+ __free_pages(ch->large_pg, 9);
+ } else {
+ if (ch->small_slots) {
+ for (j = 0; j < 512; j++) {
+ if (ch->small_slots[j])
+ l4h_slot_delete(ch->small_slots[j]);
+ }
+ kfree(ch->small_slots);
+ }
+ if (ch->small_pgs) {
+ for (j = 0; j < 512; j++) {
+ if (ch->small_pgs[j])
+ __free_page(ch->small_pgs[j]);
+ }
+ kfree(ch->small_pgs);
+ }
+ }
+ }
+ kvfree(km->chunks);
+ }
+
+ list_for_each_entry_safe(node, tmp, &km->pts, list) {
+ list_del(&node->list);
+ l4h_obj_free(&node->pt);
+ kfree(node);
+ }
+ kfree(km);
+}
+
+int fki_kmem_alloc(unsigned long size, unsigned long high_va, fki_u64 pa_base, struct fki_region *r)
+{
+ unsigned long aligned, nchunks, va_end;
+ fki_u64 pa_end;
+ struct fki_kmem *km;
+ struct fki_bind_ctx *bctx = NULL;
+ unsigned long i, j;
+ int cpu, err = 0;
+
+ if (!(fki_caps() & FKI_CAP_HIGH_WINDOW))
+ return -EOPNOTSUPP;
+ if (!size || !r)
+ return -EINVAL;
+ if (check_add_overflow(size, (unsigned long)(SZ_2M - 1), &aligned))
+ return -EINVAL;
+ aligned &= ~(unsigned long)(SZ_2M - 1);
+ nchunks = aligned >> 21;
+ if ((high_va & (SZ_2M - 1)) || (pa_base & (SZ_2M - 1)) || !aligned || !nchunks)
+ return -EINVAL;
+ if (check_add_overflow(high_va, aligned, &va_end) ||
+ check_add_overflow(pa_base, (fki_u64)aligned, &pa_end))
+ return -EINVAL;
+
+ mutex_lock(&fki_kmem_mutex);
+ if (rcu_access_pointer(active_kmem)) {
+ mutex_unlock(&fki_kmem_mutex);
+ return -EBUSY;
+ }
+
+ km = kzalloc(sizeof(*km), GFP_KERNEL);
+ if (!km) {
+ mutex_unlock(&fki_kmem_mutex);
+ return -ENOMEM;
+ }
+ km->high_va = high_va;
+ km->pa_base = pa_base;
+ km->size = aligned;
+ km->nchunks = nchunks;
+ INIT_LIST_HEAD(&km->pts);
+ INIT_LIST_HEAD(&km->as_list);
+ INIT_LIST_HEAD(&km->high_txns);
+ xa_init_flags(&km->dyn_slots, XA_FLAGS_LOCK_IRQ);
+ xa_init_flags(&km->pt_ready, XA_FLAGS_LOCK_IRQ);
+ spin_lock_init(&km->lock);
+ init_completion(&km->ops_zero);
+ err = percpu_ref_init(&km->ops_ref, fki_kmem_ops_release, 0, GFP_KERNEL);
+ if (err) {
+ kfree(km);
+ mutex_unlock(&fki_kmem_mutex);
+ return err;
+ }
+ km->ops_ref_inited = true;
+ km->dead = false;
+
+ km->chunks = kvcalloc(nchunks, sizeof(*km->chunks), GFP_KERNEL);
+ if (!km->chunks) {
+ percpu_ref_exit(&km->ops_ref);
+ kfree(km);
+ mutex_unlock(&fki_kmem_mutex);
+ return -ENOMEM;
+ }
+
+ for (i = 0; i < nchunks; i++) {
+ struct fki_kmem_chunk *ch = &km->chunks[i];
+ unsigned long cva = high_va + (i << 21);
+ struct page *pg = alloc_pages(GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN, 9);
+ unsigned long lf = 0;
+
+ if (pg) {
+ unsigned long gpa = page_to_phys(pg);
+
+ lf = l4h_large_frame(gpa);
+ if (lf) {
+ unsigned long slot = l4h_cap_copy(lf, L4H_RIGHTS_ALL);
+
+ if (!slot) {
+ __free_pages(pg, 9);
+ err = -ENOMEM;
+ goto fail;
+ }
+ err = map_high_frame(km, slot, cva,
+ L4H_PROT_READ | L4H_PROT_WRITE |
+ L4H_PROT_EXEC | L4H_PROT_LARGE);
+ if (err) {
+ l4h_slot_delete(slot);
+ __free_pages(pg, 9);
+ goto fail;
+ }
+ ch->is_large = true;
+ ch->large_pg = pg;
+ ch->large_gpa = gpa;
+ ch->large_slot = slot;
+ continue;
+ }
+ __free_pages(pg, 9);
+ }
+
+ /* Fallback: 512 x 4 KiB pages. */
+ ch->small_pgs = kcalloc(512, sizeof(*ch->small_pgs), GFP_KERNEL);
+ ch->small_slots = kcalloc(512, sizeof(*ch->small_slots), GFP_KERNEL);
+ if (!ch->small_pgs || !ch->small_slots) {
+ err = -ENOMEM;
+ goto fail;
+ }
+ for (j = 0; j < 512; j++) {
+ unsigned long gpa, slot;
+
+ ch->small_pgs[j] = alloc_page(GFP_KERNEL | __GFP_ZERO);
+ if (!ch->small_pgs[j]) {
+ err = -ENOMEM;
+ goto fail;
+ }
+ gpa = page_to_phys(ch->small_pgs[j]);
+ slot = l4h_cap_copy(L4H_FRAME_CPTR(gpa), L4H_RIGHTS_ALL);
+ if (!slot) {
+ err = -ENOMEM;
+ goto fail;
+ }
+ err = map_high_frame(km, slot, cva + (j << PAGE_SHIFT),
+ L4H_PROT_READ | L4H_PROT_WRITE | L4H_PROT_EXEC);
+ if (err) {
+ l4h_slot_delete(slot);
+ goto fail;
+ }
+ ch->small_slots[j] = slot;
+ }
+ }
+
+ err = fki_vs_pool_init();
+ if (err)
+ goto fail;
+
+ bctx = kzalloc(sizeof(*bctx), GFP_KERNEL);
+ if (!bctx) {
+ err = -ENOMEM;
+ goto fail;
+ }
+ bctx->vs = L4H_CPTR(L4H_SLOT_HIGH_VSPACE);
+ on_each_cpu(bind_high_vspace_cpu, bctx, 1);
+ for_each_online_cpu(cpu) {
+ if (cpu < NR_CPUS && bctx->errs[cpu]) {
+ err = -EIO;
+ break;
+ }
+ }
+ if (err) {
+ bctx->vs = 0;
+ on_each_cpu(bind_high_vspace_cpu, bctx, 1);
+ kfree(bctx);
+ goto fail;
+ }
+ kfree(bctx);
+
+ rcu_assign_pointer(active_kmem, km);
+ mutex_unlock(&fki_kmem_mutex);
+
+ r->va = (void *)high_va;
+ r->pa = pa_base;
+ r->size = aligned;
+ r->handle = km;
+ return 0;
+
+fail:
+ fki_vs_pool_fini();
+ if (km->ops_ref_inited) {
+ percpu_ref_exit(&km->ops_ref);
+ km->ops_ref_inited = false;
+ }
+ kmem_cleanup(km);
+ mutex_unlock(&fki_kmem_mutex);
+ return err;
+}
+EXPORT_SYMBOL(fki_kmem_alloc);
+
+static void fki_as_drain_list(struct fki_kmem *km);
+
+void fki_kmem_free(struct fki_region *r)
+{
+ struct fki_kmem *km;
+ struct fki_bind_ctx *bctx;
+
+ if (!r)
+ return;
+ mutex_lock(&fki_kmem_mutex);
+ km = r->handle;
+ if (!km) {
+ mutex_unlock(&fki_kmem_mutex);
+ return;
+ }
+ WRITE_ONCE(km->dead, true);
+ if (rcu_access_pointer(active_kmem) == km)
+ RCU_INIT_POINTER(active_kmem, NULL);
+ synchronize_rcu();
+ percpu_ref_kill(&km->ops_ref);
+ wait_for_completion(&km->ops_zero);
+
+ bctx = kzalloc(sizeof(*bctx), GFP_KERNEL);
+ if (bctx) {
+ bctx->vs = 0;
+ on_each_cpu(bind_high_vspace_cpu, bctx, 1);
+ kfree(bctx);
+ } else {
+ struct fki_bind_ctx fallback = { .vs = 0 };
+ on_each_cpu(bind_high_vspace_cpu, &fallback, 1);
+ }
+ fki_vs_pool_fini();
+ fki_as_drain_list(km);
+ {
+ struct fki_high_txn *txn, *tmp;
+ unsigned long flags;
+
+ spin_lock_irqsave(&km->lock, flags);
+ list_for_each_entry_safe(txn, tmp, &km->high_txns, list) {
+ unsigned long idx;
+
+ list_del(&txn->list);
+ for (idx = 0; idx < txn->npages; idx++) {
+ if (txn->pages[idx].stashed && txn->pages[idx].cptr)
+ l4h_slot_delete(txn->pages[idx].cptr);
+ }
+ kfree(txn);
+ }
+ spin_unlock_irqrestore(&km->lock, flags);
+ }
+ if (km->ops_ref_inited) {
+ percpu_ref_exit(&km->ops_ref);
+ km->ops_ref_inited = false;
+ }
+ kmem_cleanup(km);
+ r->va = NULL;
+ r->handle = NULL;
+ mutex_unlock(&fki_kmem_mutex);
+}
+EXPORT_SYMBOL(fki_kmem_free);
+
+static int prot_to_l4h(int prot)
+{
+ int p = 0;
+
+ if (prot & FKI_PROT_READ)
+ p |= L4H_PROT_READ;
+ if (prot & FKI_PROT_WRITE)
+ p |= L4H_PROT_WRITE;
+ if (prot & FKI_PROT_EXEC)
+ p |= L4H_PROT_EXEC;
+ return p;
+}
+
+static bool high_overlaps_aperture(struct fki_kmem *km, unsigned long va, unsigned long va_end)
+{
+ unsigned long km_va_end, ap_start, ap_end;
+
+ if (check_add_overflow(km->high_va, km->size, &km_va_end))
+ return true;
+ ap_start = round_down(km->high_va, SZ_2M);
+ ap_end = round_up(km_va_end, SZ_2M);
+ if (ap_end < km_va_end)
+ ap_end = ULONG_MAX;
+ return va < ap_end && va_end > ap_start;
+}
+
+static int ensure_high_pt(struct fki_kmem *km, unsigned long va)
+{
+ unsigned long high_vs = L4H_CPTR(L4H_SLOT_HIGH_VSPACE);
+ unsigned long idx = va >> 21;
+ int lvl;
+
+ if (xa_load(&km->pt_ready, idx))
+ return 0;
+ for (lvl = 0; lvl < 3; lvl++) {
+ struct fki_pt_node *node = kzalloc(sizeof(*node), GFP_ATOMIC);
+ int err;
+
+ if (!node)
+ return -ENOMEM;
+ if (l4h_obj_alloc(L4H_OBJ_PT, 0, &node->pt)) {
+ kfree(node);
+ return -ENOMEM;
+ }
+ err = l4h_pt_map(L4H_OBJ_PT, node->pt.cptr, high_vs, va & ~(SZ_2M - 1));
+ if (err) {
+ l4h_obj_free(&node->pt);
+ kfree(node);
+ if (err == L4H_ERR_DELETE_FIRST)
+ break;
+ return -EIO;
+ }
+ list_add(&node->list, &km->pts);
+ }
+ return 0;
+}
+
+static struct fki_high_txn *fki_high_txn_find_locked(struct fki_kmem *km,
+ unsigned long cur_va,
+ unsigned long *idx_out)
+{
+ struct fki_high_txn *txn;
+
+ list_for_each_entry(txn, &km->high_txns, list) {
+ if (cur_va >= txn->va && cur_va < txn->va + txn->size) {
+ if (idx_out)
+ *idx_out = (cur_va - txn->va) >> PAGE_SHIFT;
+ return txn;
+ }
+ }
+ return NULL;
+}
+
+static void fki_dyn_slot_clear_locked(struct fki_kmem *km, unsigned long cur_va, bool was_stored)
+{
+ unsigned long vpn = cur_va >> PAGE_SHIFT;
+ unsigned long idx = 0;
+ struct fki_high_txn *txn = fki_high_txn_find_locked(km, cur_va, &idx);
+
+ if (txn && txn->pages[idx].stashed) {
+ xa_store(&km->dyn_slots, vpn, XA_ZERO_ENTRY, GFP_ATOMIC);
+ return;
+ }
+ if (was_stored)
+ xa_erase(&km->dyn_slots, vpn);
+ else
+ xa_release(&km->dyn_slots, vpn);
+}
+
+enum fki_hm_kind {
+ FKI_HM_NONE = 0,
+ FKI_HM_NEW,
+ FKI_HM_REPROT,
+ FKI_HM_RESTORE,
+};
+
+struct fki_hm_page {
+ unsigned long new_pfn;
+ unsigned long new_slot;
+ unsigned long prev_pfn;
+ unsigned long prev_prot;
+ struct fki_high_txn *txn;
+ unsigned long txn_idx;
+ u8 kind;
+};
+
+static void fki_high_unmap_km(struct fki_kmem *km, unsigned long va, unsigned long size);
+
+int fki_high_map(unsigned long va, fki_u64 xpa, unsigned long size, int prot)
+{
+ struct fki_kmem *km = fki_kmem_get();
+ unsigned long high_vs = L4H_CPTR(L4H_SLOT_HIGH_VSPACE);
+ unsigned long flags, va_end, km_va_end, npages, i, j, mapped = 0;
+ unsigned long last_pt_idx = ~0UL;
+ fki_u64 xpa_end;
+ unsigned long eff_lprot = fki_eff_prot(prot_to_l4h(prot));
+ struct fki_hm_page stack_pgs[16];
+ struct fki_hm_page *pgs = stack_pgs;
+ int err = 0;
+
+ if (!km)
+ return -ENODEV;
+ if (!size) {
+ fki_kmem_put(km);
+ return 0;
+ }
+ if ((va | xpa | size) & ~PAGE_MASK) {
+ fki_kmem_put(km);
+ return -EINVAL;
+ }
+ if (check_add_overflow(va, size, &va_end) ||
+ check_add_overflow(xpa, (fki_u64)size, &xpa_end) ||
+ check_add_overflow(km->high_va, km->size, &km_va_end)) {
+ fki_kmem_put(km);
+ return -EINVAL;
+ }
+ /* Initial linear aperture is already mapped RWX (with 2 MiB large frames). */
+ if (va >= km->high_va && va_end <= km_va_end &&
+ xpa >= km->pa_base && (va - km->high_va) == (unsigned long)(xpa - km->pa_base)) {
+ fki_kmem_put(km);
+ return 0;
+ }
+ /* Reject any non-identity or cross-boundary overlap with the permanent 2 MiB aperture. */
+ if (high_overlaps_aperture(km, va, va_end)) {
+ fki_kmem_put(km);
+ return -EBUSY;
+ }
+ if (!eff_lprot) {
+ fki_high_unmap_km(km, va, size);
+ fki_kmem_put(km);
+ return 0;
+ }
+
+ npages = size >> PAGE_SHIFT;
+ if (npages > ARRAY_SIZE(stack_pgs)) {
+ pgs = kcalloc(npages, sizeof(*pgs), GFP_ATOMIC);
+ if (!pgs) {
+ fki_kmem_put(km);
+ return -ENOMEM;
+ }
+ } else {
+ memset(stack_pgs, 0, npages * sizeof(*stack_pgs));
+ }
+
+ /* Phase 1a: validate every target xpa -> gpa before taking km->lock. */
+ for (i = 0; i < npages; i++) {
+ unsigned long gpa;
+
+ err = xpa_to_gpa(km, xpa + ((fki_u64)i << PAGE_SHIFT), &gpa);
+ if (err)
+ goto out_free;
+ pgs[i].new_pfn = gpa >> PAGE_SHIFT;
+ }
+
+ /* Phase 1b: under km->lock, ensure PTs, reserve xarray slots, and pre-allocate frame caps. */
+ spin_lock_irqsave(&km->lock, flags);
+ for (i = 0; i < npages; i++) {
+ unsigned long cur_va = va + (i << PAGE_SHIFT);
+ unsigned long pt_idx = cur_va >> 21;
+ unsigned long vpn = cur_va >> PAGE_SHIFT;
+ void *old;
+
+ old = xa_load(&km->dyn_slots, vpn);
+ if (!old) {
+ unsigned long txn_idx = 0;
+ struct fki_high_txn *txn = fki_high_txn_find_locked(km, cur_va, &txn_idx);
+
+ if (txn && txn->restoring && txn->pages[txn_idx].stashed &&
+ txn->pages[txn_idx].cptr != 0 &&
+ txn->pages[txn_idx].pfn == pgs[i].new_pfn) {
+ pgs[i].kind = FKI_HM_RESTORE;
+ pgs[i].new_slot = txn->pages[txn_idx].cptr;
+ pgs[i].txn = txn;
+ pgs[i].txn_idx = txn_idx;
+ continue;
+ }
+ if (pt_idx != last_pt_idx) {
+ err = ensure_high_pt(km, cur_va);
+ if (err)
+ break;
+ last_pt_idx = pt_idx;
+ }
+ err = xa_reserve(&km->dyn_slots, vpn, GFP_ATOMIC);
+ if (err)
+ break;
+ pgs[i].new_slot = l4h_cap_copy(L4H_FRAME_CPTR(pgs[i].new_pfn << PAGE_SHIFT),
+ L4H_RIGHTS_ALL);
+ if (!pgs[i].new_slot) {
+ fki_dyn_slot_clear_locked(km, cur_va, false);
+ err = -ENOMEM;
+ break;
+ }
+ pgs[i].kind = FKI_HM_NEW;
+ } else if (fki_as_entry_pfn(old) == pgs[i].new_pfn) {
+ /* Same PFN: re-protect in place without deleting or copying caps. */
+ pgs[i].prev_pfn = pgs[i].new_pfn;
+ pgs[i].prev_prot = fki_as_entry_prot(old);
+ pgs[i].kind = FKI_HM_REPROT;
+ } else {
+ /* Cross-PFN live overwrite prohibited: caller must unmap while quiescent first. */
+ err = -EBUSY;
+ break;
+ }
+ }
+ if (err) {
+ for (j = 0; j < i; j++) {
+ unsigned long cur_va = va + (j << PAGE_SHIFT);
+
+ if (pgs[j].kind == FKI_HM_NEW) {
+ fki_dyn_slot_clear_locked(km, cur_va, false);
+ if (pgs[j].new_slot)
+ l4h_slot_delete(pgs[j].new_slot);
+ }
+ }
+ spin_unlock_irqrestore(&km->lock, flags);
+ goto out_free;
+ }
+
+ /* Phase 2: apply all updates; roll back completely if any mapping fails. */
+ for (i = 0; i < npages; i++) {
+ unsigned long cur_va = va + (i << PAGE_SHIFT);
+ unsigned long vpn = cur_va >> PAGE_SHIFT;
+
+ if (pgs[i].kind == FKI_HM_RESTORE) {
+ if (l4h_page_map(pgs[i].new_slot, high_vs, cur_va, (int)eff_lprot) != 0) {
+ err = -EIO;
+ break;
+ }
+ if (xa_err(xa_store(&km->dyn_slots, vpn,
+ fki_as_mk_entry(pgs[i].new_slot, pgs[i].new_pfn, eff_lprot),
+ GFP_ATOMIC))) {
+ l4h_page_unmap(pgs[i].new_slot);
+ err = -ENOMEM;
+ break;
+ }
+ pgs[i].txn->pages[pgs[i].txn_idx].cptr = 0;
+ pgs[i].txn->pages[pgs[i].txn_idx].stashed = false;
+ } else if (pgs[i].kind == FKI_HM_REPROT) {
+ void *old = xa_load(&km->dyn_slots, vpn);
+ unsigned long old_cptr = old ? fki_as_entry_cptr(old) : 0;
+
+ if (!old_cptr) {
+ err = -EIO;
+ break;
+ }
+ if (pgs[i].prev_prot != eff_lprot) {
+ if (l4h_page_map(old_cptr, high_vs, cur_va, (int)eff_lprot) != 0) {
+ err = -EIO;
+ break;
+ }
+ /* Slot already exists in dyn_slots: in-place xa_store cannot fail allocation. */
+ if (xa_err(xa_store(&km->dyn_slots, vpn,
+ fki_as_mk_entry(old_cptr, pgs[i].new_pfn, eff_lprot),
+ GFP_ATOMIC))) {
+ if (l4h_page_map(old_cptr, high_vs, cur_va, (int)pgs[i].prev_prot) != 0) {
+ WRITE_ONCE(km->dead, true);
+ panic("fki: unrecoverable high_map rollback failure at %#lx", cur_va);
+ }
+ err = -ENOMEM;
+ break;
+ }
+ }
+ } else {
+ /* FKI_HM_NEW */
+ err = map_high_frame(km, pgs[i].new_slot, cur_va, (int)eff_lprot);
+ if (err)
+ break;
+ if (xa_err(xa_store(&km->dyn_slots, vpn,
+ fki_as_mk_entry(pgs[i].new_slot, pgs[i].new_pfn, eff_lprot),
+ GFP_ATOMIC))) {
+ l4h_slot_delete(pgs[i].new_slot);
+ pgs[i].new_slot = 0;
+ err = -ENOMEM;
+ break;
+ }
+ }
+ mapped++;
+ }
+
+ if (err) {
+ for (j = 0; j < mapped; j++) {
+ unsigned long cur_va = va + (j << PAGE_SHIFT);
+ unsigned long vpn = cur_va >> PAGE_SHIFT;
+
+ if (pgs[j].kind == FKI_HM_RESTORE) {
+ l4h_page_unmap(pgs[j].new_slot);
+ xa_store(&km->dyn_slots, vpn, XA_ZERO_ENTRY, GFP_ATOMIC);
+ pgs[j].txn->pages[pgs[j].txn_idx].cptr = pgs[j].new_slot;
+ pgs[j].txn->pages[pgs[j].txn_idx].stashed = true;
+ } else if (pgs[j].kind == FKI_HM_REPROT) {
+ if (pgs[j].prev_prot != eff_lprot) {
+ void *cur = xa_load(&km->dyn_slots, vpn);
+ unsigned long cptr = cur ? fki_as_entry_cptr(cur) : 0;
+
+ if (!cptr ||
+ l4h_page_map(cptr, high_vs, cur_va, (int)pgs[j].prev_prot) != 0) {
+ WRITE_ONCE(km->dead, true);
+ panic("fki: unrecoverable high_map rollback failure at %#lx", cur_va);
+ }
+ xa_store(&km->dyn_slots, vpn,
+ fki_as_mk_entry(cptr, pgs[j].prev_pfn, pgs[j].prev_prot),
+ GFP_ATOMIC);
+ }
+ } else {
+ /* FKI_HM_NEW */
+ fki_dyn_slot_clear_locked(km, cur_va, true);
+ l4h_slot_delete(pgs[j].new_slot);
+ pgs[j].new_slot = 0;
+ }
+ }
+ for (j = mapped; j < npages; j++) {
+ unsigned long cur_va = va + (j << PAGE_SHIFT);
+
+ if (pgs[j].kind == FKI_HM_NEW) {
+ fki_dyn_slot_clear_locked(km, cur_va, false);
+ if (pgs[j].new_slot)
+ l4h_slot_delete(pgs[j].new_slot);
+ }
+ }
+ }
+ spin_unlock_irqrestore(&km->lock, flags);
+
+out_free:
+ if (pgs != stack_pgs)
+ kfree(pgs);
+ fki_kmem_put(km);
+ if (err)
+ pr_err_ratelimited("fki: high_map va=0x%lx xpa=0x%llx size=0x%lx prot=0x%x failed: %d\n",
+ va, xpa, size, prot, err);
+ return err;
+}
+EXPORT_SYMBOL(fki_high_map);
+
+static void fki_high_unmap_km(struct fki_kmem *km, unsigned long va, unsigned long size)
+{
+ unsigned long flags, va_end, km_va_end, ap_lo, ap_hi;
+ unsigned long lo[2], hi[2];
+ int i;
+
+ if (!km || !size || ((va | size) & ~PAGE_MASK))
+ return;
+ if (check_add_overflow(va, size, &va_end) ||
+ check_add_overflow(km->high_va, km->size, &km_va_end))
+ return;
+ ap_lo = round_down(km->high_va, SZ_2M);
+ ap_hi = round_up(km_va_end, SZ_2M);
+ if (ap_hi < km_va_end)
+ ap_hi = ULONG_MAX;
+
+ lo[0] = va;
+ hi[0] = min(va_end, ap_lo);
+ lo[1] = max(va, ap_hi);
+ hi[1] = va_end;
+ if (lo[0] >= hi[0] && lo[1] >= hi[1])
+ return;
+
+ spin_lock_irqsave(&km->lock, flags);
+ for (i = 0; i < 2; i++) {
+ unsigned long cur_va;
+
+ for (cur_va = lo[i]; cur_va < hi[i]; cur_va += PAGE_SIZE) {
+ unsigned long vpn = cur_va >> PAGE_SHIFT;
+ unsigned long idx = 0;
+ struct fki_high_txn *txn = fki_high_txn_find_locked(km, cur_va, &idx);
+
+ if (txn) {
+ if (txn->pages[idx].stashed) {
+ void *old = xa_load(&km->dyn_slots, vpn);
+
+ if (old) {
+ unsigned long old_slot = fki_as_entry_cptr(old);
+
+ if (old_slot)
+ l4h_slot_delete(old_slot);
+ xa_store(&km->dyn_slots, vpn, XA_ZERO_ENTRY, GFP_ATOMIC);
+ }
+ } else {
+ void *old = xa_erase(&km->dyn_slots, vpn);
+
+ if (old) {
+ unsigned long old_slot = fki_as_entry_cptr(old);
+
+ if (old_slot)
+ l4h_slot_delete(old_slot);
+ }
+ }
+ } else {
+ void *old = xa_erase(&km->dyn_slots, vpn);
+
+ if (old) {
+ unsigned long old_slot = fki_as_entry_cptr(old);
+
+ if (old_slot)
+ l4h_slot_delete(old_slot);
+ }
+ }
+ }
+ }
+ spin_unlock_irqrestore(&km->lock, flags);
+}
+
+int fki_high_txn_begin(unsigned long va, unsigned long size, void **handle_out)
+{
+ struct fki_kmem *km;
+ struct fki_high_txn *txn, *cur;
+ unsigned long high_vs = L4H_CPTR(L4H_SLOT_HIGH_VSPACE);
+ unsigned long va_end, km_va_end, ap_lo, ap_hi, npages, flags, idx, j;
+
+ if (!handle_out)
+ return -EINVAL;
+ *handle_out = NULL;
+ if (!size || ((va | size) & ~PAGE_MASK) ||
+ check_add_overflow(va, size, &va_end))
+ return -EINVAL;
+
+ km = fki_kmem_get();
+ if (!km)
+ return -ENODEV;
+ if (READ_ONCE(km->dead)) {
+ fki_kmem_put(km);
+ return -ENODEV;
+ }
+ if (check_add_overflow(km->high_va, km->size, &km_va_end)) {
+ fki_kmem_put(km);
+ return -EINVAL;
+ }
+ ap_lo = round_down(km->high_va, SZ_2M);
+ ap_hi = round_up(km_va_end, SZ_2M);
+ if (ap_hi < km_va_end)
+ ap_hi = ULONG_MAX;
+
+ npages = size >> PAGE_SHIFT;
+ txn = kzalloc(struct_size(txn, pages, npages), GFP_ATOMIC);
+ if (!txn) {
+ fki_kmem_put(km);
+ return -ENOMEM;
+ }
+ txn->km = km;
+ txn->va = va;
+ txn->size = size;
+ txn->npages = npages;
+
+ spin_lock_irqsave(&km->lock, flags);
+ if (READ_ONCE(km->dead)) {
+ spin_unlock_irqrestore(&km->lock, flags);
+ kfree(txn);
+ fki_kmem_put(km);
+ return -ENODEV;
+ }
+ list_for_each_entry(cur, &km->high_txns, list) {
+ if (va < cur->va + cur->size && cur->va < va_end) {
+ spin_unlock_irqrestore(&km->lock, flags);
+ kfree(txn);
+ fki_kmem_put(km);
+ return -EBUSY;
+ }
+ }
+ for (idx = 0; idx < npages; idx++) {
+ unsigned long cur_va = va + (idx << PAGE_SHIFT);
+ unsigned long vpn = cur_va >> PAGE_SHIFT;
+ void *old;
+
+ if (cur_va >= ap_lo && cur_va < ap_hi)
+ continue;
+ old = xa_load(&km->dyn_slots, vpn);
+ if (!old)
+ continue;
+ {
+ unsigned long old_slot = fki_as_entry_cptr(old);
+
+ if (!old_slot || l4h_page_unmap(old_slot) != 0) {
+ for (j = 0; j < idx; j++) {
+ if (txn->pages[j].stashed) {
+ unsigned long prev_va = va + (j << PAGE_SHIFT);
+ unsigned long prev_vpn = prev_va >> PAGE_SHIFT;
+
+ if (l4h_page_map(txn->pages[j].cptr, high_vs,
+ prev_va, (int)txn->pages[j].prot) != 0) {
+ WRITE_ONCE(km->dead, true);
+ panic("fki: unrecoverable high_txn_begin rollback failure at %#lx",
+ prev_va);
+ }
+ xa_store(&km->dyn_slots, prev_vpn,
+ fki_as_mk_entry(txn->pages[j].cptr,
+ txn->pages[j].pfn,
+ txn->pages[j].prot),
+ GFP_ATOMIC);
+ }
+ }
+ spin_unlock_irqrestore(&km->lock, flags);
+ kfree(txn);
+ fki_kmem_put(km);
+ return -EIO;
+ }
+ txn->pages[idx].cptr = old_slot;
+ txn->pages[idx].pfn = fki_as_entry_pfn(old);
+ txn->pages[idx].prot = (u8)fki_as_entry_prot(old);
+ txn->pages[idx].stashed = true;
+ xa_store(&km->dyn_slots, vpn, XA_ZERO_ENTRY, GFP_ATOMIC);
+ }
+ }
+ list_add(&txn->list, &km->high_txns);
+ spin_unlock_irqrestore(&km->lock, flags);
+ fki_kmem_put(km);
+ *handle_out = txn;
+ return 0;
+}
+EXPORT_SYMBOL(fki_high_txn_begin);
+
+void fki_high_txn_restore(void *handle)
+{
+ struct fki_kmem *km;
+ struct fki_high_txn *cur;
+ unsigned long flags;
+
+ if (!handle)
+ return;
+ km = fki_kmem_get();
+ if (!km)
+ return;
+ spin_lock_irqsave(&km->lock, flags);
+ list_for_each_entry(cur, &km->high_txns, list) {
+ if (cur == handle) {
+ cur->restoring = true;
+ break;
+ }
+ }
+ spin_unlock_irqrestore(&km->lock, flags);
+ fki_kmem_put(km);
+}
+EXPORT_SYMBOL(fki_high_txn_restore);
+
+void fki_high_txn_end(void *handle)
+{
+ struct fki_kmem *km;
+ struct fki_high_txn *cur, *found = NULL;
+ unsigned long flags, idx;
+
+ if (!handle)
+ return;
+ km = fki_kmem_get();
+ if (!km)
+ return;
+ spin_lock_irqsave(&km->lock, flags);
+ list_for_each_entry(cur, &km->high_txns, list) {
+ if (cur == handle) {
+ found = cur;
+ list_del(&cur->list);
+ for (idx = 0; idx < cur->npages; idx++) {
+ if (cur->pages[idx].stashed) {
+ unsigned long vpn = (cur->va + (idx << PAGE_SHIFT)) >> PAGE_SHIFT;
+
+ if (cur->pages[idx].cptr)
+ l4h_slot_delete(cur->pages[idx].cptr);
+ if (xa_load(&km->dyn_slots, vpn) == NULL)
+ xa_release(&km->dyn_slots, vpn);
+ }
+ }
+ break;
+ }
+ }
+ spin_unlock_irqrestore(&km->lock, flags);
+ if (found)
+ kfree(found);
+ fki_kmem_put(km);
+}
+EXPORT_SYMBOL(fki_high_txn_end);
+
+void fki_high_unmap(unsigned long va, unsigned long size)
+{
+ struct fki_kmem *km = fki_kmem_get();
+
+ if (!km)
+ return;
+ fki_high_unmap_km(km, va, size);
+ fki_kmem_put(km);
+}
+EXPORT_SYMBOL(fki_high_unmap);
+
+void fki_high_flush(void)
+{
+ struct fki_kmem *km = fki_kmem_get();
+
+ if (!km)
+ return;
+ if (fki_caps() & FKI_CAP_HIGH_WINDOW)
+ l4h_vspace_flush(L4H_CPTR(L4H_SLOT_HIGH_VSPACE));
+ fki_kmem_put(km);
+}
+EXPORT_SYMBOL(fki_high_flush);
+
+static bool high_range_readable_locked(struct fki_kmem *km, unsigned long va, unsigned long size)
+{
+ unsigned long end, km_end, page_va, last_page;
+
+ if (!size || check_add_overflow(va, size, &end) ||
+ check_add_overflow(km->high_va, km->size, &km_end))
+ return false;
+ if (va >= km->high_va && end <= km_end)
+ return true;
+ page_va = va & PAGE_MASK;
+ last_page = (end - 1) & PAGE_MASK;
+ for (;; page_va += PAGE_SIZE) {
+ if (!(page_va >= km->high_va && page_va < km_end) &&
+ !xa_load(&km->dyn_slots, page_va >> PAGE_SHIFT))
+ return false;
+ if (page_va == last_page)
+ break;
+ }
+ return true;
+}
+
+int fki_high_read_u64x2(unsigned long va, fki_u64 *out0, fki_u64 *out1)
+{
+ struct fki_kmem *km = fki_kmem_get();
+ unsigned long flags;
+ int err = -EFAULT;
+
+ if (!km || !out0 || !out1 || (va & 7UL)) {
+ fki_kmem_put(km);
+ return -EFAULT;
+ }
+ spin_lock_irqsave(&km->lock, flags);
+ if (high_range_readable_locked(km, va, 16)) {
+ const volatile fki_u64 *p = (const volatile fki_u64 *)va;
+
+ *out0 = p[0];
+ *out1 = p[1];
+ err = 0;
+ }
+ spin_unlock_irqrestore(&km->lock, flags);
+ fki_kmem_put(km);
+ return err;
+}
+EXPORT_SYMBOL(fki_high_read_u64x2);
+
+static unsigned long icache_anchor;
+
+void fki_icache_flush(unsigned long va, unsigned long size)
+{
+ struct fki_kmem *km = fki_kmem_get();
+
+ if (km && size) {
+ unsigned long flags;
+
+ spin_lock_irqsave(&km->lock, flags);
+ if (high_range_readable_locked(km, va, size)) {
+ unsigned long ctr;
+
+ asm volatile("mrs %0, ctr_el0" : "=r"(ctr));
+ if (!((ctr >> 28) & 1UL)) {
+ unsigned long step = 4UL << ((ctr >> 16) & 0xfUL);
+ unsigned long cur = va & ~(step - 1);
+ unsigned long end = va + size;
+
+ for (; cur < end; cur += step)
+ asm volatile("dc cvau, %0" : : "r"(cur) : "memory");
+ asm volatile("dsb ish" ::: "memory");
+ }
+ }
+ spin_unlock_irqrestore(&km->lock, flags);
+ }
+ fki_kmem_put(km);
+ /* Trigger EL1 cross-core ic ialluis on a valid Linux low-VA anchor (never pass high VA or 0,0). */
+ l4h_flush_icache((unsigned long)&icache_anchor, (unsigned long)&icache_anchor + 64);
+ asm volatile("dsb ish; isb" ::: "memory");
+}
+EXPORT_SYMBOL(fki_icache_flush);
+
+/* Use high window for fki_region_alloc so mode=1 smoke tests have executable memory. */
+int fki_region_alloc(unsigned long size, struct fki_region *r)
+{
+ return fki_kmem_alloc(size, FKI_L4H_REGION_VA, FKI_L4H_REGION_PA, r);
+}
+EXPORT_SYMBOL(fki_region_alloc);
+
+void fki_region_free(struct fki_region *r)
+{
+ fki_kmem_free(r);
+}
+EXPORT_SYMBOL(fki_region_free);
+
+fki_u64 fki_phys_peek(fki_u64 pa)
+{
+ struct fki_kmem *km = fki_kmem_get();
+ unsigned long gpa;
+ fki_u64 val = ~0ULL;
+
+ if (km && xpa_to_gpa(km, pa & ~7ULL, &gpa) == 0)
+ val = READ_ONCE(*(u64 *)phys_to_virt(gpa));
+ fki_kmem_put(km);
+ return val;
+}
+EXPORT_SYMBOL(fki_phys_peek);
+
+/* ---- EL1-only primitives (unsupported on EL0 host) ---- */
+
+int fki_contig_alloc(unsigned long size, struct fki_region *r) { return -EOPNOTSUPP; }
+EXPORT_SYMBOL(fki_contig_alloc);
+void fki_contig_free(struct fki_region *r) {}
+EXPORT_SYMBOL(fki_contig_free);
+int fki_window_l1(unsigned long va, unsigned long long **l1_va, fki_u64 *l1_pa) { return -EOPNOTSUPP; }
+EXPORT_SYMBOL(fki_window_l1);
+void fki_window_set(unsigned long long *slot, fki_u64 desc) {}
+EXPORT_SYMBOL(fki_window_set);
+unsigned long fki_regs_pc(void *regs) { return 0; }
+EXPORT_SYMBOL(fki_regs_pc);
+unsigned long fki_regs_lr(void *regs) { return 0; }
+EXPORT_SYMBOL(fki_regs_lr);
+unsigned long fki_regs_pstate(void *regs) { return 0; }
+EXPORT_SYMBOL(fki_regs_pstate);
+void fki_regs_set_pc(void *regs, unsigned long pc) {}
+EXPORT_SYMBOL(fki_regs_set_pc);
+void fki_regs_set_reg(void *regs, unsigned int n, unsigned long v) {}
+EXPORT_SYMBOL(fki_regs_set_reg);
+unsigned long fki_regs_reg(void *regs, unsigned int n) { return 0; }
+EXPORT_SYMBOL(fki_regs_reg);
+int fki_fault_register(unsigned long lo, unsigned long hi, int (*handler)(unsigned long far, unsigned long esr, void *regs)) { return -EOPNOTSUPP; }
+EXPORT_SYMBOL(fki_fault_register);
+void fki_fault_unregister(void) {}
+EXPORT_SYMBOL(fki_fault_unregister);
+
+/* ---- User address space & uTCB primitives ---- */
+
+struct fki_as {
+ int vs_idx;
+ u64 gen;
+ atomic_t active_cpus;
+ refcount_t refcnt;
+ bool dead;
+ spinlock_t lock;
+ struct list_head kmem_node;
+};
+
+static bool fki_as_get(struct fki_as *as)
+{
+ return as && refcount_inc_not_zero(&as->refcnt);
+}
+
+static void fki_as_put(struct fki_as *as)
+{
+ if (as && refcount_dec_and_test(&as->refcnt))
+ kfree(as);
+}
+
+struct fki_vs_slot {
+ unsigned long root;
+ struct fki_as *owner;
+ struct list_head lru;
+ struct list_head pts;
+ struct xarray slots;
+};
+
+static struct fki_vs_slot *fki_vs_pool;
+static int fki_vs_cap;
+static LIST_HEAD(fki_vs_free);
+static LIST_HEAD(fki_vs_lru);
+static DEFINE_SPINLOCK(fki_vs_lock);
+static int fki_vs_resetting;
+static atomic64_t fki_vs_gen = ATOMIC64_INIT(1);
+
+static void fki_vs_slot_reset(struct fki_vs_slot *slot)
+{
+ struct fki_pt_node *node, *tmp;
+ unsigned long vpn;
+ void *e;
+
+ /* Free page tables in reverse order (highest level first) to avoid per-frame shootdowns. */
+ list_for_each_entry_safe_reverse(node, tmp, &slot->pts, list) {
+ list_del(&node->list);
+ l4h_obj_free(&node->pt);
+ kfree(node);
+ }
+ xa_for_each(&slot->slots, vpn, e) {
+ unsigned long cptr = fki_as_entry_cptr(e);
+
+ if (cptr)
+ l4h_slot_delete(cptr);
+ }
+ xa_destroy(&slot->slots);
+ xa_init(&slot->slots);
+ l4h_vspace_flush(slot->root);
+}
+
+static int fki_vs_pool_init(void)
+{
+ int nr, cap, i;
+
+ if (fki_vs_pool)
+ return 0;
+ nr = (int)l4h_bootinfo->nr_vspaces;
+ cap = nr > 80 ? clamp(nr - 48, 32, 192) : (nr > 16 ? nr / 2 : 0);
+ if (cap <= 0)
+ return -ENOMEM;
+
+ fki_vs_pool = kcalloc(cap, sizeof(*fki_vs_pool), GFP_KERNEL);
+ if (!fki_vs_pool)
+ return -ENOMEM;
+
+ INIT_LIST_HEAD(&fki_vs_free);
+ INIT_LIST_HEAD(&fki_vs_lru);
+ fki_vs_resetting = 0;
+
+ for (i = 0; i < cap; i++) {
+ unsigned long root = l4h_vspace_get();
+
+ if (!root) {
+ fki_vs_cap = i;
+ fki_vs_pool_fini();
+ return -ENOMEM;
+ }
+ fki_vs_pool[i].root = root;
+ fki_vs_pool[i].owner = NULL;
+ INIT_LIST_HEAD(&fki_vs_pool[i].lru);
+ INIT_LIST_HEAD(&fki_vs_pool[i].pts);
+ xa_init(&fki_vs_pool[i].slots);
+ list_add_tail(&fki_vs_pool[i].lru, &fki_vs_free);
+ }
+ fki_vs_cap = cap;
+ pr_info("fki: reserved %d/%d user VSpaces for hosted user spaces\n", cap, nr);
+ return 0;
+}
+
+static void fki_vs_pool_fini(void)
+{
+ int i;
+
+ if (!fki_vs_pool)
+ return;
+ for (i = 0; i < fki_vs_cap; i++) {
+ struct fki_vs_slot *slot = &fki_vs_pool[i];
+ struct fki_as *owner = slot->owner;
+
+ if (owner) {
+ unsigned long flags;
+
+ spin_lock_irqsave(&owner->lock, flags);
+ WRITE_ONCE(owner->vs_idx, -1);
+ owner->gen++;
+ spin_unlock_irqrestore(&owner->lock, flags);
+ slot->owner = NULL;
+ }
+ fki_vs_slot_reset(slot);
+ if (owner)
+ fki_as_put(owner);
+ if (slot->root)
+ l4h_vspace_put(slot->root);
+ }
+ kfree(fki_vs_pool);
+ fki_vs_pool = NULL;
+ fki_vs_cap = 0;
+ INIT_LIST_HEAD(&fki_vs_free);
+ INIT_LIST_HEAD(&fki_vs_lru);
+}
+
+static void fki_as_drain_list(struct fki_kmem *km)
+{
+ unsigned long flags;
+
+ for (;;) {
+ struct fki_as *as = NULL;
+
+ spin_lock_irqsave(&fki_vs_lock, flags);
+ if (!list_empty(&km->as_list)) {
+ as = list_first_entry(&km->as_list, struct fki_as, kmem_node);
+ list_del_init(&as->kmem_node);
+ WRITE_ONCE(as->dead, true);
+ }
+ spin_unlock_irqrestore(&fki_vs_lock, flags);
+ if (!as)
+ break;
+ fki_as_put(as);
+ }
+}
+
+void *fki_as_create(void)
+{
+ struct fki_kmem *km = fki_kmem_get();
+ struct fki_as *as;
+ unsigned long flags;
+
+ if (!km)
+ return NULL;
+ as = kzalloc(sizeof(*as), GFP_ATOMIC);
+ if (!as) {
+ fki_kmem_put(km);
+ return NULL;
+ }
+ as->vs_idx = -1;
+ as->gen = 0;
+ atomic_set(&as->active_cpus, 0);
+ refcount_set(&as->refcnt, 1);
+ spin_lock_init(&as->lock);
+ INIT_LIST_HEAD(&as->kmem_node);
+ spin_lock_irqsave(&fki_vs_lock, flags);
+ if (READ_ONCE(km->dead)) {
+ spin_unlock_irqrestore(&fki_vs_lock, flags);
+ kfree(as);
+ fki_kmem_put(km);
+ return NULL;
+ }
+ list_add_tail(&as->kmem_node, &km->as_list);
+ spin_unlock_irqrestore(&fki_vs_lock, flags);
+ fki_kmem_put(km);
+ return as;
+}
+EXPORT_SYMBOL(fki_as_create);
+
+void fki_as_destroy(void *as_ptr)
+{
+ struct fki_as *as = as_ptr;
+ struct fki_kmem *km;
+ struct fki_vs_slot *slot = NULL;
+ unsigned long flags;
+ bool drop_owner, drop_slot_ref = false;
+
+ if (!as)
+ return;
+ km = fki_kmem_get();
+ if (!km)
+ return;
+ spin_lock_irqsave(&fki_vs_lock, flags);
+ drop_owner = !list_empty(&as->kmem_node);
+ if (drop_owner)
+ list_del_init(&as->kmem_node);
+ spin_lock(&as->lock);
+ WRITE_ONCE(as->dead, true);
+ if (as->vs_idx >= 0 && fki_vs_pool) {
+ slot = &fki_vs_pool[as->vs_idx];
+ WRITE_ONCE(as->vs_idx, -1);
+ as->gen++;
+ if (slot->owner == as) {
+ slot->owner = NULL;
+ drop_slot_ref = true;
+ }
+ list_del_init(&slot->lru);
+ fki_vs_resetting++;
+ }
+ spin_unlock(&as->lock);
+ spin_unlock_irqrestore(&fki_vs_lock, flags);
+
+ smp_mb();
+ while (atomic_read(&as->active_cpus) != 0)
+ cpu_relax();
+
+ if (slot) {
+ fki_vs_slot_reset(slot);
+ spin_lock_irqsave(&fki_vs_lock, flags);
+ fki_vs_resetting--;
+ list_add(&slot->lru, &fki_vs_free);
+ spin_unlock_irqrestore(&fki_vs_lock, flags);
+ }
+ fki_kmem_put(km);
+ if (drop_slot_ref)
+ fki_as_put(as);
+ if (drop_owner)
+ fki_as_put(as);
+}
+EXPORT_SYMBOL(fki_as_destroy);
+
+static int map_user_frame(struct fki_vs_slot *slot, unsigned long cptr,
+ unsigned long va, unsigned long lprot)
+{
+ int err;
+
+ while ((err = l4h_page_map(cptr, slot->root, va, (int)lprot)) == L4H_ERR_FAILED_LOOKUP) {
+ struct fki_pt_node *node = kzalloc(sizeof(*node), GFP_ATOMIC);
+
+ if (!node)
+ return -ENOMEM;
+ if (l4h_obj_alloc(L4H_OBJ_PT, 0, &node->pt)) {
+ kfree(node);
+ return -ENOMEM;
+ }
+ err = l4h_pt_map(L4H_OBJ_PT, node->pt.cptr, slot->root, va);
+ if (err) {
+ l4h_obj_free(&node->pt);
+ kfree(node);
+ return -EIO;
+ }
+ list_add(&node->list, &slot->pts);
+ }
+ return err ? -EIO : 0;
+}
+
+static void fki_as_unmap_km(struct fki_kmem *km, struct fki_as *as,
+ unsigned long va, unsigned long size);
+
+int fki_as_map(void *as_ptr, unsigned long va, fki_u64 xpa, unsigned long size, int prot)
+{
+ struct fki_as *as = as_ptr;
+ struct fki_kmem *km = fki_kmem_get();
+ unsigned long lprot, va_end, flags, off;
+ fki_u64 xpa_end;
+ int changed = 0, err = 0;
+
+ if (!as || !km) {
+ fki_kmem_put(km);
+ return -ENODEV;
+ }
+ if (READ_ONCE(as->dead)) {
+ fki_kmem_put(km);
+ return -EINVAL;
+ }
+ if ((va | xpa | size) & ~PAGE_MASK) {
+ fki_kmem_put(km);
+ return -EINVAL;
+ }
+ if (!size) {
+ fki_kmem_put(km);
+ return 0;
+ }
+ if (check_add_overflow(va, size, &va_end) ||
+ check_add_overflow(xpa, (fki_u64)size, &xpa_end)) {
+ fki_kmem_put(km);
+ return -EINVAL;
+ }
+ if ((prot & FKI_PROT_EXEC) && !(prot & FKI_PROT_READ)) {
+ fki_kmem_put(km);
+ return -EOPNOTSUPP;
+ }
+ lprot = fki_eff_prot(prot_to_l4h(prot));
+ if (!lprot) {
+ fki_as_unmap_km(km, as, va, size);
+ fki_kmem_put(km);
+ return 0;
+ }
+
+ spin_lock_irqsave(&as->lock, flags);
+ if (READ_ONCE(as->dead)) {
+ spin_unlock_irqrestore(&as->lock, flags);
+ fki_kmem_put(km);
+ return -EINVAL;
+ }
+ if (as->vs_idx < 0 || !fki_vs_pool) {
+ spin_unlock_irqrestore(&as->lock, flags);
+ fki_kmem_put(km);
+ return 0;
+ }
+ {
+ struct fki_vs_slot *slot = &fki_vs_pool[as->vs_idx];
+
+ for (off = 0; off < size; off += PAGE_SIZE) {
+ unsigned long cur_va = va + off;
+ fki_u64 cur_xpa = xpa + off;
+ unsigned long vpn = cur_va >> PAGE_SHIFT;
+ unsigned long gpa, pfn, cptr;
+ void *e;
+
+ err = xpa_to_gpa(km, cur_xpa, &gpa);
+ if (err)
+ break;
+ pfn = gpa >> PAGE_SHIFT;
+ e = xa_load(&slot->slots, vpn);
+ if (e && fki_as_entry_pfn(e) == pfn) {
+ if (fki_as_entry_prot(e) == lprot)
+ continue;
+ cptr = fki_as_entry_cptr(e);
+ if (l4h_page_map(cptr, slot->root, cur_va, (int)lprot) == 0) {
+ xa_store(&slot->slots, vpn,
+ fki_as_mk_entry(cptr, pfn, lprot), GFP_ATOMIC);
+ changed = 1;
+ continue;
+ }
+ /* Remap failed: delete and recreate below. */
+ }
+ if (e) {
+ unsigned long old_cptr = fki_as_entry_cptr(e);
+
+ xa_erase(&slot->slots, vpn);
+ if (old_cptr)
+ l4h_slot_delete(old_cptr);
+ }
+ cptr = l4h_cap_copy(L4H_FRAME_CPTR(gpa), L4H_RIGHTS_ALL);
+ if (!cptr) {
+ err = -ENOMEM;
+ break;
+ }
+ err = map_user_frame(slot, cptr, cur_va, lprot);
+ if (err) {
+ l4h_slot_delete(cptr);
+ break;
+ }
+ if (xa_err(xa_store(&slot->slots, vpn,
+ fki_as_mk_entry(cptr, pfn, lprot), GFP_ATOMIC))) {
+ l4h_slot_delete(cptr);
+ err = -ENOMEM;
+ break;
+ }
+ changed = 1;
+ }
+ }
+ spin_unlock_irqrestore(&as->lock, flags);
+ fki_kmem_put(km);
+ return err ? err : changed;
+}
+EXPORT_SYMBOL(fki_as_map);
+
+static void fki_vs_slot_unmap_range(struct fki_vs_slot *slot,
+ unsigned long va, unsigned long size)
+{
+ unsigned long first_vpn, last_va, last_vpn, vpn;
+ void *e;
+
+ if (!size)
+ return;
+ first_vpn = va >> PAGE_SHIFT;
+ last_va = (size - 1 > ULONG_MAX - va) ? ULONG_MAX : (va + size - 1);
+ last_vpn = last_va >> PAGE_SHIFT;
+ xa_for_each_range(&slot->slots, vpn, e, first_vpn, last_vpn) {
+ unsigned long cptr = fki_as_entry_cptr(e);
+
+ xa_erase(&slot->slots, vpn);
+ if (cptr)
+ l4h_slot_delete(cptr);
+ }
+}
+
+static void fki_as_unmap_km(struct fki_kmem *km, struct fki_as *as,
+ unsigned long va, unsigned long size)
+{
+ unsigned long flags, va_end;
+
+ if (!km || !size)
+ return;
+ if ((va | size) & ~PAGE_MASK)
+ return;
+ if (check_add_overflow(va, size, &va_end))
+ return;
+ if (!as) {
+ int i;
+
+ if (!fki_vs_pool)
+ return;
+ spin_lock_irqsave(&fki_vs_lock, flags);
+ for (i = 0; i < fki_vs_cap; i++) {
+ struct fki_vs_slot *slot = &fki_vs_pool[i];
+ struct fki_as *owner = slot->owner;
+
+ if (!owner)
+ continue;
+ spin_lock(&owner->lock);
+ fki_vs_slot_unmap_range(slot, va, size);
+ spin_unlock(&owner->lock);
+ }
+ spin_unlock_irqrestore(&fki_vs_lock, flags);
+ return;
+ }
+ spin_lock_irqsave(&as->lock, flags);
+ if (as->vs_idx >= 0 && fki_vs_pool)
+ fki_vs_slot_unmap_range(&fki_vs_pool[as->vs_idx], va, size);
+ spin_unlock_irqrestore(&as->lock, flags);
+}
+
+void fki_as_unmap(void *as_ptr, unsigned long va, unsigned long size)
+{
+ struct fki_kmem *km = fki_kmem_get();
+
+ if (!km)
+ return;
+ fki_as_unmap_km(km, as_ptr, va, size);
+ fki_kmem_put(km);
+}
+EXPORT_SYMBOL(fki_as_unmap);
+
+void fki_as_flush(void *as_ptr)
+{
+ struct fki_as *as = as_ptr;
+ struct fki_kmem *km;
+ unsigned long flags;
+
+ if (!as)
+ return;
+ km = fki_kmem_get();
+ if (!km)
+ return;
+ spin_lock_irqsave(&as->lock, flags);
+ if (as->vs_idx >= 0 && fki_vs_pool)
+ l4h_vspace_flush(fki_vs_pool[as->vs_idx].root);
+ spin_unlock_irqrestore(&as->lock, flags);
+ fki_kmem_put(km);
+}
+EXPORT_SYMBOL(fki_as_flush);
+
+/*
+ * Caller must have incremented as->active_cpus before calling.
+ * Note: fast-path hits in fki_utcb_run_inner do not take fki_vs_lock or move
+ * the LRU node, so eviction order is approximate LRU.
+ */
+static struct fki_vs_slot *fki_vs_activate(struct fki_as *as, u64 *gen_out)
+{
+ struct fki_vs_slot *slot, *victim;
+ unsigned long flags;
+
+ if (!fki_vs_pool)
+ return NULL;
+
+ for (;;) {
+ spin_lock_irqsave(&fki_vs_lock, flags);
+ if (READ_ONCE(as->dead)) {
+ spin_unlock_irqrestore(&fki_vs_lock, flags);
+ return NULL;
+ }
+ if (as->vs_idx >= 0) {
+ slot = &fki_vs_pool[as->vs_idx];
+ list_move_tail(&slot->lru, &fki_vs_lru);
+ *gen_out = as->gen;
+ spin_unlock_irqrestore(&fki_vs_lock, flags);
+ return slot;
+ }
+ if (!list_empty(&fki_vs_free)) {
+ slot = list_first_entry(&fki_vs_free, struct fki_vs_slot, lru);
+ list_del_init(&slot->lru);
+ spin_lock(&as->lock);
+ if (!fki_as_get(as)) {
+ spin_unlock(&as->lock);
+ list_add(&slot->lru, &fki_vs_free);
+ spin_unlock_irqrestore(&fki_vs_lock, flags);
+ return NULL;
+ }
+ slot->owner = as;
+ as->gen = (u64)atomic64_inc_return(&fki_vs_gen);
+ *gen_out = as->gen;
+ smp_store_release(&as->vs_idx, (int)(slot - fki_vs_pool));
+ spin_unlock(&as->lock);
+ list_add_tail(&slot->lru, &fki_vs_lru);
+ spin_unlock_irqrestore(&fki_vs_lock, flags);
+ return slot;
+ }
+ victim = NULL;
+ list_for_each_entry(slot, &fki_vs_lru, lru) {
+ if (slot->owner && atomic_read(&slot->owner->active_cpus) == 0) {
+ victim = slot;
+ break;
+ }
+ }
+ if (victim) {
+ struct fki_as *vas = victim->owner;
+ int old_idx;
+
+ spin_lock(&vas->lock);
+ old_idx = vas->vs_idx;
+ WRITE_ONCE(vas->vs_idx, -1);
+ smp_mb();
+ if (atomic_read(&vas->active_cpus) != 0) {
+ smp_store_release(&vas->vs_idx, old_idx);
+ spin_unlock(&vas->lock);
+ spin_unlock_irqrestore(&fki_vs_lock, flags);
+ cpu_relax();
+ continue;
+ }
+ vas->gen++;
+ victim->owner = NULL;
+ list_del_init(&victim->lru);
+ fki_vs_resetting++;
+ spin_unlock(&vas->lock);
+ spin_unlock_irqrestore(&fki_vs_lock, flags);
+
+ fki_as_put(vas);
+ fki_vs_slot_reset(victim);
+
+ spin_lock_irqsave(&fki_vs_lock, flags);
+ fki_vs_resetting--;
+ list_add(&victim->lru, &fki_vs_free);
+ spin_unlock_irqrestore(&fki_vs_lock, flags);
+ continue;
+ }
+ if (!fki_vs_resetting) {
+ spin_unlock_irqrestore(&fki_vs_lock, flags);
+ pr_err("fki: all %d user VSpaces are pinned by active CPUs\n", fki_vs_cap);
+ return NULL;
+ }
+ spin_unlock_irqrestore(&fki_vs_lock, flags);
+ cpu_relax();
+ }
+}
+
+struct fki_utcb {
+ struct l4h_uctx u;
+ struct l4h_obj tcb_obj;
+ struct l4h_obj reply_obj;
+ struct fki_as *as;
+ u64 as_gen;
+ int cpu;
+ bool have_tls;
+ u64 last_tpidr;
+ u64 last_tpidrro;
+ bool have_pac;
+ struct fki_pac_keys last_pac;
+};
+
+void *fki_utcb_create(void *as_ptr)
+{
+ struct fki_utcb *utcb;
+ struct l4h_uctx *u;
+ struct fki_as *as = as_ptr;
+ int cpu = smp_processor_id();
+
+ if (as) {
+ unsigned long flags;
+ bool ok;
+
+ spin_lock_irqsave(&as->lock, flags);
+ ok = !READ_ONCE(as->dead) && fki_as_get(as);
+ spin_unlock_irqrestore(&as->lock, flags);
+ if (!ok)
+ return NULL;
+ }
+
+ utcb = kzalloc(sizeof(*utcb), GFP_ATOMIC);
+ if (!utcb) {
+ fki_as_put(as);
+ return NULL;
+ }
+ u = &utcb->u;
+
+ if (l4h_obj_alloc(L4H_OBJ_TCB, 0, &utcb->tcb_obj))
+ goto fail_free;
+ if (l4h_obj_alloc(L4H_OBJ_REPLY, 0, &utcb->reply_obj))
+ goto fail_tcb;
+ u->fault_ep = l4h_slot_alloc();
+ if (!u->fault_ep)
+ goto fail_reply;
+
+ u->tcb = utcb->tcb_obj.cptr;
+ u->reply = utcb->reply_obj.cptr;
+ u->badge = l4h_uctx_alloc_badge();
+ if (l4h_cnode_mint(u->fault_ep, 64, L4H_SLOT_VCPU(cpu) + L4H_VCPU_EP,
+ L4H_ROOT_DEPTH, L4H_RIGHTS_ALL, u->badge))
+ goto fail_ep;
+ if (l4h_tcb_set_flags(u->tcb, 1 /* fpuDisabled */, 2 /* trapSyscalls */))
+ goto fail_ep;
+
+ u->fault_ep_vcpu = cpu;
+ u->sc_vcpu = -1;
+ u->vspace = 0;
+ u->state = L4H_UCTX_FRESH;
+ u->regs_valid = 1;
+ utcb->cpu = cpu;
+ utcb->as = as;
+ return utcb;
+
+fail_ep:
+ l4h_slot_delete(u->fault_ep);
+fail_reply:
+ l4h_obj_free(&utcb->reply_obj);
+fail_tcb:
+ l4h_obj_free(&utcb->tcb_obj);
+fail_free:
+ fki_as_put(as);
+ kfree(utcb);
+ return NULL;
+}
+EXPORT_SYMBOL(fki_utcb_create);
+
+static void fki_utcb_desched_ipi(void *arg)
+{
+ struct l4h_uctx *u = arg;
+
+ if (this_cpu_read(fki_cur_utcb) == u)
+ this_cpu_write(fki_cur_utcb, NULL);
+ l4h_user_deschedule(u);
+}
+
+void fki_utcb_destroy(void *utcb_ptr)
+{
+ struct fki_utcb *utcb = utcb_ptr;
+ struct l4h_uctx *u;
+
+ if (!utcb)
+ return;
+ u = &utcb->u;
+ if (u->sc_vcpu >= 0) {
+ if (u->sc_vcpu == smp_processor_id()) {
+ fki_utcb_desched_ipi(u);
+ } else if (u->sc_vcpu < nr_cpu_ids && cpu_online(u->sc_vcpu)) {
+ smp_call_function_single(u->sc_vcpu, fki_utcb_desched_ipi, u, 1);
+ }
+ }
+ if (u->fault_ep)
+ l4h_slot_delete(u->fault_ep);
+ fki_as_put(utcb->as);
+ utcb->as = NULL;
+ l4h_obj_free(&utcb->reply_obj);
+ l4h_obj_free(&utcb->tcb_obj);
+ kfree(utcb);
+}
+EXPORT_SYMBOL(fki_utcb_destroy);
+
+int fki_utcb_set_as(void *utcb_ptr, void *as_ptr)
+{
+ struct fki_utcb *utcb = utcb_ptr;
+ struct fki_as *new_as = as_ptr;
+ struct fki_as *old_as;
+ unsigned long flags;
+ bool ok;
+
+ if (!utcb || !new_as)
+ return -EINVAL;
+ if (utcb->as == new_as)
+ return READ_ONCE(new_as->dead) ? -EINVAL : 0;
+ spin_lock_irqsave(&new_as->lock, flags);
+ ok = !READ_ONCE(new_as->dead) && fki_as_get(new_as);
+ spin_unlock_irqrestore(&new_as->lock, flags);
+ if (!ok)
+ return -EINVAL;
+ old_as = utcb->as;
+ utcb->as = new_as;
+ fki_as_put(old_as);
+ return 0;
+}
+EXPORT_SYMBOL(fki_utcb_set_as);
+
+int fki_utcb_set_pac(void *utcb_ptr, const struct fki_pac_keys *keys)
+{
+ struct fki_utcb *utcb = utcb_ptr;
+ unsigned long words[L4H_PAC_KEY_WORDS];
+ unsigned long en;
+ int err;
+
+ if (!utcb || !keys)
+ return -EINVAL;
+ en = sctlr_to_l4h_pac_en(keys->sctlr_en);
+ if (!(l4h_provider_features() & L4H_PROVIDER_ARM_PAC)) {
+ if (en)
+ return -EOPNOTSUPP;
+ utcb->last_pac = *keys;
+ utcb->have_pac = true;
+ return 0;
+ }
+ if (utcb->have_pac && memcmp(&utcb->last_pac, keys, sizeof(*keys)) == 0)
+ return 0;
+
+ if (!en) {
+ err = l4h_tcb_set_pac(utcb->u.tcb, 0, NULL);
+ } else {
+ words[0] = keys->ia[0]; words[1] = keys->ia[1];
+ words[2] = keys->ib[0]; words[3] = keys->ib[1];
+ words[4] = keys->da[0]; words[5] = keys->da[1];
+ words[6] = keys->db[0]; words[7] = keys->db[1];
+ words[8] = keys->ga[0]; words[9] = keys->ga[1];
+ err = l4h_tcb_set_pac(utcb->u.tcb, en, words);
+ }
+ if (err == FKI_L4H_ERR_ILLEGAL_OP)
+ return -EOPNOTSUPP;
+ if (err)
+ return -EIO;
+ utcb->last_pac = *keys;
+ utcb->have_pac = true;
+ return 0;
+}
+EXPORT_SYMBOL(fki_utcb_set_pac);
+
+static int fki_utcb_run_inner(void *utcb_ptr, struct fki_utcb_regs *regs,
+ struct fki_utcb_stop *stop, bool resume_unchanged)
+{
+ struct fki_utcb *utcb = utcb_ptr;
+ struct fki_kmem *km;
+ struct l4h_uctx *u;
+ struct fki_as *as;
+ struct fki_vs_slot *slot;
+ struct l4h_user_ext ext;
+ unsigned long gp[37];
+ u64 gen = 0;
+ bool as_changed, tls_ro_changed, fast_resume;
+ int st, i, idx;
+
+ if (!utcb || !regs || !stop || !utcb->as)
+ return -EINVAL;
+ km = fki_kmem_get();
+ if (!km)
+ return -EINVAL;
+ u = &utcb->u;
+ as = utcb->as;
+
+ atomic_inc(&as->active_cpus);
+ smp_mb__after_atomic();
+ if (READ_ONCE(as->dead)) {
+ atomic_dec(&as->active_cpus);
+ fki_kmem_put(km);
+ return -EINVAL;
+ }
+ idx = smp_load_acquire(&as->vs_idx);
+ if (likely(idx >= 0 && fki_vs_pool)) {
+ gen = READ_ONCE(as->gen);
+ slot = &fki_vs_pool[idx];
+ } else {
+ slot = fki_vs_activate(as, &gen);
+ if (!slot) {
+ bool is_dead = READ_ONCE(as->dead);
+
+ atomic_dec(&as->active_cpus);
+ fki_kmem_put(km);
+ return is_dead ? -EINVAL : -ENOMEM;
+ }
+ }
+
+ as_changed = (u->vspace != slot->root || utcb->as_gen != gen);
+ if (as_changed) {
+ int err;
+
+ if (u->state == L4H_UCTX_FRESH && !u->vspace)
+ err = l4h_tcb_configure_user(u->tcb, l4h_empty_cnode_cptr(), slot->root);
+ else
+ err = l4h_tcb_set_space(u->tcb, u->fault_ep, l4h_empty_cnode_cptr(), slot->root);
+ if (err) {
+ atomic_dec(&as->active_cpus);
+ fki_kmem_put(km);
+ pr_err("fki: binding user TCB to VSpace failed: %d\n", err);
+ return -EIO;
+ }
+ u->vspace = slot->root;
+ utcb->as_gen = gen;
+ }
+
+ fast_resume = (resume_unchanged && !as_changed && !u->regs_valid &&
+ u->state == L4H_UCTX_FAULTED &&
+ utcb->have_tls && regs->tpidrro == utcb->last_tpidrro);
+ if (!fast_resume) {
+ if (resume_unchanged && !u->regs_valid) {
+ /*
+ * Stopped on a page fault with live GP registers still in the
+ * TCB, but could not take fast_resume (e.g. VSpace eviction
+ * forced a rebind): read the real TCB state instead of
+ * overwriting it with stale regs[].
+ */
+ l4h_user_sync_regs(u, gp);
+ gp[34] = 0;
+ gp[36] = 0;
+ } else {
+ for (i = 0; i < 31; i++)
+ gp[i] = (unsigned long)regs->x[i];
+ gp[31] = (unsigned long)regs->sp;
+ gp[32] = (unsigned long)regs->pc;
+ gp[33] = (unsigned long)(regs->pstate & 0xf0000000UL);
+ gp[34] = 0;
+ gp[L4H_GP_TLS] = (unsigned long)regs->tpidr;
+ gp[36] = 0;
+ }
+
+ tls_ro_changed = (!utcb->have_tls ||
+ regs->tpidrro != utcb->last_tpidrro ||
+ as_changed ||
+ u->state == L4H_UCTX_FRESH);
+ l4h_user_mark_dirty(u, tls_ro_changed ? 1 : 0);
+ } else {
+ tls_ro_changed = false;
+ }
+
+ ext.size = sizeof(ext);
+ ext.flags = L4H_USER_EXT_TLS_RO |
+ (tls_ro_changed ? L4H_USER_EXT_TLS_RO_UPDATE : 0);
+ ext.tls_ro = (unsigned long)regs->tpidrro;
+ ext.raw_fsr = 0;
+
+ this_cpu_write(fki_cur_utcb, u);
+ st = l4h_user_run_ex(u, gp, 1, &ext);
+ if (st == L4H_STOP_PAGEFAULT) {
+ atomic_dec(&as->active_cpus);
+ fki_kmem_put(km);
+ utcb->last_tpidrro = regs->tpidrro;
+ utcb->have_tls = true;
+ stop->kind = FKI_STOP_PAGEFAULT;
+ stop->esr = ext.raw_fsr;
+ stop->fault_addr = u->fault_addr;
+ stop->fault_ip = u->fault_ip;
+ return 0;
+ }
+ if (!u->regs_valid)
+ l4h_user_sync_regs(u, gp);
+
+ atomic_dec(&as->active_cpus);
+ fki_kmem_put(km);
+
+ for (i = 0; i < 31; i++)
+ regs->x[i] = gp[i];
+ regs->sp = gp[31];
+ regs->pc = gp[32];
+ regs->pstate = gp[33];
+ regs->tpidr = gp[L4H_GP_TLS];
+ utcb->last_tpidr = regs->tpidr;
+ utcb->last_tpidrro = regs->tpidrro;
+ utcb->have_tls = true;
+
+ switch (st) {
+ case L4H_STOP_SYSCALL:
+ stop->kind = FKI_STOP_SYSCALL;
+ stop->esr = (0x15ULL << 26) | (1ULL << 25) | 0x80ULL;
+ stop->fault_ip = gp[32];
+ stop->fault_addr = 0;
+ break;
+ case L4H_STOP_EXCEPTION:
+ stop->kind = FKI_STOP_EXCEPTION;
+ stop->esr = u->exc_number;
+ stop->fault_addr = u->fault_addr;
+ stop->fault_ip = u->fault_ip;
+ break;
+ case L4H_STOP_INTERRUPT:
+ stop->kind = FKI_STOP_INTERRUPT;
+ stop->esr = ~0ULL;
+ stop->fault_addr = 0;
+ stop->fault_ip = gp[32];
+ break;
+ default:
+ return -EIO;
+ }
+ return 0;
+}
+
+int fki_utcb_run(void *utcb_ptr, struct fki_utcb_regs *regs, struct fki_utcb_stop *stop)
+{
+ return fki_utcb_run_inner(utcb_ptr, regs, stop, false);
+}
+EXPORT_SYMBOL(fki_utcb_run);
+
+int fki_utcb_resume(void *utcb_ptr, struct fki_utcb_regs *regs, struct fki_utcb_stop *stop)
+{
+ return fki_utcb_run_inner(utcb_ptr, regs, stop, true);
+}
+EXPORT_SYMBOL(fki_utcb_resume);
+
+int fki_utcb_sync_regs(void *utcb_ptr, struct fki_utcb_regs *regs)
+{
+ struct fki_utcb *utcb = utcb_ptr;
+ struct l4h_uctx *u;
+ unsigned long gp[37];
+ int i;
+
+ if (!utcb || !regs)
+ return -EINVAL;
+ u = &utcb->u;
+ if (u->regs_valid)
+ return 0;
+ l4h_user_sync_regs(u, gp);
+ for (i = 0; i < 31; i++)
+ regs->x[i] = gp[i];
+ regs->sp = gp[31];
+ regs->pc = gp[32];
+ regs->pstate = gp[33];
+ regs->tpidr = gp[L4H_GP_TLS];
+ utcb->last_tpidr = regs->tpidr;
+ return 0;
+}
+EXPORT_SYMBOL(fki_utcb_sync_regs);
+
+int fki_utcb_fpu_read(void *utcb_ptr, void *buf, unsigned long len)
+{
+ struct fki_utcb *utcb = utcb_ptr;
+
+ if (!utcb || !buf || !len)
+ return -EINVAL;
+ if (utcb->u.state == L4H_UCTX_FRESH) {
+ memset(buf, 0, len);
+ return 0;
+ }
+ return l4h_fpu_read(&utcb->u, buf, len) ? -EIO : 0;
+}
+EXPORT_SYMBOL(fki_utcb_fpu_read);
+
+int fki_utcb_fpu_write(void *utcb_ptr, const void *buf, unsigned long len)
+{
+ struct fki_utcb *utcb = utcb_ptr;
+
+ if (!utcb || !buf || !len)
+ return -EINVAL;
+ return l4h_fpu_write(&utcb->u, buf, len) ? -EIO : 0;
+}
+EXPORT_SYMBOL(fki_utcb_fpu_write);
+
+/* ---- arch init / exit ---- */
+
+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;
+ }
+}
+
+int fki_arch_init(void)
+{
+ int 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);
+ }
+ return 0;
+}
+
+void fki_arch_exit(void)
+{
+ fki_free_alt_stacks();
+}
diff --git a/fki-ko/fki_mod.c b/fki-ko/fki_mod.c
deleted file mode 100644
index a8541dd..0000000
--- a/fki-ko/fki_mod.c
+++ /dev/null
@@ -1,1122 +0,0 @@
-// SPDX-License-Identifier: GPL-2.0-only
-/*
- * Foreign kernel interface, version 0: see include/linux/fki.h.
- *
- * Exports are plain EXPORT_SYMBOL on purpose: this file defines a narrow,
- * stable, semantic interface of its own, and nothing behind it is
- * re-exported.
- */
-#include "fki.h"
-#include "fki_internal.h"
-#include <linux/firmware.h>
-#include <linux/gfp.h>
-#include <linux/irqflags.h>
-#include <linux/mm.h>
-#include <linux/io.h>
-#include <linux/efi.h>
-#include <linux/ioport.h>
-#include <linux/module.h>
-#include <linux/preempt.h>
-#include <linux/printk.h>
-#include <linux/random.h>
-#include <linux/slab.h>
-#include <linux/timekeeping.h>
-#include <linux/sched.h>
-#include <linux/cpumask.h>
-#include <linux/vmalloc.h>
-#include <asm/arch_timer.h>
-#include <asm/neon.h>
-#include <asm/sysreg.h>
-#include <asm/tlbflush.h>
-#include <asm/barrier.h>
-#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>
-#include <linux/fs.h>
-#include <asm/stacktrace.h>
-#include <linux/netdevice.h>
-#include <linux/etherdevice.h>
-#include <linux/skbuff.h>
-
-int fki_version(void)
-{
- return FKI_VERSION;
-}
-EXPORT_SYMBOL(fki_version);
-
-void fki_log(const char *s, unsigned long len)
-{
- pr_info("fki: %.*s\n", (int)len, s);
-}
-EXPORT_SYMBOL(fki_log);
-/* what an operator must see even with the console quiet (an XNU panic, a CPU gone silent): KERN_ALERT */
-void fki_log_alert(const char *s, unsigned long len)
-{
- pr_alert("fki: %.*s\n", (int)len, s);
-}
-EXPORT_SYMBOL(fki_log_alert);
-
-
-/*
- * Out-of-tree form only: stock kernels do not export set_memory_x(). The in-tree FKI
- * patch calls it directly; here it is found once through kallsyms (via a kprobe).
- */
-typedef int (*set_memory_fn)(unsigned long addr, int numpages);
-typedef struct page *(*alloc_contig_fn)(unsigned long nr_pages, gfp_t gfp, int nid, nodemask_t *nodemask);
-typedef void (*free_contig_fn)(unsigned long pfn, unsigned long nr_pages);
-static alloc_contig_fn p_alloc_contig;
-static free_contig_fn p_free_contig;
-struct cma;
-static struct cma **p_cma_area; /* the default CMA area (cma= on the command line), if any */
-static struct page *(*p_cma_alloc)(struct cma *, unsigned long, unsigned int, bool); /* not exported on every kernel */
-static bool (*p_cma_release)(struct cma *, const struct page *, unsigned long);
-static set_memory_fn p_set_memory_x, p_set_memory_nx;
-static unsigned long p_stext, p_end;
-static u64 *p_kimage_voffset;
-static int (*p_efi_mem_type)(unsigned long); /* the firmware's memory map: is the carve-out RAM at all */
-
-static int fki_resolve(void)
-{
- static unsigned long (*lookup)(const char *);
- struct kprobe kp = { .symbol_name = "kallsyms_lookup_name" };
-
- if (p_set_memory_x)
- return 0;
- if (!lookup) {
- if (register_kprobe(&kp))
- return -ENOENT;
- lookup = (void *)kp.addr;
- unregister_kprobe(&kp);
- }
- p_set_memory_x = (set_memory_fn)lookup("set_memory_x");
- p_alloc_contig = (alloc_contig_fn)lookup("alloc_contig_pages_noprof");
- if (!p_alloc_contig)
- p_alloc_contig = (alloc_contig_fn)lookup("alloc_contig_pages");
- p_free_contig = (free_contig_fn)lookup("free_contig_range");
- p_cma_area = (struct cma **)lookup("dma_contiguous_default_area");
- p_cma_alloc = (void *)lookup("cma_alloc");
- p_cma_release = (void *)lookup("cma_release");
- p_set_memory_nx = (set_memory_fn)lookup("set_memory_nx");
- p_stext = lookup("_stext");
- p_end = lookup("_end");
- p_kimage_voffset = (u64 *)lookup("kimage_voffset");
- p_efi_mem_type = (void *)lookup("efi_mem_type");
- return p_set_memory_x && p_set_memory_nx ? 0 : -ENOENT;
-}
-
-int fki_region_alloc(unsigned long size, struct fki_region *r)
-{
- unsigned long n = PAGE_ALIGN(size) >> PAGE_SHIFT;
- void *va;
- int err;
-
- /* vmap() memory is never executable on current kernels; vmalloc + set_memory_x is (out-of-tree form). */
- err = fki_resolve();
- if (err)
- return err;
- va = vzalloc(n << PAGE_SHIFT);
- if (!va)
- return -ENOMEM;
- err = p_set_memory_x((unsigned long)va, n);
- if (err) {
- vfree(va);
- return err;
- }
- r->va = va;
- r->pa = page_to_phys(vmalloc_to_page(va));
- r->size = n << PAGE_SHIFT;
- r->handle = NULL;
- return 0;
-}
-EXPORT_SYMBOL(fki_region_alloc);
-
-void fki_region_free(struct fki_region *r)
-{
- p_set_memory_nx((unsigned long)r->va, r->size >> PAGE_SHIFT);
- vfree(r->va);
-}
-EXPORT_SYMBOL(fki_region_free);
-
-int fki_blob_get(const char *name, const void **data, unsigned long *size, void **handle)
-{
- const struct firmware *fw;
- int err = request_firmware(&fw, name, NULL);
-
- if (err)
- return err;
- *data = fw->data;
- *size = fw->size;
- *handle = (void *)fw;
- return 0;
-}
-EXPORT_SYMBOL(fki_blob_get);
-
-void fki_blob_put(void *handle)
-{
- release_firmware(handle);
-}
-EXPORT_SYMBOL(fki_blob_put);
-
-#define FKI_SCTLR_EN (SCTLR_ELx_ENIA | SCTLR_ELx_ENIB | SCTLR_ELx_ENDA | SCTLR_ELx_ENDB)
-
-
-static __always_inline void keys_read(struct fki_pac_keys *k)
-{
- k->ia[0] = read_sysreg_s(SYS_APIAKEYLO_EL1); k->ia[1] = read_sysreg_s(SYS_APIAKEYHI_EL1);
- k->ib[0] = read_sysreg_s(SYS_APIBKEYLO_EL1); k->ib[1] = read_sysreg_s(SYS_APIBKEYHI_EL1);
- k->da[0] = read_sysreg_s(SYS_APDAKEYLO_EL1); k->da[1] = read_sysreg_s(SYS_APDAKEYHI_EL1);
- k->db[0] = read_sysreg_s(SYS_APDBKEYLO_EL1); k->db[1] = read_sysreg_s(SYS_APDBKEYHI_EL1);
- k->ga[0] = read_sysreg_s(SYS_APGAKEYLO_EL1); k->ga[1] = read_sysreg_s(SYS_APGAKEYHI_EL1);
- k->sctlr_en = read_sysreg(sctlr_el1) & FKI_SCTLR_EN;
-}
-
-static __always_inline void keys_write(const struct fki_pac_keys *k)
-{
- write_sysreg_s(k->ia[0], SYS_APIAKEYLO_EL1); write_sysreg_s(k->ia[1], SYS_APIAKEYHI_EL1);
- write_sysreg_s(k->ib[0], SYS_APIBKEYLO_EL1); write_sysreg_s(k->ib[1], SYS_APIBKEYHI_EL1);
- write_sysreg_s(k->da[0], SYS_APDAKEYLO_EL1); write_sysreg_s(k->da[1], SYS_APDAKEYHI_EL1);
- write_sysreg_s(k->db[0], SYS_APDBKEYLO_EL1); write_sysreg_s(k->db[1], SYS_APDBKEYHI_EL1);
- write_sysreg_s(k->ga[0], SYS_APGAKEYLO_EL1); write_sysreg_s(k->ga[1], SYS_APGAKEYHI_EL1);
- sysreg_clear_set(sctlr_el1, FKI_SCTLR_EN, k->sctlr_en & FKI_SCTLR_EN);
- isb();
-}
-
-/*
- * The foreign kernel uses the FP/SIMD registers (its user threads' state, its own SIMD code) without Linux knowing.
- * Linux skips reloading a task's FP/SIMD state when it believes this CPU's registers still hold it, so a task that ran
- * here before would come back with the foreign kernel's register contents (random user-space crashes on the hosted
- * kernel's CPU). Before the foreign kernel runs (on entry, and each time it resumes after Linux ran), save the current
- * task's state and make Linux forget whose state the registers hold: an empty kernel-mode NEON section does both.
- * Nothing of the foreign kernel's needs keeping across that: its kernel code does not keep FP/SIMD values across calls
- * into the host, and it saves its user threads' registers on each exception.
- */
-static void fki_fpsimd_forget(void)
-{
- struct user_fpsimd_state scratch; /* where Linux would save a kernel-mode state over a context switch: none here */
-
- kernel_neon_begin(&scratch);
- kernel_neon_end(&scratch);
-}
-
-__attribute__((target("branch-protection=none"))) unsigned long fki_enter(const struct fki_pac_keys *foreign, struct fki_pac_keys *saved)
-{
- unsigned long flags;
-
- fki_fpsimd_forget();
- preempt_disable();
- local_irq_save(flags);
- keys_read(saved);
- keys_write(foreign);
- return flags;
-}
-EXPORT_SYMBOL(fki_enter);
-
-__attribute__((target("branch-protection=none"))) void fki_leave(unsigned long cookie, const struct fki_pac_keys *saved)
-{
- keys_write(saved);
- local_irq_restore(cookie);
- preempt_enable();
-}
-EXPORT_SYMBOL(fki_leave);
-
-__attribute__((target("branch-protection=none"))) void fki_pac_swap(const struct fki_pac_keys *load, struct fki_pac_keys *save)
-{
- keys_read(save);
- keys_write(load);
-}
-EXPORT_SYMBOL(fki_pac_swap);
-
-fki_u64 fki_counter_frequency(void)
-{
- return arch_timer_get_cntfrq();
-}
-EXPORT_SYMBOL(fki_counter_frequency);
-
-fki_u64 fki_counter(void)
-{
- return __arch_counter_get_cntvct();
-}
-EXPORT_SYMBOL(fki_counter);
-
-void fki_random(void *buf, unsigned long len)
-{
- get_random_bytes(buf, len);
-}
-EXPORT_SYMBOL(fki_random);
-
-int fki_random_wait(void)
-{
- return wait_for_random_bytes();
-}
-EXPORT_SYMBOL(fki_random_wait);
-
-/*
- * cpu_list: the Linux CPUs of the foreign kernel's CPUs 0 .. n-1 (default: the same numbers). For machines where two
- * CPUs share a block-device interrupt (an NVMe with fewer queues than CPUs), which deadlocks two foreign CPUs on them.
- */
-static int cpu_list[NR_CPUS];
-static int cpu_list_n;
-module_param_array(cpu_list, int, &cpu_list_n, 0444);
-
-static int fki_cpu_map(int cpu)
-{
- if (!cpu_list_n)
- return cpu;
- return cpu >= 0 && cpu < cpu_list_n ? cpu_list[cpu] : -1;
-}
-
-int fki_bind_cpu(int cpu)
-{
- cpu = fki_cpu_map(cpu);
- if (cpu < 0 || cpu >= nr_cpu_ids || !cpu_online(cpu))
- return -EINVAL;
- return set_cpus_allowed_ptr(current, cpumask_of(cpu));
-}
-EXPORT_SYMBOL(fki_bind_cpu);
-
-void *fki_thread_start(int (*fn)(void *), void *arg, int cpu, const char *name)
-{
- struct task_struct *t;
-
- cpu = fki_cpu_map(cpu);
- if (cpu < 0 || cpu >= nr_cpu_ids || !cpu_online(cpu))
- return NULL;
- t = kthread_create(fn, arg, "%s", name);
- if (IS_ERR(t))
- return NULL;
- kthread_bind(t, cpu);
- get_task_struct(t);
- wake_up_process(t);
- return t;
-}
-EXPORT_SYMBOL(fki_thread_start);
-
-void fki_thread_stop(void *thread)
-{
- if (thread) {
- kthread_stop(thread);
- put_task_struct(thread);
- }
-}
-EXPORT_SYMBOL(fki_thread_stop);
-
-int fki_thread_should_stop(void)
-{
- return kthread_should_stop();
-}
-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)
-{
- unsigned long t = msecs_to_jiffies(ms) + 1;
-
- while (t) /* as msleep, but not counted in the load average */
- t = schedule_timeout_idle(t);
-}
-EXPORT_SYMBOL(fki_msleep);
-
-/*
- * Foreign kernel faults. Out of tree, the hook is a kprobe on __do_kernel_fault(far, esr, regs), where Linux's abort path
- * goes for a kernel address it has no mapping for (do_mem_abort and do_translation_fault cannot be probed). When
- * the handler resolves the fault, __do_kernel_fault is skipped (return to its caller), and the exception returns to retry
- * the access. The in-tree patch calls the hook from do_translation_fault/do_page_fault directly.
- */
-static unsigned long fki_fault_lo, fki_fault_hi;
-static int (*fki_fault_handler)(unsigned long far, unsigned long esr, void *regs);
-
-static int fki_fault_pre(struct kprobe *p, struct pt_regs *kregs)
-{
- unsigned long far = kregs->regs[0], esr = kregs->regs[1];
- struct pt_regs *regs = (struct pt_regs *)kregs->regs[2];
- int (*h)(unsigned long, unsigned long, void *) = READ_ONCE(fki_fault_handler);
-
- if (!h || user_mode(regs))
- return 0;
- if ((far < fki_fault_lo || far >= fki_fault_hi) &&
- (instruction_pointer(regs) < fki_fault_lo || instruction_pointer(regs) >= fki_fault_hi))
- return 0;
- if (h(far, esr, regs))
- return 0;
- instruction_pointer_set(kregs, kregs->regs[30]); /* __do_kernel_fault returns at once */
- return 1;
-}
-NOKPROBE_SYMBOL(fki_fault_pre);
-
-unsigned long fki_regs_pc(void *regs) { return instruction_pointer((struct pt_regs *)regs); }
-EXPORT_SYMBOL(fki_regs_pc);
-unsigned long fki_regs_lr(void *regs) { return ((struct pt_regs *)regs)->regs[30]; }
-EXPORT_SYMBOL(fki_regs_lr);
-unsigned long fki_regs_pstate(void *regs) { return ((struct pt_regs *)regs)->pstate; }
-EXPORT_SYMBOL(fki_regs_pstate);
-void fki_regs_set_pc(void *regs, unsigned long pc) { instruction_pointer_set((struct pt_regs *)regs, pc); }
-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;
-
-/*
- * Other kernel-mode exceptions the foreign kernel takes (an FPAC authentication failure, an undefined instruction, a
- * BTI fault) end in die(str, regs, err): offered to the same handler with far 0 and the ESR, before Linux oopses.
- */
-static int fki_die_pre(struct kprobe *p, struct pt_regs *kregs)
-{
- struct pt_regs *regs = (struct pt_regs *)kregs->regs[1];
- unsigned long esr = kregs->regs[2];
- int (*h)(unsigned long, unsigned long, void *) = READ_ONCE(fki_fault_handler);
-
- if (!h || !regs || user_mode(regs))
- return 0;
- if (instruction_pointer(regs) < fki_fault_lo || instruction_pointer(regs) >= fki_fault_hi)
- return 0;
- if (h(0, esr, regs))
- return 0;
- instruction_pointer_set(kregs, kregs->regs[30]); /* die returns at once */
- return 1;
-}
-NOKPROBE_SYMBOL(fki_die_pre);
-static struct kprobe fki_die_kp = { .symbol_name = "die", .pre_handler = fki_die_pre };
-static int fki_die_registered;
-
-int fki_fault_register(unsigned long lo, unsigned long hi, int (*handler)(unsigned long far, unsigned long esr, void *regs))
-{
- int err;
-
- if (fki_fault_registered)
- return -EBUSY;
- fki_fault_lo = lo;
- fki_fault_hi = hi;
- WRITE_ONCE(fki_fault_handler, handler);
- err = register_kprobe(&fki_fault_kp);
- if (err) {
- WRITE_ONCE(fki_fault_handler, NULL);
- return err;
- }
- fki_fault_registered = 1;
- fki_die_registered = register_kprobe(&fki_die_kp) == 0; /* best effort */
- if (!fki_die_registered)
- pr_warn("fki: no die() probe: foreign non-abort exceptions oops\n");
- return 0;
-}
-EXPORT_SYMBOL(fki_fault_register);
-
-void fki_fault_unregister(void)
-{
- if (!fki_fault_registered)
- return;
- unregister_kprobe(&fki_fault_kp);
- if (fki_die_registered) {
- unregister_kprobe(&fki_die_kp);
- fki_die_registered = 0;
- memset(&fki_die_kp, 0, sizeof(fki_die_kp));
- fki_die_kp.symbol_name = "die";
- fki_die_kp.pre_handler = fki_die_pre;
- }
- WRITE_ONCE(fki_fault_handler, NULL);
- fki_fault_registered = 0;
- /* a fresh kprobe struct for the next registration */
- memset(&fki_fault_kp, 0, sizeof(fki_fault_kp));
- fki_fault_kp.symbol_name = "__do_kernel_fault";
- fki_fault_kp.pre_handler = fki_fault_pre;
-}
-EXPORT_SYMBOL(fki_fault_unregister);
-
-fki_u64 fki_phys_peek(fki_u64 pa)
-{
- if (!pfn_valid(PHYS_PFN(pa)))
- return ~0ULL;
- return READ_ONCE(*(u64 *)phys_to_virt(pa & ~7ULL));
-}
-EXPORT_SYMBOL(fki_phys_peek);
-
-/* ---- contiguous memory and the top foreign window ---- */
-
-/*
- * The foreign kernel's DRAM, one physically contiguous block of GBs, from the first that works of:
- * - carve_base/carve_mb: RAM the host kernel does not manage at all (its command line limits it with mem=, the rest is
- * left for us), mapped here with memremap. Nothing of Linux's ever lands in it: the block is always there.
- * - reserve_mb: taken from the CMA area when fki loads early in the host's boot. A single page pinned in the area
- * (a file system's buffer-head page of the block device, allocated movable during the boot) can already be there
- * and split the area, so this is best effort.
- * - a CMA or alloc_contig_pages allocation at the time of the call.
- */
-static unsigned long carve_base, carve_mb, reserve_mb;
-module_param(carve_base, ulong, 0444);
-module_param(carve_mb, ulong, 0444);
-module_param(reserve_mb, ulong, 0444);
-static struct page *resv_pg;
-static unsigned long resv_cnt;
-static bool resv_used, carve_used;
-
-static void fki_reserve(void)
-{
- unsigned long cnt = ALIGN(reserve_mb << 20, SZ_2M) >> PAGE_SHIFT;
-
- if (carve_mb)
- pr_info("fki: %lu MiB at %#lx for the foreign kernel's DRAM (outside the host's memory)\n", carve_mb, carve_base);
- if (!reserve_mb || fki_resolve() || !p_cma_area || !*p_cma_area || !p_cma_alloc)
- return;
- resv_pg = p_cma_alloc(*p_cma_area, cnt, get_order(SZ_2M), true);
- if (resv_pg)
- resv_cnt = cnt;
- pr_info("fki: %lu MiB for the foreign kernel's DRAM %s\n", reserve_mb, resv_pg ? "reserved" : "NOT reserved (CMA)");
-}
-
-static int fki_carve_check(unsigned long base, unsigned long len)
-{
- unsigned long end = base + len;
-
- if (end < base) {
- pr_err("fki: carve-out [%#lx, %#lx) overflows physical address space\n", base, end);
- return -EINVAL;
- }
- /* RAM in the firmware's map, every 2 MiB of it: a carve-out past the end of the VM's memory (carve_base from a
- * bigger VM) would map addresses with nothing behind them */
- if (p_efi_mem_type && p_efi_mem_type(base) >= 0) { /* < 0: no EFI memory map (not an EFI boot) */
- unsigned long a;
-
- for (a = base; a < end; a += SZ_2M) {
- int t = p_efi_mem_type(a);
-
- /* free RAM once Linux runs: loader and boot-services code and data, conventional memory */
- if (t != EFI_LOADER_CODE && t != EFI_LOADER_DATA && t != EFI_BOOT_SERVICES_CODE &&
- t != EFI_BOOT_SERVICES_DATA && t != EFI_CONVENTIONAL_MEMORY) {
- pr_err("fki: carve-out [%#lx, %#lx) is not all RAM (EFI type %d at %#lx); refusing to map (check carve_base, carve_mb and the VM's memory size)\n",
- base, end, t, a);
- return -EINVAL;
- }
- }
- }
- if (p_stext && p_end && p_kimage_voffset) {
- unsigned long k_start = p_stext - *p_kimage_voffset;
- unsigned long k_end = p_end - *p_kimage_voffset;
-
- if (base < k_end && k_start < end) {
- pr_err("fki: carve-out [%#lx, %#lx) overlaps Linux kernel image [%#lx, %#lx); refusing to map (boot with nokaslr or adjust carve_base)\n",
- base, end, k_start, k_end);
- return -EBUSY;
- }
- }
- if (region_intersects(base, len, IORESOURCE_SYSTEM_RAM, IORES_DESC_NONE) != REGION_DISJOINT) {
- pr_err("fki: carve-out [%#lx, %#lx) overlaps IORESOURCE_SYSTEM_RAM; refusing to map (check mem= and carve_base)\n",
- base, end);
- return -EBUSY;
- }
- if (region_intersects(base, len, IORESOURCE_MEM, IORES_DESC_NONE) != REGION_DISJOINT) {
- pr_err("fki: carve-out [%#lx, %#lx) overlaps busy/reserved IORESOURCE_MEM; refusing to map (check /proc/iomem and carve_base)\n",
- base, end);
- return -EBUSY;
- }
- return 0;
-}
-
-int fki_contig_alloc(unsigned long size, struct fki_region *r)
-{
- unsigned long n = 1;
- struct page *pg;
- int err = fki_resolve();
-
- if (err)
- return err;
- if (carve_mb && !carve_used && ALIGN(size, SZ_2M) <= carve_mb << 20 && !(carve_base & (SZ_2M - 1))) {
- unsigned long clen = ALIGN(size, SZ_2M);
- void *va;
-
- err = fki_carve_check(carve_base, clen);
- if (err)
- return err;
- va = memremap(carve_base, clen, MEMREMAP_WB);
- if (va) {
- carve_used = true;
- r->va = va;
- r->size = clen;
- memset(r->va, 0, r->size);
- r->pa = carve_base;
- r->handle = (void *)4UL; /* bit 2: the carve-out */
- return 0;
- }
- pr_warn("fki: carve-out at %#lx not mappable\n", carve_base);
- }
- if (resv_pg && !resv_used && ALIGN(size, SZ_2M) >> PAGE_SHIFT <= resv_cnt) {
- resv_used = true;
- r->va = page_address(resv_pg);
- r->size = ALIGN(size, SZ_2M);
- memset(r->va, 0, r->size);
- r->pa = page_to_phys(resv_pg);
- r->handle = (void *)((unsigned long)resv_pg | 2); /* bit 1: the reservation, kept when freed */
- return 0;
- }
- /*
- * Large blocks (a hosted kernel's DRAM, GBs) come from the CMA area when there is one: a long-running host
- * fragments its memory with unmovable pages and alloc_contig_pages then fails. CMA blocks are 2 MiB aligned
- * and sized to 2 MiB; a CMA block's handle has bit 0 set.
- */
- if (size >= (64UL << 20) && p_cma_area && *p_cma_area && p_cma_alloc && p_cma_release) {
- unsigned long cnt = ALIGN(size, SZ_2M) >> PAGE_SHIFT;
- pg = p_cma_alloc(*p_cma_area, cnt, get_order(SZ_2M), true);
- if (pg) {
- r->va = page_address(pg);
- memset(r->va, 0, cnt << PAGE_SHIFT);
- r->pa = page_to_phys(pg);
- r->size = cnt << PAGE_SHIFT;
- r->handle = (void *)((unsigned long)pg | 1);
- return 0;
- }
- }
- if (!p_alloc_contig)
- return -ENOENT;
- while ((n << PAGE_SHIFT) < size)
- n <<= 1;
- pg = p_alloc_contig(n, GFP_KERNEL | __GFP_NOWARN, numa_node_id(), NULL);
- if (!pg)
- return -ENOMEM;
- r->va = page_address(pg);
- memset(r->va, 0, n << PAGE_SHIFT);
- r->pa = page_to_phys(pg);
- r->size = n << PAGE_SHIFT;
- r->handle = pg;
- return 0;
-}
-EXPORT_SYMBOL(fki_contig_alloc);
-
-void fki_contig_free(struct fki_region *r)
-{
- if ((unsigned long)r->handle == 4) {
- memunmap(r->va);
- carve_used = false;
- return;
- }
- if ((unsigned long)r->handle & 2) {
- resv_used = false; /* back to the reservation, for the next run */
- return;
- }
- if ((unsigned long)r->handle & 1) {
- p_cma_release(*p_cma_area, (struct page *)((unsigned long)r->handle & ~1UL), r->size >> PAGE_SHIFT);
- return;
- }
- if (p_free_contig)
- p_free_contig(page_to_pfn((struct page *)r->handle), r->size >> PAGE_SHIFT);
-}
-EXPORT_SYMBOL(fki_contig_free);
-
-int fki_window_l1(unsigned long va, unsigned long long **l1_va, fki_u64 *l1_pa)
-{
- u64 ttbr1 = read_sysreg(ttbr1_el1) & GENMASK_ULL(47, 1);
- u64 *l0 = phys_to_virt(ttbr1 & ~0xfffULL);
- u64 e = READ_ONCE(l0[(va >> 39) & 511]);
-
- if ((e & 3) != 3)
- return -ENOENT;
- *l1_pa = e & GENMASK_ULL(47, 12);
- *l1_va = phys_to_virt(*l1_pa);
- return 0;
-}
-EXPORT_SYMBOL(fki_window_l1);
-
-void fki_window_set(unsigned long long *slot, fki_u64 desc)
-{
- WRITE_ONCE(*slot, desc);
- dsb(ishst);
- __tlbi(vmalle1is);
- dsb(ish);
- isb();
-}
-EXPORT_SYMBOL(fki_window_set);
-
-/*
- * Letting Linux run (IRQs on, maybe a reschedule) from inside fki_enter() happens on whatever stack the foreign kernel
- * is on. Linux's exception entry takes a stack whose bit THREAD_SHIFT is set at sp for an overflow and panics, so
- * 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]; /* 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"
-" .type fki_run_on_stack, %function\n"
-"fki_run_on_stack:\n"
-" hint #34\n"
-" stp x29, x30, [sp, #-16]!\n"
-" mov x29, sp\n"
-" mov x9, sp\n"
-" mov sp, x2\n"
-" stp x9, xzr, [sp, #-16]!\n"
-" mov x9, x0\n"
-" mov x0, x1\n"
-" blr x9\n"
-" ldp x9, xzr, [sp], #16\n"
-" mov sp, x9\n"
-" ldp x29, x30, [sp], #16\n"
-" ret\n"
-" .size fki_run_on_stack, . - fki_run_on_stack\n"
-" .popsection\n");
-void fki_run_on_stack(void (*fn)(void *), void *arg, void *top); /* x0 = fn, x1 = arg, x2 = stack top */
-
-static void fki_linux_runs_body(void (*fn)(void *), void *arg);
-
-/*
- * Linux runs with SError (PSTATE.A) unmasked; the foreign kernel keeps D, A, I and F masked and asserts so in its
- * idle loop. Give it back exactly the exception mask it called with.
- */
-struct fki_runs {
- void (*fn)(void *);
- void *arg;
-};
-
-/* fn runs with interrupts on and turns them off again; then, before the foreign kernel resumes, fki_fpsimd_forget */
-static void fki_runs_then_forget(void *p)
-{
- struct fki_runs *r = p;
-
- r->fn(r->arg);
- local_irq_enable();
- fki_fpsimd_forget();
- local_irq_disable();
-}
-
-static void fki_linux_runs(void (*fn)(void *), void *arg)
-{
- unsigned long daif = read_sysreg(daif);
- struct fki_runs r = { fn, arg };
-
- fki_linux_runs_body(fki_runs_then_forget, &r);
- write_sysreg(daif, daif);
-}
-
-void fki_linux_runs_ext(void (*fn)(void *), void *arg)
-{
- fki_linux_runs(fn, arg);
-}
-
-static void fki_linux_runs_body(void (*fn)(void *), void *arg)
-{
- unsigned long sp = current_stack_pointer;
- int cpu = smp_processor_id();
-
- if (on_task_stack(current, sp, 1)) {
- fn(arg);
- return;
- }
- fki_run_on_stack(fn, arg, (char *)fki_alt_stack[cpu] + THREAD_SIZE);
-}
-
-struct fki_idle_args { fki_u64 ns; const volatile unsigned int *wake; };
-
-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)
-{
- struct fki_idle_args *a = p;
- ktime_t t = ns_to_ktime(a->ns);
-
- local_irq_enable();
- preempt_enable();
- set_current_state(TASK_IDLE); /* uninterruptible, and not counted in the load average: the foreign kernel is idle */
- 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();
-}
-
-static void fki_yield_body(void *p)
-{
- local_irq_enable();
- preempt_enable();
- cond_resched();
- preempt_disable();
- local_irq_disable();
-}
-
-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;
-
- if (counter_deadline <= now) {
- /* already due: still let Linux take its interrupts and reschedule (an idle loop that never sleeps starves it) */
- fki_linux_runs(fki_yield_body, NULL);
- return;
- }
- ns = div64_u64((counter_deadline - now) * 1000000ULL, freq) * 1000ULL;
- 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);
-
-void fki_yield(void)
-{
- fki_linux_runs(fki_yield_body, NULL);
-}
-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.
- */
-/*
- * One csd per target CPU, shared by every sender: smp_call_function_single_async's -EBUSY check is not atomic, so two
- * CPUs kicking the same one at once would both queue the same csd, and the doubly linked llist entry loops the target
- * forever in its IPI handler with interrupts off (three or more hosted CPUs: two can kick a third). A sender claims the
- * target's csd first; the target's handler releases it (an async csd is unlocked before its function runs).
- */
-static atomic_t fki_kick_claimed[NR_CPUS];
-static void fki_kick_fn(void *unused) { atomic_set_release(&fki_kick_claimed[smp_processor_id()], 0); }
-static DEFINE_PER_CPU(call_single_data_t, fki_kick_csd);
-
-void fki_kick_cpu(int cpu)
-{
- struct task_struct *t;
-
- cpu = fki_cpu_map(cpu);
- 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() && atomic_cmpxchg_acquire(&fki_kick_claimed[cpu], 0, 1) == 0) {
- /* irq_work_queue_on is not exported; an IPI already on its way (claimed) is just as good */
- if (smp_call_function_single_async(cpu, per_cpu_ptr(&fki_kick_csd, cpu)))
- atomic_set_release(&fki_kick_claimed[cpu], 0);
- }
-}
-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;
-
- cpu = fki_cpu_map(cpu);
- 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 cpu_list_n ? cpu_list_n : num_online_cpus();
-}
-EXPORT_SYMBOL(fki_num_cpus);
-
-void fki_realtime(fki_u64 *sec, fki_u64 *nsec)
-{
- struct timespec64 ts;
-
- ktime_get_real_ts64(&ts);
- *sec = ts.tv_sec;
- *nsec = ts.tv_nsec;
-}
-EXPORT_SYMBOL(fki_realtime);
-
-/*
- * A virtual Ethernet link to the foreign kernel: the Linux netdev "xnu0". What Linux transmits on xnu0 is queued for
- * the foreign kernel (fki_net_recv); what the foreign kernel sends (fki_net_send) arrives on xnu0 as received frames.
- */
-#define FKI_NET_QLEN 1024
-static struct net_device *fki_netdev;
-static struct sk_buff_head fki_net_rxq; /* Linux -> foreign */
-
-static netdev_tx_t fki_net_xmit(struct sk_buff *skb, struct net_device *dev)
-{
- struct task_struct *t;
-
- if (skb_queue_len(&fki_net_rxq) >= FKI_NET_QLEN) {
- dev->stats.tx_dropped++;
- dev_kfree_skb_any(skb);
- return NETDEV_TX_OK;
- }
- dev->stats.tx_packets++;
- dev->stats.tx_bytes += skb->len;
- skb_queue_tail(&fki_net_rxq, skb);
- t = READ_ONCE(fki_idle_task[0]);
- if (t)
- wake_up_process(t); /* the foreign kernel's first CPU is idle: let it see the frame now */
- return NETDEV_TX_OK;
-}
-
-static int fki_net_up(struct net_device *dev) { netif_start_queue(dev); return 0; }
-static int fki_net_down(struct net_device *dev) { netif_stop_queue(dev); return 0; }
-
-static const struct net_device_ops fki_net_ops = {
- .ndo_open = fki_net_up,
- .ndo_stop = fki_net_down,
- .ndo_start_xmit = fki_net_xmit,
- .ndo_set_mac_address = eth_mac_addr,
- .ndo_validate_addr = eth_validate_addr,
-};
-
-struct fki_net_io { const void *in; void *out; unsigned long len; long result; };
-
-static void fki_net_send_body(void *p)
-{
- struct fki_net_io *io = p;
- struct sk_buff *skb;
-
- io->result = -ENODEV;
- if (!fki_netdev || io->len < ETH_HLEN || io->len > ETH_FRAME_LEN + 4)
- return;
- skb = netdev_alloc_skb(fki_netdev, io->len + NET_IP_ALIGN);
- if (!skb) {
- fki_netdev->stats.rx_dropped++;
- io->result = -ENOMEM;
- return;
- }
- skb_reserve(skb, NET_IP_ALIGN);
- skb_put_data(skb, io->in, io->len);
- skb->protocol = eth_type_trans(skb, fki_netdev);
- fki_netdev->stats.rx_packets++;
- fki_netdev->stats.rx_bytes += io->len;
- local_irq_enable(); /* netif_rx re-enables bottom halves, which must not happen with interrupts off */
- netif_rx(skb);
- local_irq_disable();
- io->result = io->len;
-}
-
-/* The foreign kernel sends one Ethernet frame (header included, no FCS) out of its link: it arrives on xnu0. */
-long fki_net_send(const void *frame, unsigned long len)
-{
- struct fki_net_io io = { .in = frame, .len = len };
-
- fki_linux_runs(fki_net_send_body, &io);
- return io.result;
-}
-EXPORT_SYMBOL(fki_net_send);
-
-static void fki_net_recv_body(void *p)
-{
- struct fki_net_io *io = p;
- struct sk_buff *skb = skb_dequeue(&fki_net_rxq);
-
- io->result = 0;
- if (!skb)
- return;
- if (skb->len > io->len) {
- io->result = -EMSGSIZE;
- } else if (skb_copy_bits(skb, 0, io->out, skb->len) == 0) {
- io->result = skb->len;
- } else {
- io->result = -EIO;
- }
- dev_consume_skb_any(skb);
-}
-
-/* The next frame Linux sent on xnu0 into buf (at most len bytes): its length, 0 when none is waiting. */
-long fki_net_recv(void *buf, unsigned long len)
-{
- struct fki_net_io io = { .out = buf, .len = len };
-
- fki_linux_runs(fki_net_recv_body, &io);
- return io.result;
-}
-EXPORT_SYMBOL(fki_net_recv);
-
-/* Frames waiting for the foreign kernel. */
-long fki_net_pending(void)
-{
- return skb_queue_len(&fki_net_rxq);
-}
-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, 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();
- if (err)
- pr_warn("fki: no /dev/xnu-hostcall (%d)\n", err);
- dev = alloc_etherdev(0);
- if (!dev)
- return 0; /* no link; the rest of fki still works */
- strscpy(dev->name, "xnu0", IFNAMSIZ);
- dev->netdev_ops = &fki_net_ops;
- eth_hw_addr_random(dev);
- dev->min_mtu = 68;
- dev->max_mtu = ETH_DATA_LEN;
- err = register_netdev(dev);
- if (err) {
- free_netdev(dev);
- pr_warn("fki: no xnu0 link (%d)\n", err);
- return 0;
- }
- fki_netdev = dev;
- return 0;
-}
-
-static void __exit fki_exit(void)
-{
- fki_hostcall_exit();
- if (resv_pg && !resv_used)
- p_cma_release(*p_cma_area, resv_pg, resv_cnt);
- if (fki_netdev) {
- unregister_netdev(fki_netdev);
- free_netdev(fki_netdev);
- fki_netdev = NULL;
- }
- skb_queue_purge(&fki_net_rxq);
- fki_free_alt_stacks();
-}
-module_init(fki_init);
-module_exit(fki_exit);
-
-MODULE_LICENSE("GPL");
-MODULE_DESCRIPTION("Foreign kernel interface v0 (out-of-tree form for stock kernels)");
-
-void *fki_file_open(const char *path, int writable, fki_u64 *size)
-{
- struct file *f = filp_open(path, (writable ? O_RDWR : O_RDONLY) | O_LARGEFILE, 0);
-
- if (IS_ERR(f))
- return NULL;
- if (size) /* the mapping's host: a block device's own size (a device node's inode says 0) */
- *size = i_size_read(f->f_mapping->host);
- return f;
-}
-EXPORT_SYMBOL(fki_file_open);
-
-#define FKI_FILE_CHUNK (256UL << 10)
-
-static long fki_file_rw_body(void *file, int write, void *buf, unsigned long len, fki_u64 off);
-struct fki_file_args { void *file; int write; void *buf; unsigned long len; fki_u64 off; long ret; };
-static void fki_file_rw_thunk(void *p)
-{
- struct fki_file_args *a = p;
- a->ret = fki_file_rw_body(a->file, a->write, a->buf, a->len, a->off);
-}
-
-long fki_file_rw(void *file, int write, void *buf, unsigned long len, fki_u64 off)
-{
- struct fki_file_args a = { file, write, buf, len, off, -EIO };
-
- if (!file)
- return -EBADF;
- fki_linux_runs(fki_file_rw_thunk, &a);
- return a.ret;
-}
-EXPORT_SYMBOL(fki_file_rw);
-
-static long fki_file_rw_body(void *file, int write, void *buf, unsigned long len, fki_u64 off)
-{
- struct file *f = file;
- unsigned long done = 0;
- long ret = 0;
- void *bounce;
-
- local_irq_enable();
- preempt_enable();
- bounce = kvmalloc(min(len, FKI_FILE_CHUNK), GFP_KERNEL);
- if (!bounce)
- ret = -ENOMEM;
- while (bounce && done < len) {
- unsigned long n = min(len - done, FKI_FILE_CHUNK);
- loff_t pos = off + done;
- ssize_t r;
-
- if (write) {
- preempt_disable(); local_irq_disable();
- memcpy(bounce, (char *)buf + done, n);
- local_irq_enable(); preempt_enable();
- r = kernel_write(f, bounce, n, &pos);
- } else {
- r = kernel_read(f, bounce, n, &pos);
- if (r > 0) {
- preempt_disable(); local_irq_disable();
- memcpy((char *)buf + done, bounce, r);
- local_irq_enable(); preempt_enable();
- }
- }
- if (r < 0) {
- ret = r;
- break;
- }
- done += r;
- if ((unsigned long)r < n)
- break;
- }
- kvfree(bounce);
- preempt_disable();
- local_irq_disable();
- return ret < 0 && !done ? ret : (long)done;
-}
-
-
-long fki_file_pwrite(void *file, const void *buf, unsigned long len, fki_u64 off)
-{
- loff_t pos = off;
-
- if (!file)
- return -EBADF;
- return kernel_write(file, buf, len, &pos);
-}
-EXPORT_SYMBOL(fki_file_pwrite);
-
-void fki_file_close(void *file)
-{
- if (file)
- filp_close(file, NULL);
-}
-EXPORT_SYMBOL(fki_file_close);
diff --git a/kexts/XnuDisplay/XnuDisplay.cpp b/kexts/XnuDisplay/XnuDisplay.cpp
index 7f87bf4..ec18a3d 100644
--- a/kexts/XnuDisplay/XnuDisplay.cpp
+++ b/kexts/XnuDisplay/XnuDisplay.cpp
@@ -296,6 +296,7 @@ private:
// unmapped descriptor was most of the copy's time.
struct SurfaceMap {
IOSurface *surface; // retained while mapped
+ IOMemoryDescriptor *memory; // kept prepared while the kernel mapping is cached
IOMemoryMap *map;
uint64_t used;
};
@@ -898,12 +899,12 @@ void XnuDisplay::copyLoop()
IOLockUnlock(fCopyLock);
}
-// The kernel address of a surface's memory, mapped once for the next copies.
+// The kernel address of a surface's memory, kept prepared and mapped for the next copies.
const uint8_t *XnuDisplay::surfaceBytes(IOSurface *surface, IOMemoryDescriptor *memory)
{
SurfaceMap *slot = &fSurfaceMaps[0];
for (SurfaceMap &entry : fSurfaceMaps) {
- if (entry.surface == surface && entry.map->getMemoryDescriptor() == memory) {
+ if (entry.surface == surface && entry.memory == memory) {
entry.used = ++fSurfaceMapClock;
return reinterpret_cast<const uint8_t *>(entry.map->getVirtualAddress());
}
@@ -912,14 +913,21 @@ const uint8_t *XnuDisplay::surfaceBytes(IOSurface *surface, IOMemoryDescriptor *
}
if (slot->surface) {
slot->map->release();
+ slot->memory->complete();
+ slot->memory->release();
reinterpret_cast<OSObject *>(slot->surface)->release();
*slot = {};
}
+ if (memory->prepare() != kIOReturnSuccess)
+ return nullptr;
IOMemoryMap *map = memory->createMappingInTask(kernel_task, 0, kIOMapAnywhere | kIOMapReadOnly);
- if (!map)
+ if (!map) {
+ memory->complete();
return nullptr;
+ }
+ memory->retain();
reinterpret_cast<OSObject *>(surface)->retain();
- *slot = {surface, map, ++fSurfaceMapClock};
+ *slot = {surface, memory, map, ++fSurfaceMapClock};
return reinterpret_cast<const uint8_t *>(map->getVirtualAddress());
}
@@ -947,6 +955,8 @@ void XnuDisplay::releaseSurfaceMaps()
if (!entry.surface)
continue;
entry.map->release();
+ entry.memory->complete();
+ entry.memory->release();
reinterpret_cast<OSObject *>(entry.surface)->release();
entry = {};
}
@@ -1145,14 +1155,10 @@ void XnuDisplay::copySurface(IOSurface *surface, bool refresh)
total += ns;
mark = now;
};
- if (memory->prepare() != kIOReturnSuccess)
- return;
const uint8_t *bytes = surfaceBytes(surface, memory);
lap(fPrepareNs);
- if (!bytes) {
- memory->complete();
+ if (!bytes)
return;
- }
uint64_t lit = 0, raw = 0, center = 0;
bool sample = !refresh; // bring-up: the first frames and every 50th are logged, the last one goes into the periodic report
for (uint64_t y = 0; y < copyHeight; y++) {
@@ -1201,7 +1207,6 @@ void XnuDisplay::copySurface(IOSurface *surface, bool refresh)
memcpy(line, fLine, copyWidth * 4);
lap(fWriteNs);
}
- memory->complete();
uint64_t ns;
absolutetime_to_nanoseconds(mach_absolute_time() - began, &ns);
fCopies++;
diff --git a/kexts/XnuDrm/XnuDrm.cpp b/kexts/XnuDrm/XnuDrm.cpp
index 21cdb97..b133bf4 100644
--- a/kexts/XnuDrm/XnuDrm.cpp
+++ b/kexts/XnuDrm/XnuDrm.cpp
@@ -145,15 +145,28 @@ IOReturn AGXDeviceUserClient::doMap(IOExternalMethodArguments *a)
*h = (xnudrm_hdr){ .magic = XNUDRM_MAGIC, .op = XNUDRM_MAP, .client = fClient, .arg0 = handle, .arg1 = size };
long n = hostcall(sizeof(*h));
xnudrm_hdr *r = (xnudrm_hdr *)gOut;
- if (n < 0 || r->status) {
+ if (n < (long)sizeof(xnudrm_hdr) || r->status) {
+ int rstatus = (n >= (long)sizeof(xnudrm_hdr)) ? r->status : 0;
IOLockUnlock(gCallLock);
- IOLog("XnuDrm: map of handle %llu failed (%ld, %d)\n", handle, n, n < 0 ? 0 : r->status);
+ IOLog("XnuDrm: map of handle %llu failed (%ld, %d)\n", handle, n, rstatus);
return kIOReturnNoMemory;
}
uint64_t id = r->arg0;
+ size_t avail = (size_t)n - sizeof(xnudrm_hdr);
+ if (r->payload_len != avail || r->payload_len == 0 || (r->payload_len % sizeof(xnudrm_range)) != 0) {
+ IOLockUnlock(gCallLock);
+ xnudrm_hdr ur;
+ simple(XNUDRM_UNMAP, id, 0, &ur);
+ return kIOReturnBadArgument;
+ }
uint32_t nr = r->payload_len / sizeof(xnudrm_range);
IOAddressRange *ranges = (IOAddressRange *)IOMallocData(nr * sizeof(IOAddressRange));
- if (!ranges) { IOLockUnlock(gCallLock); return kIOReturnNoMemory; }
+ if (!ranges) {
+ IOLockUnlock(gCallLock);
+ xnudrm_hdr ur;
+ simple(XNUDRM_UNMAP, id, 0, &ur);
+ return kIOReturnNoMemory;
+ }
const xnudrm_range *rg = (const xnudrm_range *)(gOut + sizeof(xnudrm_hdr));
for (uint32_t i = 0; i < nr; i++) ranges[i] = (IOAddressRange){ rg[i].pa, rg[i].len };
IOLockUnlock(gCallLock);
@@ -177,7 +190,13 @@ IOReturn AGXDeviceUserClient::doMap(IOExternalMethodArguments *a)
if (i == fNSlots) {
unsigned nn = fNSlots ? fNSlots * 2 : 64;
Slot *s = (Slot *)IOMallocZeroData(nn * sizeof(Slot));
- if (!s) { map->release(); md->release(); return kIOReturnNoMemory; }
+ if (!s) {
+ map->release();
+ md->release();
+ xnudrm_hdr ur;
+ simple(XNUDRM_UNMAP, id, 0, &ur);
+ return kIOReturnNoMemory;
+ }
if (fSlots) { memcpy(s, fSlots, fNSlots * sizeof(Slot)); IOFreeData(fSlots, fNSlots * sizeof(Slot)); }
fSlots = s; fNSlots = nn;
}
diff --git a/linux/drivers/fki/fki.c b/linux/drivers/fki/fki.c
index a065f69..6d61b80 100644
--- a/linux/drivers/fki/fki.c
+++ b/linux/drivers/fki/fki.c
@@ -18,13 +18,15 @@
#include <linux/slab.h>
#include <linux/sched.h>
#include <linux/cpumask.h>
+#include <linux/uaccess.h>
#include <linux/vmalloc.h>
#include <asm/arch_timer.h>
#include <asm/sysreg.h>
int fki_version(void)
{
- return FKI_VERSION;
+ /* This minimal in-tree driver implements only the FKI v0 subset; full FKI v1 lives in fki-ko/. */
+ return 0;
}
EXPORT_SYMBOL(fki_version);
@@ -136,10 +138,11 @@ void fki_leave(unsigned long cookie, const struct fki_pac_keys *saved)
}
EXPORT_SYMBOL(fki_leave);
-void fki_pac_swap(const struct fki_pac_keys *load, struct fki_pac_keys *save)
+int fki_pac_swap(const struct fki_pac_keys *load, struct fki_pac_keys *save)
{
keys_read(save);
keys_write(load);
+ return 0;
}
EXPORT_SYMBOL(fki_pac_swap);
@@ -174,3 +177,81 @@ int fki_bind_cpu(int cpu)
return set_cpus_allowed_ptr(current, cpumask_of(cpu));
}
EXPORT_SYMBOL(fki_bind_cpu);
+
+/* FKI v1 capability & EL0/high-window stubs (native EL1 backend). */
+unsigned long fki_caps(void)
+{
+ return FKI_CAP_PAC | FKI_CAP_EXEC_ONLY;
+}
+EXPORT_SYMBOL(fki_caps);
+
+int fki_cpu_id(void)
+{
+ return smp_processor_id();
+}
+EXPORT_SYMBOL(fki_cpu_id);
+
+void fki_log_alert(const char *s, unsigned long len)
+{
+ pr_alert("fki: %.*s\n", (int)len, s);
+}
+EXPORT_SYMBOL(fki_log_alert);
+
+int fki_kmem_alloc(unsigned long size, unsigned long high_va, fki_u64 pa_base, struct fki_region *r) { return -EOPNOTSUPP; }
+EXPORT_SYMBOL(fki_kmem_alloc);
+void fki_kmem_free(struct fki_region *r) {}
+EXPORT_SYMBOL(fki_kmem_free);
+int fki_high_map(unsigned long va, fki_u64 xpa, unsigned long size, int prot) { return -EOPNOTSUPP; }
+EXPORT_SYMBOL(fki_high_map);
+void fki_high_unmap(unsigned long va, unsigned long size) {}
+EXPORT_SYMBOL(fki_high_unmap);
+void fki_high_flush(void) {}
+EXPORT_SYMBOL(fki_high_flush);
+int fki_high_read_u64x2(unsigned long va, fki_u64 *out0, fki_u64 *out1)
+{
+ fki_u64 pair[2];
+
+ if (!out0 || !out1 || (va & 7UL) || va < 0xffffff8000000000UL || va > 0xfffffffc00000000UL - sizeof(pair))
+ return -EFAULT;
+ if (copy_from_kernel_nofault(pair, (const void *)va, sizeof(pair)) != 0)
+ return -EFAULT;
+ *out0 = pair[0];
+ *out1 = pair[1];
+ return 0;
+}
+EXPORT_SYMBOL(fki_high_read_u64x2);
+void fki_icache_flush(unsigned long va, unsigned long size)
+{
+ (void)va;
+ (void)size;
+ asm volatile("dsb ish; ic ialluis; dsb ish; isb" ::: "memory");
+}
+EXPORT_SYMBOL(fki_icache_flush);
+void *fki_as_create(void) { return NULL; }
+EXPORT_SYMBOL(fki_as_create);
+void fki_as_destroy(void *as) {}
+EXPORT_SYMBOL(fki_as_destroy);
+int fki_as_map(void *as, unsigned long va, fki_u64 xpa, unsigned long size, int prot) { return -EOPNOTSUPP; }
+EXPORT_SYMBOL(fki_as_map);
+void fki_as_unmap(void *as, unsigned long va, unsigned long size) {}
+EXPORT_SYMBOL(fki_as_unmap);
+void fki_as_flush(void *as) {}
+EXPORT_SYMBOL(fki_as_flush);
+void *fki_utcb_create(void *as) { return NULL; }
+EXPORT_SYMBOL(fki_utcb_create);
+void fki_utcb_destroy(void *utcb) {}
+EXPORT_SYMBOL(fki_utcb_destroy);
+int fki_utcb_set_as(void *utcb, void *as) { return -EOPNOTSUPP; }
+EXPORT_SYMBOL(fki_utcb_set_as);
+int fki_utcb_set_pac(void *utcb, const struct fki_pac_keys *keys) { return -EOPNOTSUPP; }
+EXPORT_SYMBOL(fki_utcb_set_pac);
+int fki_utcb_run(void *utcb, struct fki_utcb_regs *regs, struct fki_utcb_stop *stop) { return -EOPNOTSUPP; }
+EXPORT_SYMBOL(fki_utcb_run);
+int fki_utcb_resume(void *utcb, struct fki_utcb_regs *regs, struct fki_utcb_stop *stop) { return -ENOSYS; }
+EXPORT_SYMBOL(fki_utcb_resume);
+int fki_utcb_sync_regs(void *utcb, struct fki_utcb_regs *regs) { return -ENOSYS; }
+EXPORT_SYMBOL(fki_utcb_sync_regs);
+int fki_utcb_fpu_read(void *utcb, void *buf, unsigned long len) { return -EOPNOTSUPP; }
+EXPORT_SYMBOL(fki_utcb_fpu_read);
+int fki_utcb_fpu_write(void *utcb, const void *buf, unsigned long len) { return -EOPNOTSUPP; }
+EXPORT_SYMBOL(fki_utcb_fpu_write);
diff --git a/linux/include/linux/fki.h b/linux/include/linux/fki.h
index f6de5c3..6fb84f9 100644
--- a/linux/include/linux/fki.h
+++ b/linux/include/linux/fki.h
@@ -1,6 +1,6 @@
/* SPDX-License-Identifier: GPL-2.0-only WITH Linux-syscall-note */
/*
- * Foreign kernel interface (FKI), version 0.
+ * Foreign kernel interface (FKI), version 2.
*
* The only interface between Linux and a foreign-kernel module. It is
* semantic and shaped like a hypervisor interface: plain integer types and
@@ -10,7 +10,7 @@
#ifndef _LINUX_FKI_H
#define _LINUX_FKI_H
-#define FKI_VERSION 0
+#define FKI_VERSION 2
#ifndef __KERNEL__
#include <stdint.h>
@@ -20,6 +20,17 @@ typedef uint64_t fki_u64;
typedef u64 fki_u64;
#endif
+/* Host capability bits returned by fki_caps(). */
+#define FKI_CAP_EL0 (1UL << 0) /* hosted kernel runs at EL0 */
+#define FKI_CAP_HIGH_WINDOW (1UL << 1) /* host manages TTBR1 high window */
+#define FKI_CAP_PAC (1UL << 2) /* per-context PAC keys supported */
+#define FKI_CAP_EXEC_ONLY (1UL << 3) /* execute-only (--x) user mappings supported */
+
+/* Page mapping protection bits for fki_high_map() and fki_as_map(). */
+#define FKI_PROT_READ (1 << 0)
+#define FKI_PROT_WRITE (1 << 1)
+#define FKI_PROT_EXEC (1 << 2)
+
/* Physically contiguous memory, mapped contiguously and executable. */
struct fki_region {
void *va;
@@ -34,21 +45,43 @@ struct fki_pac_keys {
fki_u64 sctlr_en; /* SCTLR_EL1 EnIA|EnIB|EnDA|EnDB bits */
};
+/* User-context register state and stop info (FKI_CAP_EL0 hosts). */
+struct fki_utcb_regs {
+ fki_u64 x[31];
+ fki_u64 sp, pc, pstate, tpidr, tpidrro;
+};
+
+enum {
+ FKI_STOP_SYSCALL = 1,
+ FKI_STOP_PAGEFAULT = 2,
+ FKI_STOP_EXCEPTION = 3,
+ FKI_STOP_INTERRUPT = 4,
+};
+
+struct fki_utcb_stop {
+ int kind;
+ fki_u64 fault_addr, fault_ip, esr;
+};
+
#ifdef __cplusplus
extern "C" {
#endif
int fki_version(void);
+unsigned long fki_caps(void);
+int fki_cpu_id(void);
void fki_log(const char *s, unsigned long len);
+void fki_log_alert(const char *s, unsigned long len); /* KERN_ALERT: on the console even when it is quiet */
int fki_region_alloc(unsigned long size, struct fki_region *r);
void fki_region_free(struct fki_region *r);
/* A named blob from the firmware search path. */
int fki_blob_get(const char *name, const void **data, unsigned long *size, void **handle);
void fki_blob_put(void *handle);
-/* Enter and leave a foreign context on this CPU: no preemption, no interrupts, foreign PAC keys. */
+/* Enter and leave a foreign context on this CPU: no preemption, no interrupts, foreign PAC keys; the FP/SIMD registers are
+ * the foreign kernel's to use (the current task's state saved first). */
unsigned long fki_enter(const struct fki_pac_keys *foreign, struct fki_pac_keys *saved);
void fki_leave(unsigned long cookie, const struct fki_pac_keys *saved);
/* Swap PAC keys only (caller already in a foreign context): save current into *save, load *load. */
-void fki_pac_swap(const struct fki_pac_keys *load, struct fki_pac_keys *save);
+int fki_pac_swap(const struct fki_pac_keys *load, struct fki_pac_keys *save);
fki_u64 fki_counter_frequency(void);
fki_u64 fki_counter(void);
void fki_random(void *buf, unsigned long len);
@@ -66,11 +99,49 @@ void fki_contig_free(struct fki_region *r);
*/
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);
+/*
+ * Host-managed foreign kernel memory and high-window mappings (FKI_CAP_HIGH_WINDOW):
+ * fki_kmem_alloc allocates backing memory (no multi-GB physical contiguity required), maps it at high_va
+ * as RWX, associates synthetic physical addresses starting at pa_base, and binds the high window on all CPUs.
+ * fki_high_map/unmap/flush mirror additional kernel-VA mappings backed by xpa in [pa_base, pa_base + size).
+ * fki_high_map only supports new mappings or in-place same-PFN re-protection; cross-PFN replacement
+ * returns -EBUSY and requires the caller to fki_high_unmap while quiescent first.
+ */
+int fki_kmem_alloc(unsigned long size, unsigned long high_va, fki_u64 pa_base, struct fki_region *r);
+void fki_kmem_free(struct fki_region *r);
+int fki_high_map(unsigned long va, fki_u64 xpa, unsigned long size, int prot);
+void fki_high_unmap(unsigned long va, unsigned long size);
+void fki_high_flush(void);
+int fki_high_txn_begin(unsigned long va, unsigned long size, void **handle_out);
+void fki_high_txn_restore(void *txn);
+void fki_high_txn_end(void *txn);
+int fki_high_read_u64x2(unsigned long va, fki_u64 *out0, fki_u64 *out1);
+void fki_icache_flush(unsigned long va, unsigned long size);
+/*
+ * Host-managed user address spaces and user execution contexts (FKI_CAP_EL0).
+ * Passing as == NULL to fki_as_unmap() broadcasts the unmap of [va, va + size)
+ * across all active user address spaces (for shared/nested page tables).
+ */
+void *fki_as_create(void);
+void fki_as_destroy(void *as);
+int fki_as_map(void *as, unsigned long va, fki_u64 xpa, unsigned long size, int prot);
+void fki_as_unmap(void *as, unsigned long va, unsigned long size);
+void fki_as_flush(void *as);
+void *fki_utcb_create(void *as);
+void fki_utcb_destroy(void *utcb);
+int fki_utcb_set_as(void *utcb, void *as);
+int fki_utcb_set_pac(void *utcb, const struct fki_pac_keys *keys);
+int fki_utcb_run(void *utcb, struct fki_utcb_regs *regs, struct fki_utcb_stop *stop);
+int fki_utcb_resume(void *utcb, struct fki_utcb_regs *regs, struct fki_utcb_stop *stop);
+int fki_utcb_sync_regs(void *utcb, struct fki_utcb_regs *regs);
+int fki_utcb_fpu_read(void *utcb, void *buf, unsigned long len);
+int fki_utcb_fpu_write(void *utcb, const void *buf, unsigned long len);
/*
* 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.
@@ -87,6 +158,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().
@@ -94,6 +170,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
@@ -106,6 +186,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). */
@@ -119,6 +200,13 @@ fki_u64 fki_phys_peek(fki_u64 pa);
void *fki_file_open(const char *path, int writable, fki_u64 *size);
long fki_file_rw(void *file, int write, void *buf, unsigned long len, fki_u64 off);
void fki_file_close(void *file);
+/* Write to a host file from ordinary Linux context (a host thread, not inside fki_enter()); bytes written or -errno. */
+long fki_file_pwrite(void *file, const void *buf, unsigned long len, fki_u64 off);
+/*
+ * A host call (from inside fki_enter()): len bytes at req to the Linux service reading /dev/xnu-hostcall, its reply into
+ * reply (at most max bytes). Returns the reply's length or a negative errno (-ETIMEDOUT: no service answered).
+ */
+long fki_hostcall(const void *req, unsigned long len, void *reply, unsigned long max);
#ifdef __cplusplus
}
#endif
diff --git a/xnu-ko/macho.c b/xnu-ko/macho.c
index 64618db..d947327 100644
--- a/xnu-ko/macho.c
+++ b/xnu-ko/macho.c
@@ -5,9 +5,48 @@
#define ENOMEM 12
#include "macho.h"
+static int lc_bounds_ok(const unsigned char *base, unsigned long size,
+ u32_t ncmds, u32_t sizeofcmds)
+{
+ if (size < sizeof(struct mh64))
+ return 0;
+ if ((unsigned long)sizeofcmds > size - sizeof(struct mh64))
+ return 0;
+ const unsigned char *p = base + sizeof(struct mh64);
+ const unsigned char *end = p + sizeofcmds;
+ for (u32_t i = 0; i < ncmds; i++) {
+ if ((unsigned long)(end - p) < sizeof(struct lc))
+ return 0;
+ const struct lc *l = (const void *)p;
+ if (l->cmdsize < sizeof(struct lc) || l->cmdsize > (unsigned long)(end - p))
+ return 0;
+ p += l->cmdsize;
+ }
+ return 1;
+}
+
+static int cstr_bounded_eq(const char *s, unsigned long max_len, const char *want)
+{
+ unsigned long i = 0;
+ while (i < max_len) {
+ if (s[i] != want[i])
+ return 0;
+ if (s[i] == '\0')
+ return 1;
+ i++;
+ }
+ return 0;
+}
+
+#define LC_OK(l, end) \
+ ((const char *)(end) - (const char *)(l) >= (long)sizeof(struct lc) && \
+ (l)->cmdsize >= sizeof(struct lc) && \
+ (l)->cmdsize <= (u64_t)((const char *)(end) - (const char *)(l)))
+
#define FOR_EACH_LC(img, l) \
+ for (u32_t _lci = 0, _ncmds = ((const struct mh64 *)(img)->file)->ncmds; _lci < _ncmds; _lci = _ncmds) \
for (const struct lc *l = (const void *)((img)->file + sizeof(struct mh64)), *_e = (const void *)((img)->file + sizeof(struct mh64) + ((const struct mh64 *)(img)->file)->sizeofcmds); \
- l < _e; l = (const void *)((const char *)l + l->cmdsize))
+ _lci < _ncmds && LC_OK(l, _e); _lci++, l = (const void *)((const char *)l + l->cmdsize))
int macho_load(struct xnu_image *img, const void *file, unsigned long size, unsigned long extra)
{
@@ -16,14 +55,24 @@ int macho_load(struct xnu_image *img, const void *file, unsigned long size, unsi
(void)err;
img->file = file; img->file_size = size;
- if (size < sizeof(*mh) || mh->magic != MH_MAGIC_64)
+ if (!file || size < sizeof(*mh) || mh->magic != MH_MAGIC_64)
+ return -ENOEXEC;
+ if (!lc_bounds_ok(img->file, size, mh->ncmds, mh->sizeofcmds))
return -ENOEXEC;
img->vmlow = ~0ULL; img->vmhigh = 0;
FOR_EACH_LC(img, l) {
if (l->cmd == LC_SEGMENT_64) {
+ if (l->cmdsize < sizeof(struct seg64))
+ return -ENOEXEC;
const struct seg64 *s = (const void *)l;
+ if (s->nsects > (l->cmdsize - sizeof(struct seg64)) / sizeof(struct sect64))
+ return -ENOEXEC;
if (!s->vmsize || !x_strncmp(s->segname, "__PAGEZERO", 16))
continue;
+ if (s->vmaddr + s->vmsize < s->vmaddr)
+ return -ENOEXEC;
+ if (s->filesize > s->vmsize || s->fileoff > size || s->filesize > size - s->fileoff)
+ return -ENOEXEC;
if (s->vmaddr < img->vmlow) img->vmlow = s->vmaddr;
if (s->vmaddr + s->vmsize > img->vmhigh) img->vmhigh = s->vmaddr + s->vmsize;
const struct sect64 *sc = (const void *)(s + 1);
@@ -33,9 +82,13 @@ int macho_load(struct xnu_image *img, const void *file, unsigned long size, unsi
img->thread_starts_size = sc[i].size;
}
} else if (l->cmd == LC_SYMTAB) {
+ if (l->cmdsize < sizeof(struct symtab_lc))
+ return -ENOEXEC;
img->symtab = (const void *)l;
} else if (l->cmd == LC_UNIXTHREAD) {
/* flavor, count, then arm_thread_state64: x[29], fp, lr, sp, pc */
+ if (l->cmdsize < sizeof(struct lc) + (2 + 2 * 32) * sizeof(u32_t) + sizeof(u64_t))
+ return -ENOEXEC;
const u32_t *t = (const void *)(l + 1);
img->entry = *(const u64_t *)(t + 2 + 2 * 32);
}
@@ -51,20 +104,40 @@ int macho_load(struct xnu_image *img, const void *file, unsigned long size, unsi
img->symtab = 0;
FOR_EACH_LC(img, l) {
if (l->cmd != LC_FILESET_ENTRY) continue;
+ if (l->cmdsize < sizeof(struct fileset_entry_lc)) return -ENOEXEC;
const struct fileset_entry_lc *fe = (const void *)l;
- if (fe->entry_id >= fe->cmdsize || x_strcmp((const char *)fe + fe->entry_id, "com.apple.kernel")) continue;
- if (fe->fileoff + sizeof(struct mh64) > size) return -ENOEXEC;
- img->kernel_mh = fe->vmaddr;
+ if (fe->entry_id >= fe->cmdsize ||
+ !cstr_bounded_eq((const char *)fe + fe->entry_id, fe->cmdsize - fe->entry_id, "com.apple.kernel"))
+ continue;
+ if (fe->fileoff > size || size - fe->fileoff < sizeof(struct mh64))
+ return -ENOEXEC;
const struct mh64 *kh = (const void *)((const char *)file + fe->fileoff);
+ if (kh->magic != MH_MAGIC_64 ||
+ !lc_bounds_ok((const unsigned char *)kh, size - fe->fileoff, kh->ncmds, kh->sizeofcmds))
+ return -ENOEXEC;
+ img->kernel_mh = fe->vmaddr;
const struct lc *kl = (const void *)(kh + 1);
- for (u32_t i = 0; i < kh->ncmds; i++, kl = (const void *)((const char *)kl + kl->cmdsize))
- if (kl->cmd == LC_SYMTAB) img->symtab = (const void *)kl;
+ for (u32_t i = 0; i < kh->ncmds; i++, kl = (const void *)((const char *)kl + kl->cmdsize)) {
+ if (kl->cmd == LC_SYMTAB) {
+ if (kl->cmdsize < sizeof(struct symtab_lc))
+ return -ENOEXEC;
+ img->symtab = (const void *)kl;
+ }
+ }
}
if (!img->kernel_mh || !img->symtab)
return -ENOEXEC;
}
+ if (img->symtab) {
+ const struct symtab_lc *st = img->symtab;
+ if ((u64_t)st->symoff > size || (u64_t)st->nsyms > (size - st->symoff) / sizeof(struct nlist64) ||
+ (u64_t)st->stroff > size || (u64_t)st->strsize > size - st->stroff)
+ return -ENOEXEC;
+ }
if (extra == ~0UL) /* parse only: the caller places the image (macho_copy) */
return 0;
+ if ((img->vmhigh - img->vmlow) + extra < (img->vmhigh - img->vmlow))
+ return -ENOMEM;
err = fki_region_alloc(img->vmhigh - img->vmlow + extra, &img->region);
if (err)
return err;
@@ -75,11 +148,15 @@ int macho_load(struct xnu_image *img, const void *file, unsigned long size, unsi
/* Copy the segments to dst, which is where vmlow will live. */
int macho_copy(struct xnu_image *img, void *dst)
{
+ u64_t img_span = img->vmhigh - img->vmlow;
FOR_EACH_LC(img, l) {
if (l->cmd != LC_SEGMENT_64) continue;
const struct seg64 *s = (const void *)l;
if (!s->vmsize || !s->filesize || !x_strncmp(s->segname, "__PAGEZERO", 16)) continue;
- if (s->fileoff + s->filesize > img->file_size) return -ENOEXEC;
+ if (s->fileoff > img->file_size || s->filesize > img->file_size - s->fileoff) return -ENOEXEC;
+ if (s->vmaddr < img->vmlow || (s->vmaddr - img->vmlow) > img_span ||
+ s->filesize > img_span - (s->vmaddr - img->vmlow))
+ return -ENOEXEC;
x_memcpy((char *)dst + (s->vmaddr - img->vmlow), img->file + s->fileoff, s->filesize);
}
return 0;
@@ -135,6 +212,26 @@ int macho_rebase(struct xnu_image *img)
return (int)n;
}
+int macho_va_to_loaded(const struct xnu_image *img, u64_t unslid, u64_t len, u64_t *out_va)
+{
+ if (!img || !out_va || img->vmhigh < img->vmlow)
+ return 0;
+ if (unslid < img->vmlow || unslid > img->vmhigh)
+ return 0;
+ u64_t off = unslid - img->vmlow;
+ u64_t span = img->vmhigh - img->vmlow;
+ if (len > span - off)
+ return 0;
+ u64_t base = img->vmlow + img->slide;
+ if (base + off < base)
+ return 0;
+ u64_t va = base + off;
+ if (va + len < va)
+ return 0;
+ *out_va = va;
+ return 1;
+}
+
u64_t macho_sym(struct xnu_image *img, const char *name)
{
const struct symtab_lc *st = img->symtab;
@@ -143,8 +240,12 @@ u64_t macho_sym(struct xnu_image *img, const char *name)
const char *strs = (const char *)img->file + st->stroff;
for (u32_t i = 0; i < st->nsyms; i++) {
if ((nl[i].n_type & 0x0e) != 0x0e || nl[i].n_strx >= st->strsize) continue; /* N_SECT */
- if (!x_strcmp(strs + nl[i].n_strx, name))
- return nl[i].n_value + img->slide;
+ if (cstr_bounded_eq(strs + nl[i].n_strx, st->strsize - nl[i].n_strx, name)) {
+ u64_t va;
+ if (!macho_va_to_loaded(img, nl[i].n_value, 1, &va))
+ return 0;
+ return va;
+ }
}
return 0;
}
@@ -165,7 +266,7 @@ int macho_slide_header(struct xnu_image *img, u64_t *mh_unslid)
const struct mh64 *h = (const void *)mh;
struct lc *l = (void *)(mh + sizeof(struct mh64)), *e = (void *)(mh + sizeof(struct mh64) + h->sizeofcmds);
int n = 0;
- for (; l < e; l = (void *)((char *)l + l->cmdsize)) {
+ for (u32_t ci = 0; ci < h->ncmds && LC_OK(l, e); ci++, l = (void *)((char *)l + l->cmdsize)) {
if (l->cmd != LC_SEGMENT_64) continue;
struct seg64 *sg = (void *)l;
if (!sg->vmsize) continue;
diff --git a/xnu-ko/macho.h b/xnu-ko/macho.h
index 086e818..97ed438 100644
--- a/xnu-ko/macho.h
+++ b/xnu-ko/macho.h
@@ -36,4 +36,5 @@ int macho_load(struct xnu_image *img, const void *file, unsigned long size, unsi
int macho_copy(struct xnu_image *img, void *dst);
int macho_rebase(struct xnu_image *img);
int macho_slide_header(struct xnu_image *img, u64_t *mh_unslid);
+int macho_va_to_loaded(const struct xnu_image *img, u64_t unslid, u64_t len, u64_t *out_va);
u64_t macho_sym(struct xnu_image *img, const char *name); /* runtime address or 0 */
diff --git a/xnu-ko/world.S b/xnu-ko/world.S
index 8986d33..bb0f054 100644
--- a/xnu-ko/world.S
+++ b/xnu-ko/world.S
@@ -3,8 +3,9 @@
* 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. */
+ * TPIDR_EL1 stays Linux's: the LINUX64 XNU keeps its kernel thread pointer in TPIDR_EL0 (swapping user TPIDR_EL0 on
+ * EL0 entry/exit and persisting it in thread->machine.linux64_user_tpidr), 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.
@@ -223,3 +224,116 @@ xnu_fault_tramp:
add sp, sp, #256
eret
.size xnu_fault_tramp, . - xnu_fault_tramp
+
+/*
+ * Pure EL0 host world switch (FKI_CAP_EL0): zero EL1 system instructions.
+ * Slot comes from TPIDRRO_EL0 (set to the host CPU id per vCPU).
+ * Linux keeps its per-CPU TLS pointer in TPIDR_EL0; XNU keeps its current thread pointer in TPIDR_EL0.
+ * Always restore Linux's TPIDR_EL0 before calling into FKI or xnu_hook, and switch PAC keys while Linux's
+ * TPIDR_EL0 is live.
+ */
+#define W_EL0(reg) mrs reg, tpidrro_el0; and reg, reg, #0xff; \
+ adrp x10, xnu_worlds; add x10, x10, :lo12:xnu_worlds; ldr reg, [x10, reg, lsl #3]
+
+ .globl xnu_world_call_el0
+ .type xnu_world_call_el0, %function
+xnu_world_call_el0:
+ W_EL0(x9)
+ str x18, [x9, #464]
+ stp x19, x20, [x9, #0]
+ stp x21, x22, [x9, #16]
+ stp x23, x24, [x9, #32]
+ stp x25, x26, [x9, #48]
+ stp x27, x28, [x9, #64]
+ stp x29, x30, [x9, #80]
+ mov x10, sp
+ str x10, [x9, #96]
+ mov x19, x0
+ mov x20, x1
+ add x0, x9, #328 /* load XNU keys */
+ add x1, x9, #240 /* save Linux keys */
+ bl fki_enter /* no preemption, no IRQs */
+ W_EL0(x9)
+ str x0, [x9, #104]
+ mrs x10, tpidr_el0
+ str x10, [x9, #216] /* save Linux TPIDR_EL0 */
+ ldr x10, [x9, #448]
+ msr tpidr_el0, x10 /* load XNU TPIDR_EL0 */
+ mov x0, x20
+ blr x19
+ W_EL0(x9)
+ mov x19, #0
+ ldr x10, [x9, #216]
+ msr tpidr_el0, x10 /* restore Linux TPIDR_EL0 before fki_leave */
+ b 2f
+xnu_world_abort_el0: /* from xnu_world_upcall_el0: Linux TPIDR_EL0 and keys are already live */
+ W_EL0(x9)
+ mov x19, #1
+2: ldr x18, [x9, #464]
+ ldr x10, [x9, #96]
+ mov sp, x10
+ ldr x0, [x9, #104]
+ add x1, x9, #240
+ bl fki_leave /* Linux keys, IRQs, preemption back */
+ mov x0, x19
+ W_EL0(x9)
+ ldp x19, x20, [x9, #0]
+ ldp x21, x22, [x9, #16]
+ ldp x23, x24, [x9, #32]
+ ldp x25, x26, [x9, #48]
+ ldp x27, x28, [x9, #64]
+ ldp x29, x30, [x9, #80]
+ ret
+ .size xnu_world_call_el0, . - xnu_world_call_el0
+
+ .globl xnu_world_upcall_el0
+ .type xnu_world_upcall_el0, %function
+xnu_world_upcall_el0:
+ hint #34 /* bti c */
+ W_EL0(x9)
+ stp x19, x20, [x9, #112]
+ stp x21, x22, [x9, #128]
+ stp x23, x24, [x9, #144]
+ stp x25, x26, [x9, #160]
+ stp x27, x28, [x9, #176]
+ stp x29, x30, [x9, #192]
+ mov x10, sp
+ str x10, [x9, #208]
+ mov x19, x0
+ mov x20, x1
+ mov x21, x2
+ mrs x10, tpidr_el0
+ str x10, [x9, #448] /* save XNU TPIDR_EL0 */
+ ldr x10, [x9, #216]
+ msr tpidr_el0, x10 /* restore Linux TPIDR_EL0 first */
+ add x0, x9, #240 /* load Linux keys */
+ add x1, x9, #328 /* save XNU keys */
+ bl fki_pac_swap
+ cbnz x0, .Lpac_fail_el0
+ mov x0, x19
+ mov x1, x20
+ mov x2, x21
+ bl xnu_hook
+ cbnz x0, xnu_world_abort_el0
+ W_EL0(x9)
+ add x0, x9, #328 /* load XNU keys (while Linux TPIDR_EL0 is live) */
+ add x1, x9, #240 /* save Linux keys */
+ bl fki_pac_swap
+ cbnz x0, .Lpac_fail_el0
+ W_EL0(x9)
+ mrs x10, tpidr_el0
+ str x10, [x9, #216]
+ ldr x10, [x9, #448]
+ msr tpidr_el0, x10 /* restore XNU TPIDR_EL0 */
+ ldr x10, [x9, #208]
+ mov sp, x10
+ ldp x19, x20, [x9, #112]
+ ldp x21, x22, [x9, #128]
+ ldp x23, x24, [x9, #144]
+ ldp x25, x26, [x9, #160]
+ ldp x27, x28, [x9, #176]
+ ldp x29, x30, [x9, #192]
+ ret
+.Lpac_fail_el0:
+ bl xnu_world_pac_abort_el0
+ .size xnu_world_upcall_el0, . - xnu_world_upcall_el0
diff --git a/xnu-ko/world.h b/xnu-ko/world.h
index 2506bb3..13a2359 100644
--- a/xnu-ko/world.h
+++ b/xnu-ko/world.h
@@ -26,6 +26,9 @@ extern struct xnu_world *xnu_worlds[]; /* each CPU's, by slot (LINUX64_CPU_SLOT)
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. */
void xnu_world_upcall(void);
+/* Pure EL0 host variants (FKI_CAP_EL0): no EL1 system instructions; slot from TPIDRRO_EL0. */
+long xnu_world_call_el0(unsigned long fn, unsigned long arg);
+void xnu_world_upcall_el0(void);
/* Where an XNU fault that cannot be handled returns to (still with XNU's keys): back to Linux's, then xnu_world_abort. */
void xnu_world_fault_abort(void);
/* Linux-world handler: return 0 to resume XNU, nonzero to end the run. */
diff --git a/xnu-ko/xnu_main.c b/xnu-ko/xnu_main.c
index 70b086d..bbdf087 100644
--- a/xnu-ko/xnu_main.c
+++ b/xnu-ko/xnu_main.c
@@ -52,16 +52,70 @@ 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];
+#define STOP_PARKED_MASK 0x0000ffffu
+#define STOP_ACTIVE_SHIFT 16
+#define STOP_ACTIVE_MASK 0x7fff0000u
+#define STOP_ACTIVE_ONE (1u << STOP_ACTIVE_SHIFT)
+#define STOP_COMMIT 0x80000000u
+static volatile unsigned stop_state = STOP_ACTIVE_ONE;
+static inline int stop_cas(unsigned old, unsigned new);
static void stop_commit(void);
+static int stop_park(int me);
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); }
+static int el0_mode; /* nonzero when host reports FKI_CAP_EL0 */
+struct cpu_slot_hot {
+ volatile int in_xnu_state, in_call;
+ unsigned long upcalls, last_call;
+ void *utcb;
+ void *utcb_as;
+ u64_t utcb_thread;
+ u64_t utcb_rop_pid, utcb_jop_pid;
+ int utcb_fpu_live, utcb_disable_jop;
+} __attribute__((aligned(64)));
+static struct cpu_slot_hot cpu_hot[LINUX64_CPU_SLOTS];
+static inline unsigned this_slot(void)
+{
+ if (el0_mode) {
+ unsigned long id;
+ __asm__ volatile("mrs %0, tpidrro_el0" : "=r"(id));
+ return (unsigned)(id & (LINUX64_CPU_SLOTS - 1));
+ }
+ 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);
static int assert_fatal; /* 1: a failed XNU assert() ends the run; 0: report it and let XNU continue */
module_param(assert_fatal, int, 0444);
+static int xo_compat; /* 1: opt-in fallback relaxing --x to r-x when host lacks FKI_CAP_EXEC_ONLY */
+module_param(xo_compat, int, 0444);
+/*
+ * EL0 KTCB lacks EL1 MRS emulation, so el0_patch_image replaces 2 ID_AA64ISAR0/PFR0_EL1
+ * instructions in com.apple.kec.corecrypto, invalidating its static __TEXT HMAC.
+ * By default (el0_fips_sha256=""), _fipspost_post_integrity is NEVER patched so the real
+ * integrity failure path stays intact. Only when the operator supplies the exact 64-hex
+ * SHA-256 of the unpatched com.apple.kec.corecrypto loaded segments is the integrity check
+ * updated after verifying the digest and that exactly those 2 ID-reg patches were applied.
+ */
+static char *el0_fips_sha256 = "";
+module_param(el0_fips_sha256, charp, 0444);
+
+__attribute__((target("branch-protection=none"), noreturn))
+void xnu_world_pac_abort_el0(int err);
+__attribute__((target("branch-protection=none"), noreturn))
+void xnu_world_pac_abort_el0(int err)
+{
+ static const char msg[] = "xnu: FATAL: fki_pac_swap failed in EL0 upcall\n";
+
+ (void)err;
+ fki_log_alert(msg, sizeof(msg) - 1);
+ BUG();
+}
static struct xnu_image img;
+static struct fki_pac_keys xnu_user_keys; /* separate PAC key domain for EL0 user contexts */
static struct fki_region l2page;
static unsigned long long *window_slot, *window_l1;
static unsigned char window_owned[512];
@@ -163,7 +217,7 @@ static int run_m1(void)
logkv("xnu: threaded fixups applied", (u64_t)n);
if (n < 0) return n;
u64_t v = macho_sym(&img, "_version"), sl = macho_sym(&img, "_strlen"), cr = macho_sym(&img, "_crc32");
- if (!v || !sl || !cr) { logs("xnu: symbols missing"); return 0; }
+ if (!v || !sl || !cr) { logs("xnu: symbols missing"); return -2; }
c = fki_enter(&xnu_W.xnu_keys, &saved);
unsigned long len = ((strlen_fn)sl)((const char *)v);
unsigned int crc = ((crc32_fn)cr)(0, (const void *)v, len);
@@ -245,8 +299,7 @@ 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_slot[LINUX64_CPU_SLOTS];
-#define in_xnu in_xnu_slot[this_slot()]
+#define in_xnu cpu_hot[this_slot()].in_xnu_state
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;
@@ -411,13 +464,26 @@ static int cpu_fn(void *arg)
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);
+ for (;;) {
+ unsigned s = stop_state;
+ if ((s & STOP_COMMIT) || ((s & STOP_ACTIVE_MASK) <= STOP_ACTIVE_ONE))
+ break;
+ if (stop_cas(s, s - STOP_ACTIVE_ONE))
+ break;
+ }
+ cpu_running[c] = 0;
+ while (!fki_thread_should_stop())
+ fki_msleep(10);
+ return 0;
+ }
+ if (READ_ONCE(stop_run) && stop_park(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]);
+ long r = el0_mode ? xnu_world_call_el0(a_cpu_entry, cpu_start_arg[c]) : 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 */
@@ -445,14 +511,24 @@ static inline void acct_add(unsigned long call, u64_t ticks)
acct_calls_slot[s][b]++;
}
+_Static_assert(sizeof(struct fki_utcb_regs) == 36 * sizeof(fki_u64), "fki_utcb_regs size");
+_Static_assert(__builtin_offsetof(struct linux64_utcb_req, sp) - __builtin_offsetof(struct linux64_utcb_req, x) ==
+ __builtin_offsetof(struct fki_utcb_regs, sp), "utcb_req sp offset");
+_Static_assert(__builtin_offsetof(struct linux64_utcb_req, pc) - __builtin_offsetof(struct linux64_utcb_req, x) ==
+ __builtin_offsetof(struct fki_utcb_regs, pc), "utcb_req pc offset");
+_Static_assert(__builtin_offsetof(struct linux64_utcb_req, pstate) - __builtin_offsetof(struct linux64_utcb_req, x) ==
+ __builtin_offsetof(struct fki_utcb_regs, pstate), "utcb_req pstate offset");
+_Static_assert(__builtin_offsetof(struct linux64_utcb_req, tpidr) - __builtin_offsetof(struct linux64_utcb_req, x) ==
+ __builtin_offsetof(struct fki_utcb_regs, tpidr), "utcb_req tpidr offset");
+_Static_assert(__builtin_offsetof(struct linux64_utcb_req, tpidrro) - __builtin_offsetof(struct linux64_utcb_req, x) ==
+ __builtin_offsetof(struct fki_utcb_regs, tpidrro), "utcb_req tpidrro offset");
+
/*
* Stopping the run: the CPUs leave XNU together. A CPU still inside XNU could otherwise wait for good, interrupts masked,
* for one that had already left. Each parks briefly at its host calls and kicks the others, so that one idle or in user
- * space comes to a host call too; the run is abandoned once all are parked at once.
- * stop_state: the number of parked CPUs, and STOP_COMMIT once the run is abandoned.
+ * space comes to a host call too; the run is abandoned once all active CPUs are parked at once.
+ * stop_state layout: [15:0] parked count, [30:16] active CPU count, [31] STOP_COMMIT.
*/
-#define STOP_COMMIT 0x10000u
-static volatile unsigned stop_state;
static inline int stop_cas(unsigned old, unsigned new)
{
unsigned cur, fail;
@@ -473,40 +549,54 @@ static void stop_commit(void)
unsigned s;
do s = stop_state; while (!(s & STOP_COMMIT) && !stop_cas(s, s | STOP_COMMIT));
}
-static int stop_park(void) /* 1: the run is abandoned, do not return to XNU */
+static int stop_park(int me) /* 1: the run is abandoned, do not return to XNU */
{
- unsigned s, in_xnu_cpus = 1;
+ unsigned s, last_active;
u64_t end;
- for (int c = 1; c < cpus; c++)
- in_xnu_cpus += cpu_running[c] != 0;
do {
s = stop_state;
if (s & STOP_COMMIT) return 1;
} while (!stop_cas(s, s + 1));
- for (int c = 0, me = linux_cpu_of_slot[this_slot()]; c < cpus; c++)
+ last_active = (s & STOP_ACTIVE_MASK) >> STOP_ACTIVE_SHIFT;
+ for (int c = 0; c < cpus; c++)
if (c != me && (c == 0 || cpu_running[c]))
fki_kick_cpu(c);
end = fki_counter() + fki_counter_frequency() / 500; /* 2 ms */
for (;;) {
+ unsigned parked, active;
+
s = stop_state;
if (s & STOP_COMMIT) return 1;
- if ((s & (STOP_COMMIT - 1)) >= in_xnu_cpus) { stop_cas(s, s | STOP_COMMIT); continue; }
+ parked = s & STOP_PARKED_MASK;
+ active = (s & STOP_ACTIVE_MASK) >> STOP_ACTIVE_SHIFT;
+ if (active != last_active) {
+ last_active = active;
+ for (int c = 0; c < cpus; c++)
+ if (c != me && (c == 0 || cpu_running[c]))
+ fki_kick_cpu(c);
+ }
+ if (parked >= active) { stop_cas(s, s | STOP_COMMIT); continue; }
if (fki_counter() > end && stop_cas(s, s - 1)) 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);
-/* each CPU's host calls so far, the last one's number, and whether it is inside one: the monitor's silent-CPU check */
-static unsigned long upcalls_slot[LINUX64_CPU_SLOTS], last_call_slot[LINUX64_CPU_SLOTS];
-static volatile int in_call_slot[LINUX64_CPU_SLOTS];
long xnu_hook(unsigned long call, unsigned long a1, unsigned long a2)
{
unsigned in_s = this_slot(); /* the thread is bound to its CPU while in the host */
- upcalls_slot[in_s]++;
- last_call_slot[in_s] = call;
- {
+ struct cpu_slot_hot *hot = &cpu_hot[in_s];
+ hot->upcalls++;
+ hot->last_call = call;
+ hot->in_xnu_state = 0;
+ if (*(volatile int *)&stop_run && stop_park(linux_cpu_of_slot[in_s])) { /* the host asked the run to end (scripts/xnulinux-boot.sh stop): XNU is abandoned here */
+ logs("xnu: run stopped by the host (stop_run)");
+ return 1;
+ }
+ u64_t t0 = 0;
+ int do_perf = unlikely(READ_ONCE(perf));
+ if (do_perf) {
/* debugging: an XNU stack Linux's overflow check would reject (bit 14 of sp set) */
static int told;
unsigned long sp;
@@ -516,29 +606,245 @@ long xnu_hook(unsigned long call, unsigned long a1, unsigned long a2)
logkv("xnu: upcall on an XNU stack with sp bit 14 set, sp", sp);
logkv("xnu: call", call);
}
+ t0 = fki_counter();
}
- in_xnu = 0;
- if (*(volatile int *)&stop_run && stop_park()) { /* the host asked the run to end: XNU is abandoned here */
- logs("xnu: run stopped by the host (stop_run)");
- return 1;
- }
- u64_t t0 = fki_counter();
- in_call_slot[in_s] = 1;
+ hot->in_call = 1;
long r = xnu_hook_body(call, a1, a2);
- in_call_slot[in_s] = 0;
- acct_add(call, fki_counter() - t0);
+ hot->in_call = 0;
+ if (do_perf)
+ acct_add(call, fki_counter() - t0);
if (r)
stop_commit(); /* this CPU ends the run by itself (a panic, a failed assert) */
- else if (*(volatile int *)&stop_run && stop_park()) { /* back from a long call when the stop was asked */
+ else if (*(volatile int *)&stop_run && stop_park(linux_cpu_of_slot[in_s])) { /* back from a long call when the stop was asked */
logs("xnu: run stopped by the host (stop_run)");
r = 1;
}
- if (!r) in_xnu = 1;
+ if (!r) hot->in_xnu_state = 1;
return r;
}
+static void derive_user_pac_keys(u64_t rop_pid, u64_t jop_pid, int djop,
+ struct fki_pac_keys *out)
+{
+ struct fki_pac_keys k = xnu_user_keys;
+ u64_t jmix = jop_pid * 0x9e3779b97f4a7c15ULL;
+ u64_t rmix = rop_pid * 0x9e3779b97f4a7c15ULL;
+ k.ia[0] ^= jop_pid; k.ia[1] ^= jmix;
+ k.da[0] ^= jop_pid; k.da[1] ^= jmix;
+ k.ga[0] ^= jop_pid; k.ga[1] ^= jmix;
+ k.ib[0] ^= rop_pid; k.ib[1] ^= rmix;
+ k.db[0] ^= rop_pid; k.db[1] ^= rmix;
+ if (djop)
+ k.sctlr_en &= ~((1ULL << 31) | (1ULL << 27));
+ *out = k;
+}
+
+static __always_inline u64_t xnu_user_pac_exec(u64_t val, u64_t disc,
+ unsigned int key, unsigned int is_auth)
+{
+ if (!is_auth) {
+ u64_t out = val;
+ if (key == LINUX64_PAC_KEY_IA)
+ __asm__ volatile(".arch armv8.3-a\n pacia %0, %1" : "+r"(out) : "r"(disc) : "memory");
+ else
+ __asm__ volatile(".arch armv8.3-a\n pacda %0, %1" : "+r"(out) : "r"(disc) : "memory");
+ return out;
+ }
+ /*
+ * Authenticate without trapping under FEAT_FPAC: strip the PAC, re-sign
+ * under the active user JOP key, and return the stripped pointer only on
+ * an exact match (otherwise return an ARMv8.3-A A-key error-tagged ptr).
+ */
+ u64_t stripped = val;
+ if (key == LINUX64_PAC_KEY_IA)
+ __asm__ volatile(".arch armv8.3-a\n xpaci %0" : "+r"(stripped) : : "memory");
+ else
+ __asm__ volatile(".arch armv8.3-a\n xpacd %0" : "+r"(stripped) : : "memory");
+ u64_t expected = stripped;
+ if (key == LINUX64_PAC_KEY_IA)
+ __asm__ volatile(".arch armv8.3-a\n pacia %0, %1" : "+r"(expected) : "r"(disc) : "memory");
+ else
+ __asm__ volatile(".arch armv8.3-a\n pacda %0, %1" : "+r"(expected) : "r"(disc) : "memory");
+ if (expected == val)
+ return stripped;
+ return (stripped & ~(3ULL << 61)) | (1ULL << 61);
+}
+
static long xnu_hook_body(unsigned long call, unsigned long a1, unsigned long a2)
{
+ if (call == LINUX64_CALL_USER_PAC_OP) {
+ struct linux64_user_pac_req *q = (struct linux64_user_pac_req *)a1;
+ if (!q)
+ return 0;
+ struct fki_pac_keys uk, saved, tmp;
+ derive_user_pac_keys(0, q->jop_key, 0, &uk);
+ int perr = fki_pac_swap(&uk, &saved);
+ if (perr != 0) {
+ q->err = perr;
+ return 0;
+ }
+ q->result = xnu_user_pac_exec(q->value, q->discriminator, q->key, q->is_auth);
+ q->err = 0;
+ int rerr = fki_pac_swap(&saved, &tmp);
+ if (rerr != 0) {
+ logs("xnu: failed to restore kernel PAC keys");
+ return 1;
+ }
+ return 0;
+ }
+ if (call == LINUX64_CALL_UTCB_RUN || call == LINUX64_CALL_UTCB_RESUME) {
+ struct linux64_utcb_req *q = (struct linux64_utcb_req *)a1;
+ if (!q || !q->as_handle)
+ return 0;
+ unsigned s = this_slot();
+ struct cpu_slot_hot *hot = &cpu_hot[s];
+ void *as = (void *)(unsigned long)q->as_handle;
+ void *utcb = hot->utcb;
+ int djop = q->disable_jop ? 1 : 0;
+ if (call == LINUX64_CALL_UTCB_RESUME &&
+ likely(utcb && hot->utcb_thread == q->thread_id && !q->fpu_dirty &&
+ hot->utcb_as == as && hot->utcb_disable_jop == djop &&
+ hot->utcb_rop_pid == q->rop_pid && hot->utcb_jop_pid == q->jop_pid)) {
+ struct fki_utcb_stop stop;
+ int err = fki_utcb_resume(utcb, (struct fki_utcb_regs *)&q->x[0], &stop);
+ q->result = err;
+ if (err == 0) {
+ hot->utcb_fpu_live = 1;
+ q->stop_kind = stop.kind;
+ q->fault_addr = stop.fault_addr;
+ q->fault_ip = stop.fault_ip;
+ q->esr = stop.esr;
+ }
+ return 0;
+ }
+ if (!utcb) {
+ utcb = fki_utcb_create(as);
+ if (!utcb) {
+ q->result = -12;
+ return 0;
+ }
+ hot->utcb = utcb;
+ hot->utcb_as = as;
+ hot->utcb_thread = 0;
+ hot->utcb_fpu_live = 0;
+ hot->utcb_disable_jop = -1;
+ hot->utcb_rop_pid = ~0ULL;
+ hot->utcb_jop_pid = ~0ULL;
+ } else if (hot->utcb_as != as) {
+ int aerr = fki_utcb_set_as(utcb, as);
+ if (aerr != 0) {
+ q->result = aerr;
+ return 0;
+ }
+ hot->utcb_as = as;
+ }
+ if (hot->utcb_disable_jop != djop ||
+ hot->utcb_rop_pid != q->rop_pid ||
+ hot->utcb_jop_pid != q->jop_pid) {
+ struct fki_pac_keys k;
+ derive_user_pac_keys(q->rop_pid, q->jop_pid, djop, &k);
+ int perr = fki_utcb_set_pac(utcb, &k);
+ if (perr != 0) {
+ q->result = perr;
+ return 0;
+ }
+ hot->utcb_disable_jop = djop;
+ hot->utcb_rop_pid = q->rop_pid;
+ hot->utcb_jop_pid = q->jop_pid;
+ }
+ if (q->fpu_dirty || hot->utcb_thread != q->thread_id) {
+ if (!q->neon_ptr) {
+ q->result = -22;
+ return 0;
+ }
+ int ferr = fki_utcb_fpu_write(utcb, (const void *)(unsigned long)q->neon_ptr, 520);
+ if (ferr != 0) {
+ q->result = ferr;
+ return 0;
+ }
+ hot->utcb_thread = q->thread_id;
+ hot->utcb_fpu_live = 0;
+ q->fpu_dirty = 0;
+ }
+ struct fki_utcb_stop stop;
+ int err = fki_utcb_run(utcb, (struct fki_utcb_regs *)&q->x[0], &stop);
+ q->result = err;
+ if (err == 0) {
+ hot->utcb_fpu_live = 1;
+ q->stop_kind = stop.kind;
+ q->fault_addr = stop.fault_addr;
+ q->fault_ip = stop.fault_ip;
+ q->esr = stop.esr;
+ }
+ return 0;
+ }
+ if (call == LINUX64_CALL_UTCB_SYNC_REGS) {
+ struct linux64_utcb_req *q = (struct linux64_utcb_req *)a1;
+ if (!q)
+ return 0;
+ unsigned s = this_slot();
+ struct cpu_slot_hot *hot = &cpu_hot[s];
+ if (unlikely(!hot->utcb)) {
+ q->result = -22;
+ return 0;
+ }
+ q->result = fki_utcb_sync_regs(hot->utcb, (struct fki_utcb_regs *)&q->x[0]);
+ return 0;
+ }
+ if (call == LINUX64_CALL_UTCB_FPU_SYNC) {
+ struct linux64_fpu_sync_req *q = (struct linux64_fpu_sync_req *)a1;
+ if (!q)
+ return 0;
+ unsigned s = this_slot();
+ struct cpu_slot_hot *hot = &cpu_hot[s];
+ q->result = 0;
+ if ((q->flags & LINUX64_FPU_FLUSH) &&
+ hot->utcb && hot->utcb_thread == q->thread_id && hot->utcb_fpu_live) {
+ if (!q->neon_ptr) {
+ q->result = -22;
+ return 0;
+ }
+ int ferr = fki_utcb_fpu_read(hot->utcb, (void *)(unsigned long)q->neon_ptr, 520);
+ if (ferr != 0) {
+ q->result = ferr;
+ return 0;
+ }
+ hot->utcb_fpu_live = 0;
+ }
+ if ((q->flags & LINUX64_FPU_INVALIDATE) && hot->utcb_thread == q->thread_id) {
+ hot->utcb_fpu_live = 0;
+ hot->utcb_thread = 0;
+ }
+ return 0;
+ }
+ if (call == LINUX64_CALL_AS_MAP) {
+ struct linux64_map_req *q = (struct linux64_map_req *)a1;
+ if (q)
+ q->result = fki_as_map((void *)(unsigned long)q->as_handle, (unsigned long)q->va,
+ q->pa, (unsigned long)q->size, (int)q->prot);
+ return 0;
+ }
+ if (call == LINUX64_CALL_AS_UNMAP) {
+ struct linux64_map_req *q = (struct linux64_map_req *)a1;
+ if (q) {
+ fki_as_unmap((void *)(unsigned long)q->as_handle, (unsigned long)q->va,
+ (unsigned long)q->size);
+ q->result = 0;
+ }
+ return 0;
+ }
+ if (call == LINUX64_CALL_AS_FLUSH) {
+ struct linux64_map_req *q = (struct linux64_map_req *)a1;
+ if (q) {
+ fki_as_flush((void *)(unsigned long)q->as_handle);
+ q->result = 0;
+ }
+ return 0;
+ }
+ if (call == LINUX64_CALL_ICACHE_FLUSH) {
+ fki_icache_flush(a1, a2);
+ return 0;
+ }
if (call == LINUX64_CALL_CONSOLE_READ) { /* console input: new bytes of console_in */
struct linux64_buf_req *q = (struct linux64_buf_req *)a1;
if (!q) return 0;
@@ -673,7 +979,7 @@ static long xnu_hook_body(unsigned long call, unsigned long a1, unsigned long a2
logkv("xnu: probe Mach-O magic", *(volatile unsigned int *)diag_va[1]);
logkv("xnu: probe boot args Version", ((volatile struct boot_args_v2 *)diag_va[2])->Version);
logkv("xnu: probe ADT word", *(volatile unsigned int *)diag_va[3]);
- if (diag_va[4]) { volatile unsigned int *pc = (void *)diag_va[4]; unsigned v = *pc; *pc = v; logkv("xnu: probe port_crumb (rw)", v); }
+ if (diag_va[4]) { volatile u64_t *pc = (void *)diag_va[4]; u64_t v = *pc; *pc = v; logkv("xnu: probe port_crumb (rw)", v); }
if (diag_va[5]) { unsigned long l = ((unsigned long (*)(const char *))diag_va[5])("xnulinux"); logkv("xnu: probe exec strlen through XNU tables", l); }
logs("xnu: probes done");
}
@@ -721,14 +1027,28 @@ static long xnu_hook_body(unsigned long call, unsigned long a1, unsigned long a2
logs_alert("xnu: XNU panic:");
logs_alert(m);
logkv("xnu: panic caller", a2);
+ if (diag_va[4])
+ logkv("xnu: port_crumb", *(volatile u64_t *)diag_va[4]);
{ /* the frame-pointer chain from here through XNU's frames (the hook runs on XNU's stack); return addresses
* with their pointer-authentication bits replaced by the kernel's all-ones top */
- unsigned long *fp = __builtin_frame_address(0);
- for (i = 0; i < 24 && fp && !((unsigned long)fp & 15) && (unsigned long)fp >> 48 == 0xffff; i++) {
- unsigned long lr = fp[1] | 0xffffff8000000000ul;
+ unsigned long *fp = el0_mode ? (unsigned long *)xnu_worlds[this_slot()]->xnu_regs[10] : __builtin_frame_address(0);
+ unsigned long fp_lo = el0_mode ? (unsigned long)(img.vmlow & ~0x1fffffULL) : 0xffffff8000000000UL;
+ unsigned long fp_hi = 0xfffffffc00000000UL;
+ for (i = 0; i < 24 && fp && !((unsigned long)fp & 15) &&
+ (unsigned long)fp >= fp_lo && (unsigned long)fp + 16 <= fp_hi; i++) {
+ fki_u64 w0, w1;
+ if (el0_mode) {
+ if (fki_high_read_u64x2((unsigned long)fp, &w0, &w1) != 0)
+ break;
+ } else {
+ w0 = fp[0];
+ w1 = fp[1];
+ }
+ unsigned long lr = (unsigned long)w1 | 0xffffff8000000000ul;
+ unsigned long *next = (unsigned long *)w0;
logkv("xnu: frame", lr);
- if ((unsigned long *)fp[0] <= fp) break;
- fp = (unsigned long *)fp[0];
+ if (next <= fp || (unsigned long)next - (unsigned long)fp > 0x100000UL) break;
+ fp = next;
}
}
return 1;
@@ -740,6 +1060,16 @@ static long xnu_hook_body(unsigned long call, unsigned long a1, unsigned long a2
logkv("xnu: XNU asked to start a CPU it was not given, MPIDR", a1);
return 0;
}
+ for (;;) {
+ unsigned s;
+ if (READ_ONCE(stop_run))
+ return 0;
+ s = stop_state;
+ if (s & STOP_COMMIT)
+ return 0;
+ if (stop_cas(s, s + STOP_ACTIVE_ONE))
+ break;
+ }
cpu_running[c] = 1;
WRITE_ONCE(cpu_start_arg[c], a2);
fki_thread_wake(cpu_thread[c]);
@@ -753,6 +1083,61 @@ static long xnu_hook_body(unsigned long call, unsigned long a1, unsigned long a2
}
if (call == LINUX64_CALL_KERNEL_TABLES)
return 0;
+ if (call == LINUX64_CALL_KMAP) {
+ struct linux64_map_req *q = (struct linux64_map_req *)a1;
+ if (q)
+ q->result = fki_high_map((unsigned long)q->va, q->pa, (unsigned long)q->size, (int)q->prot);
+ return 0;
+ }
+ if (call == LINUX64_CALL_KUNMAP) {
+ struct linux64_map_req *q = (struct linux64_map_req *)a1;
+ if (q) {
+ fki_high_unmap((unsigned long)q->va, (unsigned long)q->size);
+ q->result = 0;
+ }
+ return 0;
+ }
+ if (call == LINUX64_CALL_KFLUSH) {
+ fki_high_flush();
+ return 0;
+ }
+ if (call == LINUX64_CALL_KMAP_TXN) {
+ struct linux64_map_req *q = (struct linux64_map_req *)a1;
+ if (q) {
+ if (q->prot == LINUX64_KMAP_TXN_BEGIN) {
+ void *txn = NULL;
+ int err = fki_high_txn_begin((unsigned long)q->va, (unsigned long)q->size, &txn);
+ q->as_handle = (u64_t)(unsigned long)txn;
+ q->result = err;
+ } else if (q->prot == LINUX64_KMAP_TXN_RESTORE) {
+ fki_high_txn_restore((void *)(unsigned long)q->as_handle);
+ q->result = 0;
+ } else if (q->prot == LINUX64_KMAP_TXN_END) {
+ fki_high_txn_end((void *)(unsigned long)q->as_handle);
+ q->result = 0;
+ } else {
+ q->result = -22; /* -EINVAL */
+ }
+ }
+ return 0;
+ }
+ if (call == LINUX64_CALL_AS_CREATE) {
+ struct linux64_map_req *q = (struct linux64_map_req *)a1;
+ if (q) {
+ q->as_handle = (u64_t)(unsigned long)fki_as_create();
+ q->result = q->as_handle ? 0 : -12;
+ }
+ return 0;
+ }
+ if (call == LINUX64_CALL_AS_DESTROY) {
+ struct linux64_map_req *q = (struct linux64_map_req *)a1;
+ if (q && q->as_handle) {
+ fki_as_destroy((void *)(unsigned long)q->as_handle);
+ q->as_handle = 0;
+ q->result = 0;
+ }
+ return 0;
+ }
{ /* a call this module does not know (an XNU built against a newer linux64_abi.h): say so once, go on */
static unsigned long told;
if (told != call) { told = call; logkv("xnu: unknown call from XNU", call); }
@@ -1092,7 +1477,7 @@ static int monitor_fn(void *arg)
static unsigned long seen[XNU_MAX_CPUS], still[XNU_MAX_CPUS];
for (int c = 0; c < cpus && xnu_dbg; c++) {
unsigned s = LINUX64_CPU_SLOT(cpu_mpidr[c]);
- if ((c && !cpu_running[c]) || upcalls_slot[s] != seen[c]) { seen[c] = upcalls_slot[s]; still[c] = 0; continue; }
+ if ((c && !cpu_running[c]) || cpu_hot[s].upcalls != seen[c]) { seen[c] = cpu_hot[s].upcalls; still[c] = 0; continue; }
if (++still[c] == 1) {
struct xnu_world *w = xnu_worlds[s];
unsigned long fp = w->xnu_regs[10];
@@ -1100,17 +1485,27 @@ static int monitor_fn(void *arg)
char ab[160]; char *q = ab;
put_str(&q, "xnu: XNU CPU "); q = put_dec(q, (unsigned long)c);
put_str(&q, " made no host call for 2 s (its Linux CPU held, interrupts masked); last call ");
- q = put_dec(q, last_call_slot[s]); put_str(&q, in_call_slot[s] ? " (inside it)" : " (back in XNU)");
+ q = put_dec(q, cpu_hot[s].last_call); put_str(&q, cpu_hot[s].in_call ? " (inside it)" : " (back in XNU)");
*q = 0;
logs_alert(ab);
}
logkv("xnu: XNU CPU silent for 2 s (no host call), cpu", (u64_t)c);
- logkv("xnu: its last host call", last_call_slot[s]);
- logkv("xnu: still inside it (1) or back in XNU (0)", in_call_slot[s]);
+ logkv("xnu: its last host call", cpu_hot[s].last_call);
+ logkv("xnu: still inside it (1) or back in XNU (0)", cpu_hot[s].in_call);
logkv("xnu: lr at that call", w->xnu_regs[11]);
for (int f = 0; f < 16 && fp >= XNU_VA_LO && fp < XNU_VA_HI && !(fp & 7); f++) {
- logkv("xnu: frame", ((unsigned long *)fp)[1]);
- fp = ((unsigned long *)fp)[0];
+ fki_u64 w0, w1;
+ if (el0_mode) {
+ if (fki_high_read_u64x2(fp, &w0, &w1) != 0)
+ break;
+ } else {
+ w0 = ((unsigned long *)fp)[0];
+ w1 = ((unsigned long *)fp)[1];
+ }
+ unsigned long next = (unsigned long)w0;
+ logkv("xnu: frame", w1);
+ if (next <= fp || next - fp > 0x100000UL) break;
+ fp = next;
}
}
}
@@ -1120,7 +1515,7 @@ static int monitor_fn(void *arg)
put_str(&q, "xnu: calls");
for (int c = 0; c < cpus; c++) {
unsigned s = LINUX64_CPU_SLOT(cpu_mpidr[c]);
- put_str(&q, " "); q = put_dec(q, upcalls_slot[s]); put_str(&q, "/"); q = put_dec(q, last_call_slot[s]);
+ put_str(&q, " "); q = put_dec(q, cpu_hot[s].upcalls); put_str(&q, "/"); q = put_dec(q, cpu_hot[s].last_call);
}
*q = 0;
logs(cb);
@@ -1157,6 +1552,472 @@ static int fb_fn(void *arg)
return 0;
}
+/*
+ * Pure EL0 load-time binary patching:
+ * 1. Replace UBSan minimal soft-trap `brk #0xff00` (0xd43fe000) with `nop` (0xd503201f).
+ * 2. Replace EL1 ID register reads (`mrs xN, ID_AA64ISAR0_EL1` / `ID_AA64PFR0_EL1`) found in
+ * prelinked kexts with `movz xN, #0` (0xd2800000 | rd) so they take the safe baseline path
+ * without trapping at EL0.
+ */
+#define S_ATTR_PURE_INSTRUCTIONS 0x80000000U
+#define S_ATTR_SOME_INSTRUCTIONS 0x00000400U
+
+static int x_str_bounded_eq(const char *s, u64_t max, const char *lit)
+{
+ u64_t i = 0;
+ while (i < max) {
+ if (s[i] != lit[i])
+ return 0;
+ if (s[i] == 0)
+ return 1;
+ i++;
+ }
+ return 0;
+}
+
+struct el0_va_span {
+ u64_t lo, hi;
+};
+
+static int va_in_spans(const struct el0_va_span *spans, unsigned nspans, u64_t va, u64_t len)
+{
+ if (!len || va + len < va)
+ return 0;
+ for (unsigned i = 0; i < nspans; i++) {
+ if (va >= spans[i].lo && va + len <= spans[i].hi)
+ return 1;
+ }
+ return 0;
+}
+
+#define XNU_LC_OK(l, end) \
+ ((const char *)(end) - (const char *)(l) >= (long)sizeof(struct lc) && \
+ (l)->cmdsize >= sizeof(struct lc) && \
+ (l)->cmdsize <= (u64_t)((const char *)(end) - (const char *)(l)))
+
+static int va_in_loaded_segs_prot(const struct xnu_image *im, u64_t va, u64_t len, u32_t req_prot)
+{
+ if (!len || va + len < va)
+ return 0;
+ const struct mh64 *mh = (const void *)im->file;
+ const struct lc *l = (const void *)(im->file + sizeof(*mh));
+ const struct lc *end = (const void *)(im->file + sizeof(*mh) + mh->sizeofcmds);
+ for (u32_t ci = 0; ci < mh->ncmds && XNU_LC_OK(l, end);
+ ci++, l = (const void *)((const char *)l + l->cmdsize)) {
+ if (l->cmd != LC_SEGMENT_64 || l->cmdsize < sizeof(struct seg64))
+ continue;
+ const struct seg64 *s = (const void *)l;
+ if (!x_strncmp(s->segname, "__PAGEZERO", 16))
+ continue;
+ /* Writable segments include zero-filled BSS (vmsize > filesize). */
+ u64_t span = (s->initprot & 2) ? s->vmsize : s->filesize;
+ if (!span || (s->initprot & req_prot) != req_prot)
+ continue;
+ u64_t lo;
+ if (!macho_va_to_loaded(im, s->vmaddr, span, &lo))
+ continue;
+ u64_t hi = lo + span;
+ if (va >= lo && va + len <= hi)
+ return 1;
+ }
+ return 0;
+}
+
+static int va_in_loaded_segs(const struct xnu_image *im, u64_t va, u64_t len)
+{
+ return va_in_loaded_segs_prot(im, va, len, 1);
+}
+
+/* Minimal self-contained SHA-256 (FIPS 180-4) for corecrypto pre-patch verification. */
+struct el0_sha256_ctx {
+ u32_t h[8];
+ u64_t bits;
+ unsigned char buf[64];
+ unsigned n;
+};
+
+static inline u32_t sha256_rotr(u32_t x, unsigned r) { return (x >> r) | (x << (32 - r)); }
+
+static void sha256_compress(u32_t h[8], const unsigned char blk[64])
+{
+ static const u32_t K[64] = {
+ 0x428a2f98U, 0x71374491U, 0xb5c0fbcfU, 0xe9b5dba5U, 0x3956c25bU, 0x59f111f1U, 0x923f82a4U, 0xab1c5ed5U,
+ 0xd807aa98U, 0x12835b01U, 0x243185beU, 0x550c7dc3U, 0x72be5d74U, 0x80deb1feU, 0x9bdc06a7U, 0xc19bf174U,
+ 0xe49b69c1U, 0xefbe4786U, 0x0fc19dc6U, 0x240ca1ccU, 0x2de92c6fU, 0x4a7484aaU, 0x5cb0a9dcU, 0x76f988daU,
+ 0x983e5152U, 0xa831c66dU, 0xb00327c8U, 0xbf597fc7U, 0xc6e00bf3U, 0xd5a79147U, 0x06ca6351U, 0x14292967U,
+ 0x27b70a85U, 0x2e1b2138U, 0x4d2c6dfcU, 0x53380d13U, 0x650a7354U, 0x766a0abbU, 0x81c2c92eU, 0x92722c85U,
+ 0xa2bfe8a1U, 0xa81a664bU, 0xc24b8b70U, 0xc76c51a3U, 0xd192e819U, 0xd6990624U, 0xf40e3585U, 0x106aa070U,
+ 0x19a4c116U, 0x1e376c08U, 0x2748774cU, 0x34b0bcb5U, 0x391c0cb3U, 0x4ed8aa4aU, 0x5b9cca4fU, 0x682e6ff3U,
+ 0x748f82eeU, 0x78a5636fU, 0x84c87814U, 0x8cc70208U, 0x90befffaU, 0xa4506cebU, 0xbef9a3f7U, 0xc67178f2U,
+ };
+ u32_t w[64], a, b, c, d, e, f, g, hh;
+ for (unsigned i = 0; i < 16; i++)
+ w[i] = ((u32_t)blk[i * 4] << 24) | ((u32_t)blk[i * 4 + 1] << 16) |
+ ((u32_t)blk[i * 4 + 2] << 8) | (u32_t)blk[i * 4 + 3];
+ for (unsigned i = 16; i < 64; i++) {
+ u32_t s0 = sha256_rotr(w[i - 15], 7) ^ sha256_rotr(w[i - 15], 18) ^ (w[i - 15] >> 3);
+ u32_t s1 = sha256_rotr(w[i - 2], 17) ^ sha256_rotr(w[i - 2], 19) ^ (w[i - 2] >> 10);
+ w[i] = w[i - 16] + s0 + w[i - 7] + s1;
+ }
+ a = h[0]; b = h[1]; c = h[2]; d = h[3]; e = h[4]; f = h[5]; g = h[6]; hh = h[7];
+ for (unsigned i = 0; i < 64; i++) {
+ u32_t S1 = sha256_rotr(e, 6) ^ sha256_rotr(e, 11) ^ sha256_rotr(e, 25);
+ u32_t ch = (e & f) ^ ((~e) & g);
+ u32_t t1 = hh + S1 + ch + K[i] + w[i];
+ u32_t S0 = sha256_rotr(a, 2) ^ sha256_rotr(a, 13) ^ sha256_rotr(a, 22);
+ u32_t maj = (a & b) ^ (a & c) ^ (b & c);
+ u32_t t2 = S0 + maj;
+ hh = g; g = f; f = e; e = d + t1;
+ d = c; c = b; b = a; a = t1 + t2;
+ }
+ h[0] += a; h[1] += b; h[2] += c; h[3] += d; h[4] += e; h[5] += f; h[6] += g; h[7] += hh;
+}
+
+static void sha256_init(struct el0_sha256_ctx *ctx)
+{
+ ctx->h[0] = 0x6a09e667U; ctx->h[1] = 0xbb67ae85U; ctx->h[2] = 0x3c6ef372U; ctx->h[3] = 0xa54ff53aU;
+ ctx->h[4] = 0x510e527fU; ctx->h[5] = 0x9b05688cU; ctx->h[6] = 0x1f83d9abU; ctx->h[7] = 0x5be0cd19U;
+ ctx->bits = 0;
+ ctx->n = 0;
+}
+
+static void sha256_update(struct el0_sha256_ctx *ctx, const unsigned char *p, u64_t len)
+{
+ ctx->bits += len * 8;
+ while (len > 0) {
+ unsigned take = (unsigned)(64 - ctx->n);
+ if (take > len)
+ take = (unsigned)len;
+ x_memcpy(ctx->buf + ctx->n, p, take);
+ ctx->n += take;
+ p += take;
+ len -= take;
+ if (ctx->n == 64) {
+ sha256_compress(ctx->h, ctx->buf);
+ ctx->n = 0;
+ }
+ }
+}
+
+static void sha256_final(struct el0_sha256_ctx *ctx, unsigned char out[32])
+{
+ ctx->buf[ctx->n++] = 0x80;
+ if (ctx->n > 56) {
+ while (ctx->n < 64)
+ ctx->buf[ctx->n++] = 0;
+ sha256_compress(ctx->h, ctx->buf);
+ ctx->n = 0;
+ }
+ while (ctx->n < 56)
+ ctx->buf[ctx->n++] = 0;
+ for (unsigned i = 0; i < 8; i++)
+ ctx->buf[56 + i] = (unsigned char)(ctx->bits >> (56 - i * 8));
+ sha256_compress(ctx->h, ctx->buf);
+ for (unsigned i = 0; i < 8; i++) {
+ out[i * 4 + 0] = (unsigned char)(ctx->h[i] >> 24);
+ out[i * 4 + 1] = (unsigned char)(ctx->h[i] >> 16);
+ out[i * 4 + 2] = (unsigned char)(ctx->h[i] >> 8);
+ out[i * 4 + 3] = (unsigned char)(ctx->h[i]);
+ }
+}
+
+static int parse_sha256_hex(const char *s, unsigned char out[32])
+{
+ if (!s)
+ return 0;
+ for (unsigned i = 0; i < 32; i++) {
+ unsigned char v = 0;
+ for (unsigned k = 0; k < 2; k++) {
+ char c = s[i * 2 + k];
+ unsigned char d;
+ if (c >= '0' && c <= '9') d = (unsigned char)(c - '0');
+ else if (c >= 'a' && c <= 'f') d = (unsigned char)(c - 'a' + 10);
+ else if (c >= 'A' && c <= 'F') d = (unsigned char)(c - 'A' + 10);
+ else return 0;
+ v = (unsigned char)((v << 4) | d);
+ }
+ out[i] = v;
+ }
+ return s[64] == '\0';
+}
+
+static int ct_memeq32(const unsigned char a[32], const unsigned char b[32])
+{
+ unsigned char diff = 0;
+ for (unsigned i = 0; i < 32; i++)
+ diff |= (unsigned char)(a[i] ^ b[i]);
+ return diff == 0;
+}
+
+static void log_sha256(const char *prefix, const unsigned char d[32])
+{
+ static const char hex[] = "0123456789abcdef";
+ char line[160];
+ unsigned p = 0;
+ while (prefix[p] && p < 80) {
+ line[p] = prefix[p];
+ p++;
+ }
+ for (unsigned i = 0; i < 32; i++) {
+ line[p++] = hex[d[i] >> 4];
+ line[p++] = hex[d[i] & 0xf];
+ }
+ line[p++] = '\n';
+ fki_log(line, p);
+}
+
+static void el0_patch_macho_sections(const struct xnu_image *im, const struct mh64 *mh,
+ const struct el0_va_span *cc_sects, unsigned cc_nsects,
+ u64_t *n_ubsan, u64_t *n_idreg,
+ u64_t *n_cc_idreg, u64_t *n_cc_ubsan)
+{
+ const char *file = (const char *)im->file;
+ u64_t file_size = im->file_size;
+ u64_t mh_off = (u64_t)((const char *)mh - file);
+ if (mh_off > file_size || file_size - mh_off < sizeof(*mh) ||
+ mh->magic != MH_MAGIC_64 ||
+ mh->sizeofcmds > file_size - mh_off - sizeof(*mh) ||
+ mh->ncmds > mh->sizeofcmds / sizeof(struct lc))
+ return;
+ const struct lc *l = (const void *)(mh + 1);
+ const struct lc *end = (const void *)((const char *)l + mh->sizeofcmds);
+ for (u32_t ci = 0; ci < mh->ncmds && XNU_LC_OK(l, end);
+ ci++, l = (const void *)((const char *)l + l->cmdsize)) {
+ if (l->cmd != LC_SEGMENT_64 || l->cmdsize < sizeof(struct seg64))
+ continue;
+ const struct seg64 *s = (const void *)l;
+ if (!s->vmsize || !(s->initprot & 4))
+ continue;
+ if ((u64_t)s->nsects > (l->cmdsize - sizeof(*s)) / sizeof(struct sect64))
+ continue;
+ const struct sect64 *sc = (const void *)(s + 1);
+ for (u32_t si = 0; si < s->nsects; si++) {
+ if (!(sc[si].flags & (S_ATTR_PURE_INSTRUCTIONS | S_ATTR_SOME_INSTRUCTIONS)))
+ continue;
+ if (!sc[si].size || sc[si].addr < s->vmaddr ||
+ sc[si].addr - s->vmaddr > s->vmsize ||
+ sc[si].size > s->vmsize - (sc[si].addr - s->vmaddr))
+ continue;
+ u64_t sec_va;
+ if (!macho_va_to_loaded(im, sc[si].addr, sc[si].size, &sec_va) ||
+ (sec_va & 3) ||
+ !va_in_loaded_segs(im, sec_va, sc[si].size))
+ continue;
+ u32_t *ins = (u32_t *)sec_va;
+ u64_t cnt = sc[si].size / 4;
+ for (u64_t i = 0; i < cnt; i++) {
+ u32_t w = ins[i];
+ if (w == 0xd43fe000U) { /* brk #0xff00 */
+ u64_t va = (u64_t)&ins[i];
+ ins[i] = 0xd503201fU; /* nop */
+ __asm__ volatile("dc cvau, %0\n\tdsb ish\n\tic ivau, %0" : : "r"(&ins[i]) : "memory");
+ if (va_in_spans(cc_sects, cc_nsects, va, 4))
+ (*n_cc_ubsan)++;
+ (*n_ubsan)++;
+ } else if ((w & 0xffffffe0U) == 0xd5380600U || /* mrs xN, ID_AA64ISAR0_EL1 */
+ (w & 0xffffffe0U) == 0xd5380400U) { /* mrs xN, ID_AA64PFR0_EL1 */
+ u32_t rd = w & 0x1fU;
+ u64_t va = (u64_t)&ins[i];
+ ins[i] = 0xd2800000U | rd; /* movz xN, #0 */
+ __asm__ volatile("dc cvau, %0\n\tdsb ish\n\tic ivau, %0" : : "r"(&ins[i]) : "memory");
+ if (va_in_spans(cc_sects, cc_nsects, va, 4))
+ (*n_cc_idreg)++;
+ if (*n_idreg < 16) {
+ logkv("xnu: EL0 patched ID-reg mrs at", va);
+ logkv("xnu: original insn", w);
+ }
+ (*n_idreg)++;
+ }
+ }
+ }
+ }
+}
+
+static void el0_patch_image(struct xnu_image *im)
+{
+ const struct mh64 *mh = (const void *)im->file;
+ const struct lc *l = (const void *)(im->file + sizeof(*mh));
+ const struct lc *end = (const void *)(im->file + sizeof(*mh) + mh->sizeofcmds);
+ u64_t n_ubsan = 0, n_idreg = 0, n_cc_idreg = 0, n_cc_ubsan = 0;
+ struct el0_va_span cc_sects[32];
+ unsigned cc_nsects = 0;
+ int cc_sects_overflow = 0;
+ const struct fileset_entry_lc *cc_fe = 0;
+ unsigned char cc_digest[32];
+ int have_cc_digest = 0;
+
+ /* Locate com.apple.kec.corecrypto executable sections & hash unpatched loaded bytes. */
+ if (im->filetype == MH_FILESET) {
+ u32_t fi = 0;
+ for (const struct lc *fl = l; fi < mh->ncmds && XNU_LC_OK(fl, end);
+ fi++, fl = (const void *)((const char *)fl + fl->cmdsize)) {
+ if (fl->cmd != LC_FILESET_ENTRY || fl->cmdsize < sizeof(struct fileset_entry_lc))
+ continue;
+ const struct fileset_entry_lc *fe = (const void *)fl;
+ if (fe->entry_id >= fe->cmdsize ||
+ !x_str_bounded_eq((const char *)fe + fe->entry_id,
+ fe->cmdsize - fe->entry_id,
+ "com.apple.kec.corecrypto"))
+ continue;
+ if (fe->fileoff > im->file_size || im->file_size - fe->fileoff < sizeof(*mh))
+ break;
+ const struct mh64 *cmh = (const void *)(im->file + fe->fileoff);
+ if (cmh->magic != MH_MAGIC_64 ||
+ cmh->sizeofcmds > im->file_size - fe->fileoff - sizeof(*cmh) ||
+ cmh->ncmds > cmh->sizeofcmds / sizeof(struct lc))
+ break;
+ cc_fe = fe;
+ struct el0_sha256_ctx sctx;
+ sha256_init(&sctx);
+ int hash_ok = 1;
+ const struct lc *cl = (const void *)(cmh + 1);
+ const struct lc *cend = (const void *)((const char *)cl + cmh->sizeofcmds);
+ for (u32_t ci = 0; ci < cmh->ncmds && XNU_LC_OK(cl, cend);
+ ci++, cl = (const void *)((const char *)cl + cl->cmdsize)) {
+ if (cl->cmd != LC_SEGMENT_64 || cl->cmdsize < sizeof(struct seg64))
+ continue;
+ const struct seg64 *cs = (const void *)cl;
+ if (cs->filesize) {
+ u64_t seg_va;
+ if (!macho_va_to_loaded(im, cs->vmaddr, cs->filesize, &seg_va) ||
+ !va_in_loaded_segs(im, seg_va, cs->filesize)) {
+ hash_ok = 0;
+ } else {
+ sha256_update(&sctx, (const unsigned char *)seg_va, cs->filesize);
+ }
+ }
+ if (!(cs->initprot & 4) || !cs->vmsize)
+ continue;
+ if ((u64_t)cs->nsects > (cl->cmdsize - sizeof(*cs)) / sizeof(struct sect64))
+ continue;
+ const struct sect64 *csc = (const void *)(cs + 1);
+ for (u32_t si = 0; si < cs->nsects; si++) {
+ if (!(csc[si].flags & (S_ATTR_PURE_INSTRUCTIONS | S_ATTR_SOME_INSTRUCTIONS)))
+ continue;
+ if (!csc[si].size || csc[si].addr < cs->vmaddr ||
+ csc[si].addr - cs->vmaddr > cs->vmsize ||
+ csc[si].size > cs->vmsize - (csc[si].addr - cs->vmaddr))
+ continue;
+ u64_t lo;
+ if (!macho_va_to_loaded(im, csc[si].addr, csc[si].size, &lo) ||
+ !va_in_loaded_segs(im, lo, csc[si].size))
+ continue;
+ u64_t hi = lo + csc[si].size;
+ if (cc_nsects < sizeof(cc_sects) / sizeof(cc_sects[0])) {
+ cc_sects[cc_nsects].lo = lo;
+ cc_sects[cc_nsects].hi = hi;
+ cc_nsects++;
+ } else {
+ cc_sects_overflow = 1;
+ }
+ }
+ }
+ if (hash_ok) {
+ sha256_final(&sctx, cc_digest);
+ have_cc_digest = 1;
+ log_sha256("xnu: EL0 corecrypto unpatched sha256: ", cc_digest);
+ }
+ break;
+ }
+ }
+
+ /* Scan ONLY executable code sections (S_ATTR_PURE/SOME_INSTRUCTIONS), never data. */
+ if (im->filetype == MH_FILESET) {
+ u32_t fi = 0;
+ for (const struct lc *fl = l; fi < mh->ncmds && XNU_LC_OK(fl, end);
+ fi++, fl = (const void *)((const char *)fl + fl->cmdsize)) {
+ if (fl->cmd != LC_FILESET_ENTRY || fl->cmdsize < sizeof(struct fileset_entry_lc))
+ continue;
+ const struct fileset_entry_lc *fe = (const void *)fl;
+ if (fe->fileoff > im->file_size || im->file_size - fe->fileoff < sizeof(*mh))
+ continue;
+ el0_patch_macho_sections(im, (const void *)(im->file + fe->fileoff),
+ cc_sects, cc_nsects,
+ &n_ubsan, &n_idreg, &n_cc_idreg, &n_cc_ubsan);
+ }
+ } else {
+ el0_patch_macho_sections(im, mh, cc_sects, cc_nsects,
+ &n_ubsan, &n_idreg, &n_cc_idreg, &n_cc_ubsan);
+ }
+ __asm__ volatile("dsb ish\n\tisb" : : : "memory");
+ logkv("xnu: EL0 patched brk #0xff00 -> nop count", n_ubsan);
+ logkv("xnu: EL0 patched ID-reg mrs -> movz count", n_idreg);
+ logkv("xnu: EL0 corecrypto ID-reg patches", n_cc_idreg);
+
+ /*
+ * Preserve _fipspost_post_integrity failure path by default. Only update it when the
+ * operator explicitly provides el0_fips_sha256 matching the pre-patch SHA-256 of
+ * com.apple.kec.corecrypto's loaded segments, exactly 2 approved ID-reg instructions
+ * (and 0 other instructions) were patched in corecrypto, and the symbol lies in a
+ * corecrypto executable section + loaded top-level segment with a valid prologue.
+ */
+ unsigned char want_digest[32];
+ int fips_digest_ok = (have_cc_digest &&
+ parse_sha256_hex(el0_fips_sha256, want_digest) &&
+ ct_memeq32(cc_digest, want_digest));
+ if (fips_digest_ok && cc_fe && !cc_sects_overflow && n_cc_idreg == 2 && n_cc_ubsan == 0) {
+ const struct mh64 *cmh = (const void *)(im->file + cc_fe->fileoff);
+ const struct lc *cl = (const void *)(cmh + 1);
+ const struct lc *cend = (const void *)((const char *)cl + cmh->sizeofcmds);
+ for (u32_t ci = 0; ci < cmh->ncmds && XNU_LC_OK(cl, cend);
+ ci++, cl = (const void *)((const char *)cl + cl->cmdsize)) {
+ if (cl->cmd != LC_SYMTAB || cl->cmdsize < sizeof(struct symtab_lc))
+ continue;
+ const struct symtab_lc *st = (const void *)cl;
+ if ((u64_t)st->symoff > im->file_size ||
+ (u64_t)st->nsyms > (im->file_size - st->symoff) / sizeof(struct nlist64) ||
+ (u64_t)st->stroff > im->file_size ||
+ (u64_t)st->strsize > im->file_size - st->stroff)
+ break;
+ const struct nlist64 *nl = (const void *)(im->file + st->symoff);
+ const char *strs = (const char *)(im->file + st->stroff);
+ for (u32_t j = 0; j < st->nsyms; j++) {
+ if ((nl[j].n_type & 0xe0) || !nl[j].n_value || nl[j].n_strx >= st->strsize)
+ continue;
+ if (x_str_bounded_eq(strs + nl[j].n_strx,
+ st->strsize - nl[j].n_strx,
+ "_fipspost_post_integrity")) {
+ u64_t fn_va;
+ if (!macho_va_to_loaded(im, nl[j].n_value, 12, &fn_va) ||
+ (fn_va & 3) ||
+ !va_in_spans(cc_sects, cc_nsects, fn_va, 12) ||
+ !va_in_loaded_segs(im, fn_va, 12)) {
+ logs("xnu: skipping _fipspost_post_integrity patch (outside corecrypto exec section)");
+ break;
+ }
+ u32_t *fn = (u32_t *)fn_va;
+ u32_t p0 = fn[0];
+ /* Expect bti c (0xd503245f), pacibsp (0xd503237f), stp, or sub sp. */
+ if (p0 == 0xd503245fU || p0 == 0xd503237fU ||
+ (p0 & 0xffc003ffU) == 0xd10003ffU ||
+ (p0 & 0x7e000000U) == 0x28000000U) {
+ fn[0] = 0xd503245fU; /* bti c */
+ fn[1] = 0x52800000U; /* mov w0, #0 */
+ fn[2] = 0xd65f03c0U; /* ret */
+ for (int k = 0; k < 3; k++)
+ __asm__ volatile("dc cvau, %0\n\tdsb ish\n\tic ivau, %0" : : "r"(&fn[k]) : "memory");
+ __asm__ volatile("dsb ish\n\tisb" : : : "memory");
+ logkv("xnu: EL0 verified sha256 and patched _fipspost_post_integrity at", fn_va);
+ } else {
+ logkv("xnu: unexpected _fipspost_post_integrity prologue", p0);
+ }
+ break;
+ }
+ }
+ break;
+ }
+ } else if (cc_fe && (n_cc_idreg > 0 || n_cc_ubsan > 0 || cc_sects_overflow)) {
+ if (cc_sects_overflow)
+ logs("xnu: preserving _fipspost_post_integrity (corecrypto exec section table overflow)");
+ else if (!el0_fips_sha256 || !el0_fips_sha256[0])
+ logs("xnu: preserving _fipspost_post_integrity (el0_fips_sha256 not set)");
+ else if (!fips_digest_ok)
+ logs("xnu: preserving _fipspost_post_integrity (el0_fips_sha256 mismatch or invalid hex)");
+ else
+ logkv("xnu: preserving _fipspost_post_integrity (unexpected corecrypto ubsan patches)", n_cc_ubsan);
+ }
+}
+
static int enter_arm_init(struct boot_args_v2 *ba)
{
if (img.filetype == MH_FILESET) {
@@ -1174,18 +2035,79 @@ static int enter_arm_init(struct boot_args_v2 *ba)
int segs = macho_slide_header(&img, &mh_unslid);
logkv("xnu: load commands slid (segments)", (u64_t)segs);
}
+ if (el0_mode)
+ el0_patch_image(&img);
u64_t a_init = macho_sym(&img, "_arm_init"), a_hook = macho_sym(&img, "_linux64_hook"),
- a_slide = macho_sym(&img, "_linux64_slide");
+ a_slide = macho_sym(&img, "_linux64_slide"), a_el0 = macho_sym(&img, "_linux64_el0"),
+ a_el0_caps = macho_sym(&img, "_linux64_el0_caps"),
+ a_abi = macho_sym(&img, "_linux64_abi_version"),
+ a_host_abi = macho_sym(&img, "_linux64_host_abi_version");
logkv("xnu: arm_init at", a_init);
if (!a_init || !a_hook || !a_slide) { logs("xnu: arm_init or linux64_hook missing (kernel without the LINUX64 patch?)"); return -2; }
- *(u64_t *)a_hook = (u64_t)xnu_world_upcall;
+ if ((a_init & 3) || !va_in_loaded_segs_prot(&img, a_init, 4, 5) ||
+ (a_hook & 7) || !va_in_loaded_segs_prot(&img, a_hook, 8, 3) ||
+ (a_slide & 7) || !va_in_loaded_segs_prot(&img, a_slide, 8, 3)) {
+ logs("xnu: invalid boot symbol address or segment permissions");
+ return -22;
+ }
+ if (!a_abi || (a_abi & 3) || !va_in_loaded_segs_prot(&img, a_abi, 4, 1)) {
+ logs("xnu: _linux64_abi_version missing or invalid (stale kernel incompatible with host ABI)");
+ return -22;
+ }
+ if (*(unsigned int *)a_abi != LINUX64_ABI_VERSION) {
+ logkv("xnu: LINUX64_ABI_VERSION mismatch: kernel has", *(unsigned int *)a_abi);
+ logkv("xnu: LINUX64_ABI_VERSION expected by host", LINUX64_ABI_VERSION);
+ return -22;
+ }
+ if (!a_host_abi || (a_host_abi & 3) || !va_in_loaded_segs_prot(&img, a_host_abi, 4, 3)) {
+ logs("xnu: _linux64_host_abi_version missing or invalid (stale kernel incompatible with host ABI)");
+ return -22;
+ }
+ *(unsigned int *)a_host_abi = LINUX64_ABI_VERSION;
+ if (el0_mode) {
+ if (!a_el0 || !a_el0_caps ||
+ (a_el0 & 3) || !va_in_loaded_segs_prot(&img, a_el0, 4, 3) ||
+ (a_el0_caps & 3) || !va_in_loaded_segs_prot(&img, a_el0_caps, 4, 3)) {
+ logs("xnu: _linux64_el0 or _linux64_el0_caps missing or invalid (kernel without EL0 patch?)");
+ return -2;
+ }
+ *(unsigned int *)a_el0 = 1;
+ unsigned int caps = (fki_caps() & FKI_CAP_EXEC_ONLY) ? LINUX64_EL0_CAP_EXEC_ONLY : 0;
+ if (xo_compat)
+ caps |= LINUX64_EL0_CAP_XO_COMPAT;
+ *(unsigned int *)a_el0_caps = caps;
+ }
+ *(u64_t *)a_hook = (u64_t)(el0_mode ? xnu_world_upcall_el0 : xnu_world_upcall);
*(u64_t *)a_slide = img.slide;
diag_va[0] = a_init; diag_va[1] = img.vmlow; diag_va[2] = (u64_t)ba; diag_va[3] = (u64_t)ba->deviceTreeP;
diag_va[4] = macho_sym(&img, "_port_crumb");
+ if (diag_va[4] && ((diag_va[4] & 7) || !va_in_loaded_segs_prot(&img, diag_va[4], 8, 3))) {
+ logs("xnu: ignoring invalid _port_crumb symbol");
+ diag_va[4] = 0;
+ }
diag_va[5] = macho_sym(&img, "_strlen");
- xnu_dbg = (const unsigned long *)macho_sym(&img, "_linux64_dbg");
- xnu_el0_stat = (const unsigned long *)macho_sym(&img, "_linux64_el0_stat");
+ if (diag_va[5] && ((diag_va[5] & 3) || !va_in_loaded_segs_prot(&img, diag_va[5], 4, 5))) {
+ logs("xnu: ignoring invalid _strlen symbol");
+ diag_va[5] = 0;
+ }
+ {
+ u64_t a_dbg = macho_sym(&img, "_linux64_dbg");
+ if (a_dbg && ((a_dbg & 7) || !va_in_loaded_segs_prot(&img, a_dbg, 16 * sizeof(unsigned long), 1))) {
+ logs("xnu: ignoring invalid _linux64_dbg symbol");
+ a_dbg = 0;
+ }
+ xnu_dbg = (const unsigned long *)a_dbg;
+
+ u64_t a_stat = macho_sym(&img, "_linux64_el0_stat");
+ if (a_stat && ((a_stat & 7) ||
+ !va_in_loaded_segs_prot(&img, a_stat,
+ (u64_t)LINUX64_CPU_SLOTS * 2 * LINUX64_EL0_CLASSES * sizeof(unsigned long), 1))) {
+ logs("xnu: ignoring invalid _linux64_el0_stat symbol");
+ a_stat = 0;
+ }
+ xnu_el0_stat = (const unsigned long *)a_stat;
+ }
{ /* 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)
@@ -1195,11 +2117,24 @@ static int enter_arm_init(struct boot_args_v2 *ba)
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)
- logs("xnu: kernel faults on XNU addresses go to XNU's vm_fault");
{
+ u64_t a_kf = macho_sym(&img, "_linux64_kernel_fault");
+ if (a_kf && ((a_kf & 3) || !va_in_loaded_segs_prot(&img, a_kf, 4, 5))) {
+ logs("xnu: ignoring invalid _linux64_kernel_fault symbol");
+ a_kf = 0;
+ }
+ xnu_kfault = (void *)a_kf;
+
+ u64_t a_kfr = macho_sym(&img, "_linux64_kernel_fault_recover");
+ if (a_kfr && ((a_kfr & 3) || !va_in_loaded_segs_prot(&img, a_kfr, 4, 5))) {
+ logs("xnu: ignoring invalid _linux64_kernel_fault_recover symbol");
+ a_kfr = 0;
+ }
+ xnu_kfault_recover = (void *)a_kfr;
+ }
+ if (!el0_mode && xnu_kfault && fki_fault_register(0xffffffe000000000ULL, 0xfffffffc00000000ULL, xnu_fault) == 0)
+ logs("xnu: kernel faults on XNU addresses go to XNU's vm_fault");
+ if (!el0_mode) {
/*
* XNU's user half starts as Linux's TTBR0. Its TCR stays Linux's (T0SZ 16, 4-level): a 4K XNU user pmap's
* hardware root (hw_ttep) is an L0 table whose first entry points at its L1 (ttep), as the walk showed.
@@ -1217,6 +2152,11 @@ static int enter_arm_init(struct boot_args_v2 *ba)
xnu_W.xnu_ttbr0 = ttbr0;
}
a_cpu_entry = macho_sym(&img, "_linux64_cpu_entry");
+ if (a_cpu_entry && ((a_cpu_entry & 3) || !va_in_loaded_segs_prot(&img, a_cpu_entry, 4, 5))) {
+ logs("xnu: ignoring invalid _linux64_cpu_entry symbol: one CPU");
+ a_cpu_entry = 0;
+ cpus = 1;
+ }
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;
@@ -1229,8 +2169,9 @@ static int enter_arm_init(struct boot_args_v2 *ba)
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");
+ stop_state = STOP_ACTIVE_ONE;
in_xnu = 1;
- long r = xnu_world_call(a_init, (unsigned long)ba);
+ long r = el0_mode ? xnu_world_call_el0(a_init, (unsigned long)ba) : 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) */
stop_commit();
@@ -1240,7 +2181,8 @@ static int enter_arm_init(struct boot_args_v2 *ba)
fki_thread_stop(cpu_thread[c]);
cpu_thread[c] = 0;
}
- fki_fault_unregister();
+ if (!el0_mode)
+ fki_fault_unregister();
logkv("xnu: kernel faults forwarded to XNU", kfaults);
fki_thread_stop(monitor);
monitor = 0;
@@ -1311,30 +2253,107 @@ static int run_m2b(void)
logs("xnu: bootstrap window mapped");
unsigned char *base = (unsigned char *)XNU_WINDOW_BASE;
- macho_copy(&img, base + image_off);
+ err = macho_copy(&img, base + image_off);
+ if (err) { logkv("xnu: macho_copy failed, err", (u64_t)err); return err; }
img.slide = 0;
struct boot_args_v2 *ba = build_boot(base, img.region.pa, img.region.size, image_off, image_size);
if (!ba) return -22;
return enter_arm_init(ba);
}
+/* Pure EL0 host M2b: host manages the high window via fki_kmem_alloc; no contiguous multi-GB RAM needed. */
+static int run_m2b_el0(void)
+{
+ u64_t image_size = img.vmhigh - img.vmlow;
+ if (img.vmlow < 0xffffffe000000000ULL) { logs("xnu: unexpected link address"); return -22; }
+ if (ram_mb <= 0 || ram_mb > 65536) { logs("xnu: invalid ram_mb"); return -22; }
+ u64_t image_off = img.vmlow - XNU_WINDOW_BASE;
+ u64_t ram_bytes = (u64_t)ram_mb << 20;
+ u64_t overhead = image_off + image_size + 0x60000 + BOOT_EXTRA;
+ if (overhead < image_off || ram_bytes > (~0ULL) - overhead) { logs("xnu: ram_mb overflow"); return -22; }
+ u64_t want = overhead + ram_bytes;
+ int err = fki_kmem_alloc((unsigned long)want, (unsigned long)XNU_WINDOW_BASE, XNU_FAKE_PHYS, &img.region);
+ if (err) { logkv("xnu: EL0 kmem allocation failed, err", (u64_t)err); return err; }
+ logkv("xnu: EL0 high window base", (u64_t)img.region.va);
+ logkv("xnu: EL0 high window size", img.region.size);
+ logkv("xnu: EL0 synthetic phys base", img.region.pa);
+
+ unsigned char *base = (unsigned char *)XNU_WINDOW_BASE;
+ err = macho_copy(&img, base + image_off);
+ if (err) { logkv("xnu: macho_copy failed, err", (u64_t)err); return err; }
+ img.slide = 0;
+ struct boot_args_v2 *ba = build_boot(base, img.region.pa, img.region.size, image_off, image_size);
+ if (!ba) return -22;
+ return enter_arm_init(ba);
+}
+
+static void xnu_cleanup(void)
+{
+ for (int i = 0; i < LINUX64_CPU_SLOTS; i++) {
+ if (cpu_hot[i].utcb) {
+ fki_utcb_destroy(cpu_hot[i].utcb);
+ cpu_hot[i].utcb = 0;
+ cpu_hot[i].utcb_thread = 0;
+ cpu_hot[i].utcb_fpu_live = 0;
+ cpu_hot[i].utcb_disable_jop = -1;
+ }
+ }
+ if (window_l1) {
+ int last = -1;
+ for (int i = 0; i < 512; i++) if (window_owned[i]) { window_l1[i] = 0; window_owned[i] = 0; last = i; }
+ if (last >= 0) fki_window_set(&window_l1[last], 0);
+ window_l1 = 0;
+ window_slot = 0;
+ }
+ if (mode == 3) {
+ if (el0_mode) {
+ if (img.region.va) fki_kmem_free(&img.region);
+ } else {
+ if (img.region.va) fki_contig_free(&img.region);
+ if (l2page.va) fki_contig_free(&l2page);
+ }
+ } else if (img.region.va) {
+ fki_region_free(&img.region);
+ }
+ img.region.va = 0;
+ img.region.handle = 0;
+ l2page.va = 0;
+ l2page.handle = 0;
+ if (blob) { fki_blob_put(blob); blob = 0; }
+ if (rd_blob) { fki_blob_put(rd_blob); rd_blob = 0; }
+ if (tc_blob) { fki_blob_put(tc_blob); tc_blob = 0; }
+ if (hd_file) { fki_file_close(hd_file); hd_file = 0; }
+ if (ks_file) { fki_file_close(ks_file); ks_file = 0; }
+ if (dk_file) { fki_file_close(dk_file); dk_file = 0; }
+ if (ci_file) { fki_file_close(ci_file); ci_file = 0; }
+ if (in_file) { fki_file_close(in_file); in_file = 0; }
+}
+
static int __init xnu_init(void)
{
const void *data; unsigned long size;
int err;
- if (fki_version() != 0)
+ if (fki_version() != FKI_VERSION)
return -22;
+ if (ram_mb <= 0 || ram_mb > 65536)
+ return -22;
+ el0_mode = !!(fki_caps() & FKI_CAP_EL0);
+ logkv("xnu: FKI caps", fki_caps());
+ if (el0_mode && !(fki_caps() & FKI_CAP_PAC)) {
+ logs("xnu: EL0 mode requires FKI_CAP_PAC");
+ return -95;
+ }
/* every random number XNU takes comes from Linux's generator (the boot seeds, LINUX64_CALL_RANDOM): seeded first */
err = fki_random_wait();
if (err) { logkv("xnu: Linux's random number generator is not seeded, err", (u64_t)err); return err; }
if (ramdisk) {
err = fki_blob_get(ramdisk, &rd_data, &rd_size, &rd_blob);
- if (err) { logkv("xnu: cannot read the RAM disk, err", (u64_t)err); return err; }
+ if (err) { logkv("xnu: cannot read the RAM disk, err", (u64_t)err); goto fail; }
}
if (trustcache) {
err = fki_blob_get(trustcache, &tc_data, &tc_size, &tc_blob);
- if (err) { logkv("xnu: cannot read the trust cache, err", (u64_t)err); return err; }
+ if (err) { logkv("xnu: cannot read the trust cache, err", (u64_t)err); goto fail; }
}
if (console_in) {
fki_u64 sz = 0;
@@ -1355,18 +2374,18 @@ static int __init xnu_init(void)
}
if (disk) {
dk_file = fki_file_open(disk, 1, &dk_size);
- if (!dk_file) { logs("xnu: cannot open the block disk"); return -2; }
+ if (!dk_file) { logs("xnu: cannot open the block disk"); err = -2; goto fail; }
logkv("xnu: block disk bytes", dk_size);
}
if (hostdisk) {
hd_file = fki_file_open(hostdisk, hostdisk_rw, &hd_size);
- if (!hd_file) { logs("xnu: cannot open the host disk"); return -2; }
+ if (!hd_file) { logs("xnu: cannot open the host disk"); err = -2; goto fail; }
logkv("xnu: host disk bytes", hd_size);
}
err = fki_blob_get(image, &data, &size, &blob);
- if (err) { logkv("xnu: cannot read image, err", (u64_t)err); return err; }
+ if (err) { logkv("xnu: cannot read image, err", (u64_t)err); goto fail; }
err = macho_load(&img, data, size, mode == 3 ? ~0UL : mode == 2 ? (unsigned long)ram_mb << 20 : 0);
- if (err) { logkv("xnu: load failed", (u64_t)err); fki_blob_put(blob); blob = 0; return err; }
+ if (err) { logkv("xnu: load failed", (u64_t)err); goto fail; }
logkv("xnu: image vmlow", img.vmlow);
logkv("xnu: image size", img.vmhigh - img.vmlow);
if (mode != 3) {
@@ -1376,29 +2395,22 @@ static int __init xnu_init(void)
fki_random(&xnu_W.xnu_keys, sizeof(xnu_W.xnu_keys));
xnu_W.xnu_keys.sctlr_en = ~0ULL;
+ fki_random(&xnu_user_keys, sizeof(xnu_user_keys));
+ xnu_user_keys.sctlr_en = ~0ULL;
- return mode == 1 ? run_m1() : mode == 3 ? run_m2b() : run_m2a();
+ err = mode == 1 ? run_m1() : mode == 3 ? (el0_mode ? run_m2b_el0() : run_m2b()) : run_m2a();
+ if (err)
+ goto fail;
+ return 0;
+
+fail:
+ xnu_cleanup();
+ return err;
}
static void __exit xnu_exit(void)
{
- if (window_l1) {
- int last = -1;
- for (int i = 0; i < 512; i++) if (window_owned[i]) { window_l1[i] = 0; last = i; }
- if (last >= 0) fki_window_set(&window_l1[last], 0);
- }
- if (mode == 3) {
- if (img.region.va) fki_contig_free(&img.region);
- if (l2page.va) fki_contig_free(&l2page);
- } else if (img.region.va) fki_region_free(&img.region);
- if (blob) fki_blob_put(blob);
- if (rd_blob) fki_blob_put(rd_blob);
- if (tc_blob) fki_blob_put(tc_blob);
- if (hd_file) fki_file_close(hd_file);
- if (ks_file) fki_file_close(ks_file);
- if (dk_file) fki_file_close(dk_file);
- if (ci_file) fki_file_close(ci_file);
- if (in_file) fki_file_close(in_file);
+ xnu_cleanup();
}
module_init(xnu_init);
diff --git a/xnu-patches/0001-linux64-machine-layer.patch b/xnu-patches/0001-linux64-machine-layer.patch
index 0ea0287..4e11f88 100644
--- a/xnu-patches/0001-linux64-machine-layer.patch
+++ b/xnu-patches/0001-linux64-machine-layer.patch
@@ -1,14 +1,4 @@
-The LINUX64 machine layer: XNU hosted inside a Linux kernel by xnu.ko.
-
-The CPU, MMU and exceptions are Linux's: XNU runs at EL1 on Linux's page tables (its kernel L1 entries installed by the
-host), with hardware interrupts masked and a virtual interrupt flag; exceptions are taken in Linux's vectors and handed
-back (kernel faults to linux64_kernel_fault, user space through linux64_el0_run/linux64_el0_exception). Idle, timers,
-the console, printf/kprintf, panics, failed asserts and a halt or restart go to the host; entropy comes from the host
-until corecrypto registers. Every hosted path is behind `if (linux64_hook)`: the same kernel still boots on hardware.
-
-The interface to the host is linux64/linux64_abi.h (shared with xnu.ko) and linux64/linux64.h, copied into
-EXTERNAL_HEADERS/linux64 from xnu-patches/include by scripts/vm-xnu-rebuild.sh.
-
+// SPDX-License-Identifier: APSL-2.0
diff --git a/bsd/dev/arm64/sysctl.c b/bsd/dev/arm64/sysctl.c
index f380ae5..7db22a8 100644
--- a/bsd/dev/arm64/sysctl.c
@@ -22,6 +12,91 @@ index f380ae5..7db22a8 100644
return SYSCTL_OUT(req, &return_value, sizeof(return_value));
}
+diff --git a/bsd/kern/kern_exec.c b/bsd/kern/kern_exec.c
+index 2bf34ab..e49caec 100644
+--- a/bsd/kern/kern_exec.c
++++ b/bsd/kern/kern_exec.c
+@@ -8491,18 +8491,35 @@ execargs_lock_sleep(void)
+ static kern_return_t
+ execargs_purgeable_allocate(char **execarg_address)
+ {
++ extern unsigned int linux64_el0;
+ mach_vm_offset_t addr = 0;
+ kern_return_t kr = mach_vm_allocate_kernel(bsd_pageable_map, &addr,
+ BSD_PAGEABLE_SIZE_PER_EXEC,
+- VM_MAP_KERNEL_FLAGS_ANYWHERE(.vmf_purgeable = true));
++ VM_MAP_KERNEL_FLAGS_ANYWHERE(.vmf_purgeable = !linux64_el0));
++ if (kr == KERN_SUCCESS && linux64_el0) {
++ kr = vm_map_wire_kernel(bsd_pageable_map, addr,
++ addr + BSD_PAGEABLE_SIZE_PER_EXEC,
++ VM_PROT_READ | VM_PROT_WRITE, VM_KERN_MEMORY_BSD, FALSE);
++ if (kr != KERN_SUCCESS) {
++ (void)mach_vm_deallocate_kernel(bsd_pageable_map, addr,
++ BSD_PAGEABLE_SIZE_PER_EXEC);
++ addr = 0;
++ }
++ }
+ *execarg_address = (char *)addr;
+- assert(kr == KERN_SUCCESS);
++ if (!linux64_el0) {
++ assert(kr == KERN_SUCCESS);
++ }
+ return kr;
+ }
+
+ static kern_return_t
+ execargs_purgeable_reference(void *execarg_address)
+ {
++ extern unsigned int linux64_el0;
++ if (linux64_el0) {
++ return KERN_SUCCESS;
++ }
+ int state = VM_PURGABLE_NONVOLATILE;
+ kern_return_t kr = vm_map_purgable_control(bsd_pageable_map,
+ (vm_offset_t) execarg_address, VM_PURGABLE_SET_STATE, &state);
+@@ -8514,6 +8531,10 @@ execargs_purgeable_reference(void *execarg_address)
+ static kern_return_t
+ execargs_purgeable_volatilize(void *execarg_address)
+ {
++ extern unsigned int linux64_el0;
++ if (linux64_el0) {
++ return KERN_SUCCESS;
++ }
+ int state = VM_PURGABLE_VOLATILE | VM_PURGABLE_ORDERING_OBSOLETE;
+ kern_return_t kr;
+ kr = vm_map_purgable_control(bsd_pageable_map,
+@@ -8571,8 +8592,17 @@ execargs_alloc(struct image_params *imgp)
+ kret = execargs_purgeable_reference(imgp->ip_strings);
+ }
+
+- assert(kret == KERN_SUCCESS);
+ if (kret != KERN_SUCCESS) {
++ extern unsigned int linux64_el0;
++ if (!linux64_el0) {
++ assert(kret == KERN_SUCCESS);
++ }
++ execargs_lock_lock();
++ execargs_free_count++;
++ if (execargs_waiters > 0) {
++ execargs_wakeup_waiters();
++ }
++ execargs_lock_unlock();
+ return ENOMEM;
+ }
+
+diff --git a/bsd/kern/mach_loader.c b/bsd/kern/mach_loader.c
+index 6ce6141..8fb290b 100644
+--- a/bsd/kern/mach_loader.c
++++ b/bsd/kern/mach_loader.c
+@@ -801,7 +801,7 @@ load_machfile(
+ #if defined(__arm64__)
+ if (result->is_64bit_addr) {
+ #if !defined(APPLE_ARM64_ARCH_FAMILY) && !__ARM_16K_PG__
+- vm_map_pageshift = FOURK_PAGE_SHIFT;
++ vm_map_pageshift = PAGE_SHIFT; /* LINUX64: the kernel's VM page (16 KB over a 4 KB granule with linux64_vm16k) */
+ #else
+ /* enforce 16KB alignment of VM map entries */
+ vm_map_pageshift = SIXTEENK_PAGE_SHIFT;
diff --git a/config/MASTER.arm64.bcm2837 b/config/MASTER.arm64.bcm2837
index 0c52cc6..87d19c7 100644
--- a/config/MASTER.arm64.bcm2837
@@ -35,954 +110,4849 @@ index 0c52cc6..87d19c7 100644
# FILESYS_RELEASE= [ FILESYS_BASE ]
# FILESYS_DEV = [ FILESYS_BASE fdesc config_union_mounts ]
# FILESYS_DEBUG = [ FILESYS_BASE fdesc config_union_mounts ]
-diff --git a/libkern/crypto/corecrypto_rand.c b/libkern/crypto/corecrypto_rand.c
-index d46815b..acea296 100644
---- a/libkern/crypto/corecrypto_rand.c
-+++ b/libkern/crypto/corecrypto_rand.c
-@@ -27,9 +27,19 @@
- */
+diff --git a/iokit/IOKit/IOMemoryDescriptor.h b/iokit/IOKit/IOMemoryDescriptor.h
+index 86696b7..86aeda2 100644
+--- a/iokit/IOKit/IOMemoryDescriptor.h
++++ b/iokit/IOKit/IOMemoryDescriptor.h
+@@ -287,6 +287,10 @@ class IOMemoryDescriptor : public OSObject
+ {
+ friend class IOMemoryMap;
+ friend class IOMultiMemoryDescriptor;
++#ifdef XNU_KERNEL_PRIVATE
++ friend IOReturn el0IOMemoryDescriptorRedirectList(
++ IOMemoryDescriptor **descs, uint32_t count, task_t safeTask, bool doRedirect);
++#endif
- #include <libkern/crypto/crypto_internal.h>
-+#include <linux64/linux64.h>
- #include <corecrypto/ccrng.h>
-+#include <string.h>
- #include <libkern/crypto/rand.h>
+ OSDeclareDefaultStructorsWithDispatch(IOMemoryDescriptor);
-+/*
-+ * LINUX64 (xnulinux): until the corecrypto kext registers g_crypto_funcs (and on a hosted kernel without it), random
-+ * bytes come from the host's generator (Linux's get_random_bytes, LINUX64_CALL_RANDOM). A context made before then
-+ * holds nothing (linux64_rng_ctx_size).
-+ */
-+#define linux64_rng_fallback() (g_crypto_funcs == NULL && linux64_hook != 0)
-+#define linux64_rng_ctx_size (2 * sizeof(uint64_t))
-+
- int
- cc_rand_generate(void *out, size_t outlen)
+@@ -1103,6 +1107,17 @@ enum {
+ class IOGeneralMemoryDescriptor : public IOMemoryDescriptor
{
-@@ -41,6 +51,9 @@ cc_rand_generate(void *out, size_t outlen)
- if (rng_state != NULL) {
- error = ccrng_generate(rng_state, outlen, out);
- }
-+ } else if (linux64_rng_fallback()) {
-+ linux64_random(out, outlen);
-+ error = 0;
- }
+ OSDeclareDefaultStructors(IOGeneralMemoryDescriptor);
++#ifdef XNU_KERNEL_PRIVATE
++ friend IOReturn el0CollectOverwriteChunks(
++ IOMemoryDescriptor *desc, vm_map_t map, IOMemoryMap *mapping,
++ IOOptionBits options, mach_vm_size_t offset, mach_vm_size_t length,
++ mach_vm_address_t baseAddr, mach_vm_size_t allowedMapSize,
++ mach_vm_address_t *curLogicalAddrIO,
++ struct linux64_el0_mem_entry_chunk **chunksIO, size_t *nchunksIO,
++ size_t *capIO, mach_vm_size_t *totalMapSizeIO,
++ struct linux64_el0_pending_pager **pagersIO, size_t *npagersIO,
++ size_t *pagerCapIO);
++#endif
- return error;
-@@ -58,6 +71,10 @@ crypto_random_generate(
- void *random,
- size_t random_size)
+ public:
+ union Ranges {
+diff --git a/iokit/IOKit/IOMultiMemoryDescriptor.h b/iokit/IOKit/IOMultiMemoryDescriptor.h
+index 1912f95..466cd96 100644
+--- a/iokit/IOKit/IOMultiMemoryDescriptor.h
++++ b/iokit/IOKit/IOMultiMemoryDescriptor.h
+@@ -44,6 +44,17 @@
+ class IOMultiMemoryDescriptor : public IOMemoryDescriptor
{
-+ if (linux64_rng_fallback()) {
-+ linux64_random(random, random_size);
-+ return;
-+ }
- g_crypto_funcs->random_generate_fn(ctx, random, random_size);
- }
+ OSDeclareDefaultStructors(IOMultiMemoryDescriptor);
++#ifdef XNU_KERNEL_PRIVATE
++ friend IOReturn el0CollectOverwriteChunks(
++ IOMemoryDescriptor *desc, vm_map_t map, IOMemoryMap *mapping,
++ IOOptionBits options, mach_vm_size_t offset, mach_vm_size_t length,
++ mach_vm_address_t baseAddr, mach_vm_size_t allowedMapSize,
++ mach_vm_address_t *curLogicalAddrIO,
++ struct linux64_el0_mem_entry_chunk **chunksIO, size_t *nchunksIO,
++ size_t *capIO, mach_vm_size_t *totalMapSizeIO,
++ struct linux64_el0_pending_pager **pagersIO, size_t *npagersIO,
++ size_t *pagerCapIO);
++#endif
-@@ -67,12 +84,19 @@ crypto_random_uniform(
- uint64_t bound,
- uint64_t *random)
+ protected:
+
+diff --git a/iokit/IOKit/IOSubMemoryDescriptor.h b/iokit/IOKit/IOSubMemoryDescriptor.h
+index 48e5ccf..ed731ce 100644
+--- a/iokit/IOKit/IOSubMemoryDescriptor.h
++++ b/iokit/IOKit/IOSubMemoryDescriptor.h
+@@ -39,6 +39,17 @@
+ class IOSubMemoryDescriptor : public IOMemoryDescriptor
{
-+ if (linux64_rng_fallback()) {
-+ *random = linux64_random_uniform(bound);
-+ return;
+ OSDeclareDefaultStructors(IOSubMemoryDescriptor);
++#ifdef XNU_KERNEL_PRIVATE
++ friend IOReturn el0CollectOverwriteChunks(
++ IOMemoryDescriptor *desc, vm_map_t map, IOMemoryMap *mapping,
++ IOOptionBits options, mach_vm_size_t offset, mach_vm_size_t length,
++ mach_vm_address_t baseAddr, mach_vm_size_t allowedMapSize,
++ mach_vm_address_t *curLogicalAddrIO,
++ struct linux64_el0_mem_entry_chunk **chunksIO, size_t *nchunksIO,
++ size_t *capIO, mach_vm_size_t *totalMapSizeIO,
++ struct linux64_el0_pending_pager **pagersIO, size_t *npagersIO,
++ size_t *pagerCapIO);
++#endif
+
+ protected:
+ IOMemoryDescriptor * _parent;
+diff --git a/iokit/Kernel/IOKitKernelInternal.h b/iokit/Kernel/IOKitKernelInternal.h
+index b33a663..899235b 100644
+--- a/iokit/Kernel/IOKitKernelInternal.h
++++ b/iokit/Kernel/IOKitKernelInternal.h
+@@ -62,6 +62,58 @@ struct IOMemoryDescriptorMapAllocRef {
+ kern_return_t
+ IOMemoryDescriptorMapAlloc(vm_map_t map, void * ref);
+
++struct linux64_el0_mem_entry_chunk {
++ ipc_port_t port;
++ vm_object_offset_t offset;
++ vm_map_size_t size;
++ vm_map_size_t map_size;
++ vm_prot_t prot;
++ vm_tag_t tag;
++ bool return_data_addr;
++ bool check_data_addr;
++ vm_map_address_t expected_data_addr;
++ vm_prot_t cache_perm;
++ vm_map_address_t data_addr_out;
++};
++
++#ifdef __cplusplus
++extern "C" {
++#endif
++extern unsigned int linux64_el0;
++extern bool linux64_el0_is_kernel_pmap(vm_map_t map);
++extern kern_return_t linux64_el0_map_mem_entries_overwrite(
++ vm_map_t target_map, vm_map_address_t base_addr, vm_map_size_t total_map_size,
++ struct linux64_el0_mem_entry_chunk *chunks, size_t nchunks,
++ vm_prot_t prot, vm_tag_t tag, bool iokit_acct, bool mte_aware);
++#ifdef __cplusplus
++}
++extern "C++" {
++class IOMemoryDescriptor;
++class IOMemoryMap;
++struct linux64_el0_pending_pager {
++ IOMemoryDescriptor *md;
++ memory_object_t pager;
++ mach_vm_size_t offset;
++ mach_vm_size_t length;
++ bool pager_contig;
++ IOOptionBits md_flags;
++};
++IOReturn el0CollectOverwriteChunks(
++ IOMemoryDescriptor *desc, vm_map_t map, IOMemoryMap *mapping,
++ IOOptionBits options, mach_vm_size_t offset, mach_vm_size_t length,
++ mach_vm_address_t baseAddr, mach_vm_size_t allowedMapSize,
++ mach_vm_address_t *curLogicalAddrIO,
++ struct linux64_el0_mem_entry_chunk **chunksIO, size_t *nchunksIO,
++ size_t *capIO, mach_vm_size_t *totalMapSizeIO,
++ struct linux64_el0_pending_pager **pagersIO, size_t *npagersIO,
++ size_t *pagerCapIO);
++IOReturn el0PopulatePendingPagers(
++ const struct linux64_el0_pending_pager *pagers, size_t npagers);
++extern IOReturn el0IOMemoryDescriptorRedirectList(
++ IOMemoryDescriptor **descs, uint32_t count, task_t safeTask, bool doRedirect);
++}
++#endif
++
+
+ mach_vm_address_t
+ IOKernelAllocateWithPhysicalRestrict(
+diff --git a/iokit/Kernel/IOLib.cpp b/iokit/Kernel/IOLib.cpp
+index ff22ba5..e2763c9 100644
+--- a/iokit/Kernel/IOLib.cpp
++++ b/iokit/Kernel/IOLib.cpp
+@@ -1412,14 +1412,67 @@ IOSetProcessorCacheMode( task_t task, IOVirtualAddress address,
+ // make map mode
+ cacheMode = (cacheMode << kIOMapCacheShift) & kIOMapCacheMask;
+
++ extern unsigned int linux64_el0;
++ extern bool linux64_el0_is_kernel_pmap(vm_map_t map);
++ extern kern_return_t vm_map_el0_set_cache_mode(
++ vm_map_t map, mach_vm_address_t va, unsigned int wimg_flags, bool use_default);
++
++ vm_map_t task_map = get_task_map(task);
++ bool el0_kmap = linux64_el0 && linux64_el0_is_kernel_pmap(task_map);
++ unsigned int wimg_flags = 0;
++ bool use_default = false;
++ if (el0_kmap) {
++ switch (cacheMode & kIOMapCacheMask) {
++ case kIOMapDefaultCache:
++ default:
++ use_default = true;
++ break;
++ case kIOMapInhibitCache:
++ wimg_flags = VM_WIMG_IO;
++ break;
++ case kIOMapWriteThruCache:
++ wimg_flags = VM_WIMG_WTHRU;
++ break;
++ case kIOMapWriteCombineCache:
++ wimg_flags = VM_WIMG_WCOMB;
++ break;
++ case kIOMapCopybackCache:
++ wimg_flags = VM_WIMG_COPYBACK;
++ break;
++ case kIOMapCopybackInnerCache:
++ wimg_flags = VM_WIMG_INNERWBACK;
++ break;
++ case kIOMapPostedWrite:
++ wimg_flags = VM_WIMG_POSTED;
++ break;
++ case kIOMapRealTimeCache:
++ wimg_flags = VM_WIMG_RT;
++ break;
++ }
+ }
- g_crypto_funcs->random_uniform_fn(ctx, bound, random);
++
+ while ((kIOReturnSuccess == ret) && (length > 0)) {
+- // Get the physical page number
+- pagenum = pmap_find_phys(kernel_pmap, (addr64_t)address);
+- if (pagenum) {
+- ret = IOUnmapPages( get_task_map(task), address, page_size );
+- ret = IOMapPages( get_task_map(task), address, ptoa_64(pagenum), page_size, cacheMode );
++ if (el0_kmap) {
++ kern_return_t kr = vm_map_el0_set_cache_mode(task_map, address, wimg_flags, use_default);
++ if (kr != KERN_SUCCESS) {
++ if (kr == KERN_NOT_SUPPORTED) {
++ ret = kIOReturnUnsupported;
++ } else if (kr == KERN_INVALID_ARGUMENT) {
++ ret = kIOReturnBadArgument;
++ } else {
++ ret = kIOReturnVMError;
++ }
++ break;
++ }
+ } else {
+- ret = kIOReturnVMError;
++ // Get the physical page number
++ pagenum = pmap_find_phys(kernel_pmap, (addr64_t)address);
++ if (pagenum) {
++ ret = IOUnmapPages( task_map, address, page_size );
++ ret = IOMapPages( task_map, address, ptoa_64(pagenum), page_size, cacheMode );
++ } else {
++ ret = kIOReturnVMError;
++ }
+ }
+
+ address += page_size;
+diff --git a/iokit/Kernel/IOMemoryDescriptor.cpp b/iokit/Kernel/IOMemoryDescriptor.cpp
+index cc2c1af..64537a0 100644
+--- a/iokit/Kernel/IOMemoryDescriptor.cpp
++++ b/iokit/Kernel/IOMemoryDescriptor.cpp
+@@ -965,6 +965,12 @@ IOMemoryDescriptorMapAlloc(vm_map_t map, void * _ref)
+ return err;
}
- size_t
- crypto_random_kmem_ctx_size(void)
- {
-+ if (linux64_rng_fallback()) {
-+ return linux64_rng_ctx_size;
++extern "C" bool pmap_el0_kmap_range_supported(vm_map_address_t va, addr64_t pa, vm_map_size_t size);
++extern "C" kern_return_t linux64_el0_prefault_kernel_map(
++ vm_map_t map, mach_vm_offset_t addr, mach_vm_size_t size, vm_prot_t prot);
++extern "C" void linux64_el0_release_autowire_range(
++ vm_map_t map, mach_vm_address_t addr, mach_vm_size_t len);
++
+ IOReturn
+ IOGeneralMemoryDescriptor::memoryReferenceMap(
+ IOMemoryReference * ref,
+@@ -984,7 +990,7 @@ IOGeneralMemoryDescriptor::memoryReferenceMap(
+ mach_vm_size_t nextLen;
+ IOByteCount physLen;
+ IOMemoryEntry * entry;
+- vm_prot_t prot, memEntryCacheMode;
++ vm_prot_t prot, memEntryCacheMode = 0;
+ IOOptionBits type;
+ IOOptionBits cacheMode;
+ vm_tag_t tag;
+@@ -1179,6 +1185,76 @@ IOGeneralMemoryDescriptor::memoryReferenceMap(
+ mapAddr = addr;
+ addr += pageOffset;
+
++ if (linux64_el0 && linux64_el0_is_kernel_pmap(map) && (options & kIOMapOverwrite) &&
++ (KERN_SUCCESS == err) && remain) {
++ struct linux64_el0_mem_entry_chunk stackChunks[16];
++ struct linux64_el0_mem_entry_chunk *chunks = stackChunks;
++ size_t maxChunks = ref->count;
++ if (maxChunks > 16) {
++ chunks = IONew(struct linux64_el0_mem_entry_chunk, maxChunks);
++ if (!chunks) {
++ return kIOReturnNoMemory;
++ }
++ }
++ size_t nchunks = 0;
++ mach_vm_size_t preRemain = remain;
++ mach_vm_size_t preOffset = offset;
++ mach_vm_size_t prePageOffset = pageOffset;
++ typeof(entry) preEntry = entry;
++ typeof(entryIdx) preIdx = entryIdx;
++ while (preRemain) {
++ if (preIdx >= ref->count) {
++ err = kIOReturnOverrun;
++ break;
++ }
++ mach_vm_size_t preEntryOffset = preOffset - preEntry->offset;
++ if ((IOMin(vm_map_page_mask(map), page_mask) & preEntryOffset) != prePageOffset) {
++ err = kIOReturnNotAligned;
++ break;
++ }
++ preEntryOffset -= prePageOffset;
++ if (preEntryOffset >= preEntry->size) {
++ err = kIOReturnBadArgument;
++ break;
++ }
++ mach_vm_size_t preChunk = preEntry->size - preEntryOffset;
++ if (preChunk) {
++ if (preChunk > preRemain) {
++ preChunk = preRemain;
++ }
++ chunks[nchunks].port = preEntry->entry;
++ chunks[nchunks].offset = preEntryOffset;
++ chunks[nchunks].size = preChunk;
++ chunks[nchunks].map_size = vm_map_round_page(preChunk, vm_map_page_mask(map));
++ chunks[nchunks].prot = prot;
++ chunks[nchunks].tag = tag;
++ chunks[nchunks].return_data_addr = false;
++ chunks[nchunks].check_data_addr = false;
++ chunks[nchunks].expected_data_addr = 0;
++ chunks[nchunks].cache_perm = memEntryCacheMode;
++ chunks[nchunks].data_addr_out = 0;
++ nchunks++;
++ preRemain -= preChunk;
++ if (!preRemain) {
++ break;
++ }
++ preOffset += preChunk - prePageOffset;
++ }
++ prePageOffset = 0;
++ preEntry++;
++ preIdx++;
++ }
++ if (KERN_SUCCESS == err) {
++ err = linux64_el0_map_mem_entries_overwrite(map, mapAddr,
++ vm_map_round_page(size, vm_map_page_mask(map)),
++ chunks, nchunks, prot, tag, true, false);
++ }
++ if (chunks != stackChunks) {
++ IODelete(chunks, struct linux64_el0_mem_entry_chunk, maxChunks);
++ }
++ remain = 0;
+ }
- return g_crypto_funcs->random_kmem_ctx_size_fn();
- }
++
+ while (remain && (KERN_SUCCESS == err)) {
+ entryOffset = offset - entry->offset;
+ if ((IOMin(vm_map_page_mask(map), page_mask) & entryOffset) != pageOffset) {
+@@ -1292,7 +1368,7 @@ IOGeneralMemoryDescriptor::memoryReferenceMapNew(
+ vm_map_offset_t entryOffset, remain, chunk;
+
+ IOMemoryEntry * entry;
+- vm_prot_t prot, memEntryCacheMode;
++ vm_prot_t prot, memEntryCacheMode = 0;
+ IOOptionBits type;
+ IOOptionBits cacheMode;
+ vm_tag_t tag;
+@@ -1347,12 +1423,18 @@ IOGeneralMemoryDescriptor::memoryReferenceMapNew(
+ entryIdx = firstEntryIdx;
+ entry = &ref->entries[entryIdx];
+
++ const bool el0Overwrite = linux64_el0 && linux64_el0_is_kernel_pmap(map) && (options & kIOMapOverwrite);
++ err = KERN_SUCCESS;
+ remain = size;
+ int64_t iteroffset = offset;
+ uint64_t mapSize = 0;
+ while (remain) {
+ entryOffset = iteroffset - entry->offset;
+ if (entryOffset >= entry->size) {
++ if (el0Overwrite) {
++ err = kIOReturnBadArgument;
++ break;
++ }
+ panic("entryOffset");
+ }
-@@ -80,5 +104,9 @@ void
- crypto_random_kmem_init(
- crypto_random_ctx_t ctx)
- {
-+ if (linux64_rng_fallback()) {
-+ memset(ctx, 0, linux64_rng_ctx_size);
-+ return;
+@@ -1368,7 +1450,13 @@ IOGeneralMemoryDescriptor::memoryReferenceMapNew(
+ }
+ mach_vm_size_t entrySize;
+ err = mach_memory_entry_map_size(entry->entry, map, entryOffset, chunk, &entrySize);
+- assert(KERN_SUCCESS == err);
++ if (el0Overwrite) {
++ if (KERN_SUCCESS != err) {
++ break;
++ }
++ } else {
++ assert(KERN_SUCCESS == err);
++ }
+ mapSize += entrySize;
+
+ remain -= chunk;
+@@ -1380,17 +1468,20 @@ IOGeneralMemoryDescriptor::memoryReferenceMapNew(
+ entry++;
+ entryIdx++;
+ if (entryIdx >= ref->count) {
+- panic("overrun");
++ if (!el0Overwrite) {
++ panic("overrun");
++ }
+ err = kIOReturnOverrun;
+ break;
+ }
+ }
+
+ if (kIOMapOverwrite & options) {
+- if ((map == kernel_map) && (kIOMemoryBufferPageable & _flags)) {
+- map = IOPageableMapForAddress(addr);
++ if (KERN_SUCCESS == err) {
++ if ((map == kernel_map) && (kIOMemoryBufferPageable & _flags)) {
++ map = IOPageableMapForAddress(addr);
++ }
+ }
+- err = KERN_SUCCESS;
+ } else {
+ IOMemoryDescriptorMapAllocRef ref;
+ ref.map = map;
+@@ -1491,6 +1582,77 @@ IOGeneralMemoryDescriptor::memoryReferenceMapNew(
+ entryIdx = firstEntryIdx;
+ entry = &ref->entries[entryIdx];
+
++ if (linux64_el0 && linux64_el0_is_kernel_pmap(map) && (options & kIOMapOverwrite) &&
++ (KERN_SUCCESS == err) && remain) {
++ struct linux64_el0_mem_entry_chunk stackChunks[16];
++ struct linux64_el0_mem_entry_chunk *chunks = stackChunks;
++ size_t maxChunks = ref->count;
++ if (maxChunks > 16) {
++ chunks = IONew(struct linux64_el0_mem_entry_chunk, maxChunks);
++ if (!chunks) {
++ return kIOReturnNoMemory;
++ }
++ }
++ size_t nchunks = 0;
++ mach_vm_size_t preRemain = remain;
++ mach_vm_size_t preOffset = offset;
++ typeof(entry) preEntry = entry;
++ typeof(entryIdx) preIdx = entryIdx;
++ while (preRemain) {
++ if (preIdx >= ref->count) {
++ err = kIOReturnOverrun;
++ break;
++ }
++ mach_vm_size_t preEntryOffset = preOffset - preEntry->offset;
++ if (preEntryOffset >= preEntry->size) {
++ err = kIOReturnBadArgument;
++ break;
++ }
++ mach_vm_size_t preChunk = preEntry->size - preEntryOffset;
++ if (preChunk) {
++ if (preChunk > preRemain) {
++ preChunk = preRemain;
++ }
++ mach_vm_size_t entrySize = 0;
++ err = mach_memory_entry_map_size(preEntry->entry, map, preEntryOffset, preChunk, &entrySize);
++ if (KERN_SUCCESS != err) {
++ break;
++ }
++ chunks[nchunks].port = preEntry->entry;
++ chunks[nchunks].offset = preEntryOffset;
++ chunks[nchunks].size = preChunk;
++ chunks[nchunks].map_size = entrySize;
++ chunks[nchunks].prot = prot;
++ chunks[nchunks].tag = tag;
++ chunks[nchunks].return_data_addr = true;
++ chunks[nchunks].check_data_addr = false;
++ chunks[nchunks].expected_data_addr = 0;
++ chunks[nchunks].cache_perm = memEntryCacheMode;
++ chunks[nchunks].data_addr_out = 0;
++ nchunks++;
++ preRemain -= preChunk;
++ if (!preRemain) {
++ break;
++ }
++ preOffset += preChunk;
++ }
++ preEntry++;
++ preIdx++;
++ }
++ if (KERN_SUCCESS == err) {
++ mach_vm_address_t baseMapAddr = vm_map_trunc_page(mapAddr, vm_map_page_mask(map));
++ err = linux64_el0_map_mem_entries_overwrite(map, baseMapAddr, mapSize,
++ chunks, nchunks, prot, tag, true, true);
++ if (KERN_SUCCESS == err && nchunks > 0) {
++ addr = chunks[0].data_addr_out;
++ }
++ }
++ if (chunks != stackChunks) {
++ IODelete(chunks, struct linux64_el0_mem_entry_chunk, maxChunks);
++ }
++ remain = 0;
+ }
- g_crypto_funcs->random_kmem_init_fn(ctx);
++
+ while (remain && (KERN_SUCCESS == err)) {
+ #if LOGUNALIGN
+ printf("offset %qx, %qx\n", offset, entry->offset);
+@@ -5254,6 +5416,16 @@ IOGeneralMemoryDescriptor::makeMapping(
+ return mapping;
}
-diff --git a/osfmk/arm/arm_init.c b/osfmk/arm/arm_init.c
-index ac1713e..8486021 100644
---- a/osfmk/arm/arm_init.c
-+++ b/osfmk/arm/arm_init.c
-@@ -1,4 +1,5 @@
- #include <kern/boot_progress.h>
-+#include <linux64/linux64.h>
- /*
- * Copyright (c) 2007-2024 Apple Inc. All rights reserved.
- *
-@@ -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[LINUX64_CPU_SLOTS];
-+unsigned int linux64_ipi_pending[LINUX64_CPU_SLOTS];
-+unsigned long linux64_dbg[LINUX64_NCOUNTERS];
++static IOReturn el0PreflightDevicePager(
++ IOMemoryDescriptor *md, vm_map_t addressMap, mach_vm_address_t address,
++ mach_vm_size_t sourceOffset, mach_vm_size_t length,
++ IOOptionBits options, bool pagerContig, IOOptionBits mdFlags);
++static IOReturn populateDevicePagerObject(
++ IOMemoryDescriptor *md, void *_pager, mach_vm_size_t sourceOffset,
++ mach_vm_size_t length, bool pagerContig, IOOptionBits mdFlags,
++ vm_map_t nativeFaultMap, mach_vm_address_t nativeFaultAddr,
++ IOOptionBits nativeFaultOpts);
+
- static void
- 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;
-+ if (linux64_hook) {
-+ /* LINUX64: xnu.ko loaded, slid (load commands too) and signed the image already. */
-+ slide = linux64_slide;
-+ }
+ IOReturn
+ IOGeneralMemoryDescriptor::doMap(
+ vm_map_t __addressMap,
+@@ -5270,7 +5442,7 @@ IOGeneralMemoryDescriptor::doMap(
+ }
+ #endif /* !__LP64__ */
- /* rebase and sign jops */
- static_kernelcache = &__thread_starts_sect_end[0] != &__thread_starts_sect_start[0];
-- if (static_kernelcache) {
-+ if (static_kernelcache && !linux64_hook) {
- 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 +353,28 @@ arm_auxkc_init(void *mh, void *base)
- #endif /* defined(HAS_APPLE_PAC) */
+- kern_return_t err;
++ kern_return_t err = kIOReturnSuccess;
+
+ IOMemoryMap * mapping = (IOMemoryMap *) *__address;
+ mach_vm_size_t offset = mapping->fOffset + __offset;
+@@ -5336,37 +5508,63 @@ IOGeneralMemoryDescriptor::doMap(
+ upl_control_flags_t flags;
+ unsigned int lock_count;
+
++ if (NULL == mapping->fRedirUPL) {
++ err = kIOReturnNotReadable;
++ DEBUG4K_ERROR("map %p err 0x%x\n", __addressMap, err);
++ break;
++ }
+ if (!_memRef || (1 != _memRef->count)) {
+ err = kIOReturnNotReadable;
+ DEBUG4K_ERROR("map %p err 0x%x\n", __addressMap, err);
+ break;
+ }
++ if (pager) {
++ if (linux64_el0) {
++ err = el0PreflightDevicePager(this, mapping->fAddressMap, mapping->fAddress,
++ offset, length, options, reserved->dp.pagerContig, _flags);
++ if (kIOReturnSuccess != err) {
++ break;
++ }
++ }
++ err = populateDevicePagerObject(this, pager, offset, length,
++ reserved->dp.pagerContig, _flags, VM_MAP_NULL, 0, 0);
++ if (kIOReturnSuccess != err) {
++ break;
++ }
++ }
+
+ size = (upl_size_t) round_page(mapping->fLength);
+ flags = UPL_COPYOUT_FROM | UPL_SET_INTERNAL
+ | UPL_SET_LITE | UPL_SET_IO_WIRE | UPL_BLOCK_ACCESS;
+
+- if (KERN_SUCCESS != memory_object_iopl_request(_memRef->entries[0].entry, 0, &size, &redirUPL2,
++ kern_return_t uplErr = memory_object_iopl_request(_memRef->entries[0].entry, 0, &size, &redirUPL2,
+ NULL, NULL,
+- &flags, (vm_tag_t) getVMTag(kernel_map))) {
++ &flags, (vm_tag_t) getVMTag(kernel_map));
++ if (KERN_SUCCESS != uplErr) {
+ redirUPL2 = NULL;
++ err = uplErr;
+ }
+
+- for (lock_count = 0;
+- IORecursiveLockHaveLock(gIOMemoryLock);
+- lock_count++) {
+- UNLOCK;
+- }
+- err = upl_transpose(redirUPL2, mapping->fRedirUPL);
+- for (;
+- lock_count;
+- lock_count--) {
+- LOCK;
+- }
++ if (NULL == redirUPL2 || NULL == mapping->fRedirUPL) {
++ if (kIOReturnSuccess == err) {
++ err = kIOReturnError;
++ }
++ } else {
++ for (lock_count = 0;
++ IORecursiveLockHaveLock(gIOMemoryLock);
++ lock_count++) {
++ UNLOCK;
++ }
++ err = upl_transpose(redirUPL2, mapping->fRedirUPL);
++ for (;
++ lock_count;
++ lock_count--) {
++ LOCK;
++ }
+
+- if (kIOReturnSuccess != err) {
+- IOLog("upl_transpose(%x)\n", err);
+- err = kIOReturnSuccess;
++ if (kIOReturnSuccess != err) {
++ IOLog("upl_transpose(%x)\n", err);
++ }
+ }
+
+ if (redirUPL2) {
+@@ -5374,30 +5572,51 @@ IOGeneralMemoryDescriptor::doMap(
+ upl_deallocate(redirUPL2);
+ redirUPL2 = NULL;
+ }
+- {
++ if (kIOReturnSuccess == err) {
+ // swap the memEntries since they now refer to different vm_objects
+ IOMemoryReference * me = _memRef;
+ _memRef = mapping->fMemory->_memRef;
+ mapping->fMemory->_memRef = me;
+ }
+- if (pager) {
+- err = populateDevicePager( pager, mapping->fAddressMap, mapping->fAddress, offset, length, options );
+- }
+ }while (false);
+ }
+ // upl_transpose> //
+ else {
+- err = memoryReferenceMap(_memRef, mapping->fAddressMap, offset, length, options, &mapping->fAddress);
++ bool el0_kmap_pager = linux64_el0 && pager && linux64_el0_is_kernel_pmap(mapping->fAddressMap);
++ bool el0_prepopulated = false;
++ err = KERN_SUCCESS;
++ if (linux64_el0 && pager) {
++ err = el0PreflightDevicePager(this, mapping->fAddressMap, mapping->fAddress,
++ offset, length, options, reserved->dp.pagerContig, _flags);
++ if (el0_kmap_pager && (err == KERN_SUCCESS) && !(kIOMemoryRedirected & _flags)) {
++ err = populateDevicePagerObject(this, pager, offset, length,
++ reserved->dp.pagerContig, _flags, VM_MAP_NULL, 0, 0);
++ if (err == KERN_SUCCESS) {
++ el0_prepopulated = true;
++ }
++ }
++ }
++ if (err == KERN_SUCCESS) {
++ err = memoryReferenceMap(_memRef, mapping->fAddressMap, offset, length, options, &mapping->fAddress);
++ }
+ if (err) {
+ DEBUG4K_ERROR("map %p err 0x%x\n", mapping->fAddressMap, err);
+ }
+ if ((err == KERN_SUCCESS) && pager) {
+- err = populateDevicePager(pager, mapping->fAddressMap, mapping->fAddress, offset, length, options);
++ if (el0_prepopulated) {
++ if (kIOMapDefaultCache == (options & kIOMapCacheMask)) {
++ mapping->fOptions |= ((_flags & kIOMemoryBufferCacheMask) >> kIOMemoryBufferCacheShift);
++ }
++ } else {
++ err = populateDevicePager(pager, mapping->fAddressMap, mapping->fAddress, offset, length, options);
+
+- if (err != KERN_SUCCESS) {
+- doUnmap(mapping->fAddressMap, (IOVirtualAddress) mapping, 0);
+- } else if (kIOMapDefaultCache == (options & kIOMapCacheMask)) {
+- mapping->fOptions |= ((_flags & kIOMemoryBufferCacheMask) >> kIOMemoryBufferCacheShift);
++ if (err != KERN_SUCCESS) {
++ if (!(kIOMapOverwrite & mapping->fOptions)) {
++ doUnmap(mapping->fAddressMap, (IOVirtualAddress) mapping, 0);
++ }
++ } else if (kIOMapDefaultCache == (options & kIOMapCacheMask)) {
++ mapping->fOptions |= ((_flags & kIOMemoryBufferCacheMask) >> kIOMemoryBufferCacheShift);
++ }
+ }
+ }
+ }
+@@ -5553,14 +5772,104 @@ IOMemoryDescriptor::handleFault(
+ return kIOReturnSuccess;
}
-+/*
-+ * 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)
+-IOReturn
+-IOMemoryDescriptor::populateDevicePager(
+- void * _pager,
++static IOReturn
++el0PreflightDevicePager(
++ IOMemoryDescriptor *md,
+ vm_map_t addressMap,
+ mach_vm_address_t address,
+ mach_vm_size_t sourceOffset,
+ mach_vm_size_t length,
+- IOOptionBits options )
++ IOOptionBits options,
++ bool pagerContig,
++ IOOptionBits mdFlags)
+{
-+ arm_init_cpu(cpu_data_ptr, 0);
-+ __builtin_unreachable();
-+}
++ if (!linux64_el0 || length == 0) {
++ return KERN_SUCCESS;
++ }
++ (void)mdFlags;
++ const bool isKernelPmap = linux64_el0_is_kernel_pmap(addressMap);
+
-+/* 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)
-+{
-+ struct linux64_assert_info a = { file, line, expr };
-+ linux64_call(LINUX64_CALL_ASSERT, &a);
-+}
++ IOPhysicalLength segLen = 0;
++ addr64_t physAddr = md->getPhysicalSegment(sourceOffset, &segLen, kIOMemoryMapperNone);
++ if (!physAddr && !segLen) {
++ return kIOReturnBadArgument;
++ }
+
- /*
- * Routine: arm_init
- * Function: Runs on the boot CPU, once, on entry from iBoot.
-@@ -431,6 +465,17 @@ arm_init(
- /* Native non-Apple 4K builds expose the hardware page size at any RAM size. */
- #if !defined(APPLE_ARM64_ARCH_FAMILY) && !__ARM_16K_PG__
- PAGE_SHIFT_CONST = ARM_PGSHIFT;
-+ /*
-+ * LINUX64 (xnulinux): hosted, the host's 4 KB translation granule is the hardware page; boot-arg linux64_vm16k=1
-+ * makes the kernel's VM page 16 KB over it (PAGE_RATIO 4, as Apple's 4 KB-granule SoCs run with more than 1 GB):
-+ * a quarter of the page faults, and the page size macOS binaries are built for.
-+ */
-+ {
-+ uint32_t vm16k = 0;
-+ if (linux64_hook && PE_parse_boot_argn("linux64_vm16k", &vm16k, sizeof(vm16k)) && vm16k) {
-+ PAGE_SHIFT_CONST = PAGE_MAX_SHIFT;
++ mach_vm_size_t pageOffset = physAddr - trunc_page_64(physAddr);
++ if (!pagerContig) {
++ if (md->_memRef && md->_memRef->count == 1) {
++ mach_vm_size_t entryOffset = sourceOffset - md->_memRef->entries[0].offset;
++ if ((IOMin(vm_map_page_mask(addressMap), (mach_vm_size_t)PAGE_MASK) & entryOffset) != pageOffset ||
++ ((entryOffset - pageOffset) & PAGE_MASK) != 0) {
++ return kIOReturnNotAligned;
+ }
++ entryOffset -= pageOffset;
++ if (entryOffset >= md->_memRef->entries[0].size) {
++ return kIOReturnBadArgument;
++ }
++ } else if (sourceOffset != trunc_page_64(sourceOffset)) {
++ return kIOReturnNotAligned;
+ }
- #else
- /*
- * Select the advertised kernel page size.
-diff --git a/osfmk/arm/cpu_data.h b/osfmk/arm/cpu_data.h
-index 743117b..753d128 100644
---- a/osfmk/arm/cpu_data.h
-+++ b/osfmk/arm/cpu_data.h
-@@ -61,8 +61,9 @@ current_thread_fast(void)
- *
- * and ignores the "attribute const", so do it the "dumb" way.
- */
-+ /* LINUX64 (xnulinux): TPIDR_EL1 belongs to Linux; XNU's kernel keeps its thread pointer in TPIDRRO_EL0 */
- unsigned long result;
-- __asm__ ("mrs %0, TPIDR_EL1" : "=r" (result));
-+ __asm__ ("mrs %0, TPIDRRO_EL0" : "=r" (result));
- return __unsafe_forge_single(thread_t, result);
- #else
- // TPIDRPRW
-@@ -101,7 +102,7 @@ current_thread_volatile(void)
- */
- #if defined(__arm64__)
- unsigned long result;
-- __asm__ volatile ("mrs %0, TPIDR_EL1" : "=r" (result));
-+ __asm__ volatile ("mrs %0, TPIDRRO_EL0" : "=r" (result)); /* LINUX64: see current_thread_fast */
- return __unsafe_forge_single(thread_t, result);
- #else
- // TPIDRPRW
-@@ -114,7 +115,16 @@ current_thread_volatile(void)
- static inline vm_offset_t
- exception_stack_pointer(void)
- {
-- vm_offset_t result = 0;
-+ vm_offset_t result = 0, spsel;
-+ /*
-+ * LINUX64 (xnulinux): hosted XNU runs on Linux's SP_EL1 stack, and SP_EL0 is
-+ * Linux's `current`; never flip SPSel. When already on SP_EL1, sp is the answer.
-+ */
-+ __asm__ volatile ("mrs %0, SPSel" : "=r" (spsel));
-+ if (spsel & 1) {
-+ __asm__ volatile ("mov %0, sp" : "=r" (result));
-+ return result;
+ }
- __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
++ mach_vm_size_t size;
++ if (os_add_overflow(length, pageOffset, &size)) {
++ return kIOReturnBadArgument;
++ }
++ physAddr -= pageOffset;
++ if (os_add_overflow(segLen, pageOffset, &segLen)) {
++ return kIOReturnBadArgument;
++ }
++ mach_vm_size_t bytes = size;
++ vm_map_address_t curVa = (!isKernelPmap || (options & kIOMapAnywhere)) ? 0 : (vm_map_address_t)trunc_page_64(address);
++
++ do {
++ if (segLen >= bytes) {
++ segLen = bytes;
++ } else if (segLen != trunc_page_64(segLen)) {
++ return kIOReturnVMError;
++ }
++ if (physAddr != trunc_page_64(physAddr)) {
++ return kIOReturnBadArgument;
++ }
++ vm_map_size_t checkLen = round_page_64(segLen);
++ if (checkLen == 0 || checkLen < segLen) {
++ return kIOReturnBadArgument;
++ }
++ if (!pmap_el0_kmap_range_supported(curVa, physAddr, checkLen)) {
++ return kIOReturnUnsupported;
++ }
++ if (isKernelPmap && !(options & kIOMapAnywhere)) {
++ if (os_add_overflow(curVa, checkLen, &curVa)) {
++ return kIOReturnBadArgument;
++ }
++ }
++ sourceOffset += segLen - pageOffset;
++ bytes -= segLen;
++ pageOffset = 0;
++ if (!bytes) {
++ break;
++ }
++ segLen = 0;
++ physAddr = md->getPhysicalSegment(sourceOffset, &segLen, kIOMemoryMapperNone);
++ } while (physAddr || segLen);
++
++ if (bytes) {
++ return kIOReturnBadArgument;
++ }
++ return KERN_SUCCESS;
++}
++
++static IOReturn
++populateDevicePagerObject(
++ IOMemoryDescriptor *md,
++ void * _pager,
++ mach_vm_size_t sourceOffset,
++ mach_vm_size_t length,
++ bool pagerContig,
++ IOOptionBits mdFlags,
++ vm_map_t nativeFaultMap,
++ mach_vm_address_t nativeFaultAddr,
++ IOOptionBits nativeFaultOpts)
+ {
+ IOReturn err = kIOReturnSuccess;
+ memory_object_t pager = (memory_object_t) _pager;
+@@ -5568,27 +5877,51 @@ IOMemoryDescriptor::populateDevicePager(
+ mach_vm_size_t bytes;
+ mach_vm_size_t page;
+ mach_vm_size_t pageOffset;
+- mach_vm_size_t pagerOffset;
+- IOPhysicalLength segLen, chunk;
++ mach_vm_size_t pagerOffset = 0;
++ IOPhysicalLength segLen = 0, chunk;
+ addr64_t physAddr;
+ IOOptionBits type;
+
+- type = _flags & kIOMemoryTypeMask;
++ type = mdFlags & kIOMemoryTypeMask;
+
+- if (reserved->dp.pagerContig) {
++ if (pagerContig) {
+ sourceOffset = 0;
+ pagerOffset = 0;
++ length = md->getLength();
+ }
--#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(); })
+- physAddr = getPhysicalSegment( sourceOffset, &segLen, kIOMemoryMapperNone );
+- assert( physAddr );
++ physAddr = md->getPhysicalSegment( sourceOffset, &segLen, kIOMemoryMapperNone );
++ if (!physAddr && !segLen) {
++ return kIOReturnBadArgument;
++ }
+ pageOffset = physAddr - trunc_page_64( physAddr );
+- pagerOffset = sourceOffset;
++ if (!pagerContig) {
++ if (md->_memRef && md->_memRef->count == 1) {
++ mach_vm_size_t entryOffset = sourceOffset - md->_memRef->entries[0].offset;
++ if ((entryOffset & PAGE_MASK) != pageOffset) {
++ return kIOReturnNotAligned;
++ }
++ entryOffset -= pageOffset;
++ if (entryOffset >= md->_memRef->entries[0].size) {
++ return kIOReturnBadArgument;
++ }
++ pagerOffset = entryOffset;
++ } else {
++ if (sourceOffset != trunc_page_64(sourceOffset)) {
++ return kIOReturnNotAligned;
++ }
++ pagerOffset = sourceOffset;
++ }
++ }
- #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
-+++ b/osfmk/arm/machdep_call.c
-@@ -38,6 +38,7 @@
+- size = length + pageOffset;
++ if (os_add_overflow(length, pageOffset, &size)) {
++ return kIOReturnBadArgument;
++ }
+ physAddr -= pageOffset;
- #include <kern/thread.h>
- #include <mach/mach_types.h>
-+#include <linux64/linux64.h>
- #include <arm/machdep_call.h>
- #if __arm64__
- #include <arm64/machine_machdep.h>
-@@ -49,6 +50,10 @@ uintptr_t
- get_tpidrro(void)
- {
- uintptr_t uthread;
-+ if (linux64_hook) {
-+ /* LINUX64 (xnulinux): in the kernel TPIDRRO_EL0 is the thread pointer; EL0 gets cthread_self on return */
-+ return current_thread()->machine.cthread_self;
+- segLen += pageOffset;
++ if (os_add_overflow(segLen, pageOffset, &segLen)) {
++ return kIOReturnBadArgument;
+ }
- __asm__ volatile ("mrs %0, TPIDRRO_EL0" : "=r" (uthread));
- return uthread;
+ bytes = size;
+ do{
+ // in the middle of the loop only map whole pages
+@@ -5613,7 +5946,7 @@ IOMemoryDescriptor::populateDevicePager(
+ }
+ #endif /* DEBUG || DEVELOPMENT */
+
+- chunk = (reserved->dp.pagerContig ? round_page(segLen) : page_size);
++ chunk = (pagerContig ? round_page(segLen) : page_size);
+ for (page = 0;
+ (page < segLen) && (KERN_SUCCESS == err);
+ page += chunk) {
+@@ -5622,40 +5955,59 @@ IOMemoryDescriptor::populateDevicePager(
+ pagerOffset += chunk;
+ }
+
+- assert(KERN_SUCCESS == err);
++ assert(KERN_SUCCESS == err || (pagerContig && KERN_INVALID_VALUE == err));
+ if (err) {
+ break;
+ }
+
+- // This call to vm_fault causes an early pmap level resolution
+- // of the mappings created above for kernel mappings, since
+- // faulting in later can't take place from interrupt level.
+- if ((addressMap == kernel_map) && !(kIOMemoryRedirected & _flags)) {
+- err = vm_fault(addressMap,
+- (vm_map_offset_t)trunc_page_64(address),
+- options & kIOMapReadOnly ? VM_PROT_READ : VM_PROT_READ | VM_PROT_WRITE,
++ if ((nativeFaultMap == kernel_map) && !(kIOMemoryRedirected & mdFlags) && !linux64_el0) {
++ err = vm_fault(nativeFaultMap,
++ (vm_map_offset_t)trunc_page_64(nativeFaultAddr),
++ nativeFaultOpts & kIOMapReadOnly ? VM_PROT_READ : VM_PROT_READ | VM_PROT_WRITE,
+ FALSE, VM_KERN_MEMORY_NONE,
+ THREAD_UNINT, NULL,
+ (vm_map_offset_t)0);
+-
+ if (KERN_SUCCESS != err) {
+ break;
+ }
+ }
+
+ sourceOffset += segLen - pageOffset;
+- address += segLen;
++ nativeFaultAddr += segLen;
+ bytes -= segLen;
+ pageOffset = 0;
+- }while (bytes && (physAddr = getPhysicalSegment( sourceOffset, &segLen, kIOMemoryMapperNone )));
++ }while (bytes && (segLen = 0, physAddr = md->getPhysicalSegment( sourceOffset, &segLen, kIOMemoryMapperNone ), physAddr || segLen));
+
+- if (bytes) {
++ if ((KERN_SUCCESS == err) && bytes) {
+ err = kIOReturnBadArgument;
+ }
+
+ return err;
}
-@@ -56,6 +61,9 @@ get_tpidrro(void)
- void
- set_tpidrro(uintptr_t uthread)
- {
-+ if (linux64_hook) {
-+ return; /* LINUX64: loaded from cthread_self on the way back to user space (linux64_el0_run) */
+
++IOReturn
++IOMemoryDescriptor::populateDevicePager(
++ void * _pager,
++ vm_map_t addressMap,
++ mach_vm_address_t address,
++ mach_vm_size_t sourceOffset,
++ mach_vm_size_t length,
++ IOOptionBits options )
++{
++ IOReturn err = populateDevicePagerObject(this, _pager, sourceOffset, length,
++ reserved->dp.pagerContig, _flags,
++ linux64_el0 ? VM_MAP_NULL : addressMap, address, options);
++
++ if (linux64_el0 && (err == KERN_SUCCESS) && !(kIOMemoryRedirected & _flags) &&
++ linux64_el0_is_kernel_pmap(addressMap)) {
++ err = linux64_el0_prefault_kernel_map(addressMap,
++ address, length,
++ (options & kIOMapReadOnly) ? VM_PROT_READ : (VM_PROT_READ | VM_PROT_WRITE));
+ }
- __asm__ volatile ("msr TPIDRRO_EL0, %0" : : "r" (uthread));
++
++ return err;
++}
++
+ IOReturn
+ IOMemoryDescriptor::doUnmap(
+ vm_map_t addressMap,
+@@ -5701,47 +6053,132 @@ IOMemoryDescriptor::doUnmap(
+ return err;
}
-diff --git a/osfmk/arm/machine_routines_common.c b/osfmk/arm/machine_routines_common.c
-index b65f76c..eac911b 100644
---- a/osfmk/arm/machine_routines_common.c
-+++ b/osfmk/arm/machine_routines_common.c
-@@ -27,6 +27,7 @@
- */
-
- #include <arm/machine_cpu.h>
-+#include <linux64/linux64.h>
- #include <arm/cpu_internal.h>
- #include <arm/cpuid.h>
- #include <arm/cpuid_internal.h>
-@@ -1094,6 +1095,59 @@ ml_set_interrupts_enabled_with_debug(boolean_t enable, boolean_t __unused debug)
+-IOReturn
+-IOMemoryDescriptor::redirect( task_t safeTask, bool doRedirect )
++static inline bool
++el0MappingUsesProtectCacheMode(IOMemoryMap *mapping, task_t safeTask)
+ {
+- IOReturn err = kIOReturnSuccess;
+- IOMemoryMap * mapping = NULL;
+- OSSharedPtr<OSIterator> iter;
+-
+- LOCK;
++ return ((safeTask && (get_task_map(safeTask) == mapping->fAddressMap)) ||
++ (0 != (mapping->fOptions & kIOMapStatic))) &&
++ (kIOMapWriteCombineCache == (mapping->fOptions & kIOMapCacheMask)) &&
++ (NULL == mapping->fSuperMap);
++}
- thread = current_thread();
+- if (doRedirect) {
+- _flags |= kIOMemoryRedirected;
+- } else {
+- _flags &= ~kIOMemoryRedirected;
++IOReturn
++el0IOMemoryDescriptorRedirectList(
++ IOMemoryDescriptor **descs,
++ uint32_t count,
++ task_t safeTask,
++ bool doRedirect)
++{
++ if (descs == NULL || count == 0) {
++ return kIOReturnSuccess;
+ }
-+ {
-+ /*
-+ * 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 (per CPU); timer "interrupts" are delivered from cpu_idle.
-+ */
-+ if (linux64_hook) {
-+ 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; and take an
-+ * IPI another CPU sent.
-+ */
-+ static uint64_t linux64_last_kyield[LINUX64_CPU_SLOTS];
-+ uint64_t now = mach_absolute_time();
-+ 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;
-+ /*
-+ * Not with preemption off (a spinlock held): Linux may reschedule this CPU's thread
-+ * away for as long as it likes, and every other CPU spins on the lock until XNU's
-+ * ticket-lock timeout panics.
-+ */
-+ if (get_preemption_level() == 0) {
-+ linux64_call2(LINUX64_CALL_PREEMPTED, 1, 0);
-+ }
-+ if (cdp->rtcPop != 0 && cdp->rtcPop != 0xFFFFFFFFFFFFFFFFULL && mach_absolute_time() >= cdp->rtcPop) {
-+ cdp->cpu_decrementer = -1;
-+ rtclock_intr(FALSE);
-+ }
-+ }
-+ linux64_ipi_take();
-+ }
-+ if (get_preemption_level() == 0) {
-+ while (thread->machine.CpuDatap->cpu_pending_ast & AST_URGENT) {
-+ ast_taken_kernel();
-+ }
+- do {
+- if ((iter = OSCollectionIterator::withCollection( _mappings.get()))) {
+- memory_object_t pager;
++ __block IOReturn err = kIOReturnSuccess;
+
+- if (reserved) {
+- pager = (memory_object_t) reserved->dp.devicePager;
+- } else {
+- pager = MACH_PORT_NULL;
+- }
++ LOCK;
+
+- while ((mapping = (IOMemoryMap *) iter->getNextObject())) {
+- mapping->redirect( safeTask, doRedirect );
+- if (!doRedirect && !safeTask && pager && (kernel_map == mapping->fAddressMap)) {
+- err = populateDevicePager(pager, mapping->fAddressMap, mapping->fAddress, mapping->fOffset, mapping->fLength, kIOMapDefaultCache );
++ /*
++ * Pass 0: Pure read-only preflight over all descriptors and mappings
++ * using zero-allocation iterateObjects before mutating any state.
++ */
++ for (uint32_t i = 0; i < count && kIOReturnSuccess == err; i++) {
++ OSSet *mset = descs[i]->_mappings.get();
++ if (!mset || mset->getCount() == 0) {
++ continue;
++ }
++ IOMemoryDescriptor *desc = descs[i];
++ IOMemoryDescriptorReserved *r = desc->reserved;
++ memory_object_t pager = r ? (memory_object_t) r->dp.devicePager : MACH_PORT_NULL;
++ IOOptionBits dflags = desc->_flags;
++ mset->iterateObjects(^(OSObject *object) {
++ IOMemoryMap *mapping = (IOMemoryMap *) object;
++ if (linux64_el0 && mapping->fAddress && mapping->fLength && mapping->fAddressMap &&
++ linux64_el0_is_kernel_pmap(mapping->fAddressMap)) {
++ if (el0MappingUsesProtectCacheMode(mapping, safeTask)) {
++ err = kIOReturnUnsupported;
++ return true;
+ }
+ }
++ if (!doRedirect && !safeTask && linux64_el0 && pager &&
++ (kernel_map == mapping->fAddressMap) &&
++ mapping->fAddress && mapping->fLength) {
++ IOReturn preErr = el0PreflightDevicePager(desc, mapping->fAddressMap,
++ mapping->fAddress, mapping->fOffset, mapping->fLength,
++ mapping->fOptions & ~kIOMapAnywhere, r->dp.pagerContig, dflags);
++ if (kIOReturnSuccess != preErr) {
++ err = preErr;
++ return true;
+ }
-+ /* 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[slot] = 0;
+ }
-+ return was;
++ return false;
++ });
++ }
++ if (kIOReturnSuccess != err) {
++ UNLOCK;
++ return err;
++ }
+
+- iter.reset();
++ /*
++ * Pass 1: Update _flags first (matching native XNU to block recursive
++ * IOMemoryMap::redirect -> fMemory->redirect), then apply mapping
++ * transitions zero-alloc via iterateObjects.
++ */
++ for (uint32_t i = 0; i < count; i++) {
++ if (doRedirect) {
++ descs[i]->_flags |= kIOMemoryRedirected;
++ } else {
++ descs[i]->_flags &= ~kIOMemoryRedirected;
+ }
+- } while (false);
++ }
++
++ for (uint32_t step = 0; step < count; step++) {
++ uint32_t i = doRedirect ? step : (count - 1 - step);
++ OSSet *mset = descs[i]->_mappings.get();
++ if (!mset || mset->getCount() == 0) {
++ continue;
+ }
++ IOMemoryDescriptor *desc = descs[i];
++ IOMemoryDescriptorReserved *r = desc->reserved;
++ memory_object_t pager = r ? (memory_object_t) r->dp.devicePager : MACH_PORT_NULL;
++ mset->iterateObjects(^(OSObject *object) {
++ IOMemoryMap *mapping = (IOMemoryMap *) object;
++ IOReturn stepErr = mapping->redirect( safeTask, doRedirect );
++ if (!doRedirect && kIOReturnSuccess == stepErr && !safeTask) {
++ if (pager && (kernel_map == mapping->fAddressMap)) {
++ stepErr = desc->populateDevicePager(pager, mapping->fAddressMap,
++ mapping->fAddress, mapping->fOffset, mapping->fLength,
++ kIOMapDefaultCache | (mapping->fOptions & kIOMapReadOnly));
++ } else if (!pager && linux64_el0 &&
++ !(mapping->fOptions & kIOMapStatic) &&
++ mapping->fAddress && mapping->fLength &&
++ mapping->fAddressMap && linux64_el0_is_kernel_pmap(mapping->fAddressMap)) {
++ stepErr = linux64_el0_prefault_kernel_map(mapping->fAddressMap,
++ mapping->fAddress, mapping->fLength,
++ (mapping->fOptions & kIOMapReadOnly) ? VM_PROT_READ : (VM_PROT_READ | VM_PROT_WRITE));
++ }
++ }
++ if (kIOReturnSuccess == err && kIOReturnSuccess != stepErr) {
++ err = stepErr;
++ }
++ return false;
++ });
+ }
+
+ if (!doRedirect) {
+- WAKEUP;
++ for (uint32_t i = 0; i < count; i++) {
++ IORecursiveLockWakeup( gIOMemoryLock, (void *)descs[i], false );
++ }
+ }
+
+ UNLOCK;
++ return err;
++}
+
- state = __builtin_arm_rsr("DAIF");
++IOReturn
++IOMemoryDescriptor::redirect( task_t safeTask, bool doRedirect )
++{
++ IOMemoryDescriptor *self = this;
++ IOReturn err = el0IOMemoryDescriptorRedirectList(&self, 1, safeTask, doRedirect);
+
+ #ifndef __LP64__
+ // temporary binary compatibility
+@@ -5776,26 +6213,30 @@ IOMemoryMap::redirect( task_t safeTask, bool doRedirect )
+
+ if ((!safeTask || (get_task_map(safeTask) != fAddressMap))
+ && (0 == (fOptions & kIOMapStatic))) {
+- IOUnmapPages( fAddressMap, fAddress, fLength );
+- err = kIOReturnSuccess;
++ err = IOUnmapPages( fAddressMap, fAddress, fLength );
+ #if DEBUG
+ IOLog("IOMemoryMap::redirect(%d, %p) 0x%qx:0x%qx from %p\n", doRedirect, this, fAddress, fLength, fAddressMap);
+ #endif
+ } else if (kIOMapWriteCombineCache == (fOptions & kIOMapCacheMask)) {
+ IOOptionBits newMode;
+ newMode = (fOptions & ~kIOMapCacheMask) | (doRedirect ? kIOMapInhibitCache : kIOMapWriteCombineCache);
+- IOProtectCacheMode(fAddressMap, fAddress, fLength, newMode);
++ err = IOProtectCacheMode(fAddressMap, fAddress, fLength, newMode);
+ }
+ }while (false);
+ UNLOCK;
+ }
- if (__improbable(!(state & DAIF_DEBUGF))) {
-@@ -1366,6 +1420,68 @@ ml_early_cpu_max_number(void)
- return ml_get_max_cpu_number();
++ LOCK;
+ if ((((fMemory->_flags & kIOMemoryTypeMask) == kIOMemoryTypePhysical)
+ || ((fMemory->_flags & kIOMemoryTypeMask) == kIOMemoryTypePhysical64))
+ && safeTask
+ && (doRedirect != (0 != (fMemory->_flags & kIOMemoryRedirected)))) {
+- fMemory->redirect(safeTask, doRedirect);
++ IOReturn memErr = fMemory->redirect(safeTask, doRedirect);
++ if (kIOReturnSuccess == err && kIOReturnSuccess != memErr) {
++ err = memErr;
++ }
+ }
++ UNLOCK;
+
+ return err;
+ }
+@@ -5865,9 +6306,53 @@ IOMemoryMap::taggedRelease(const void *tag) const
+ super::taggedRelease(tag, 2);
}
-+/*
-+ * 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)
++static IOReturn
++el0PrefaultMappingSet(OSSet *mappings, IOOptionBits mdFlags, IOMemoryMap *skipMap = NULL)
+{
-+ 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;
++ __block IOReturn err = kIOReturnSuccess;
++ if (!linux64_el0 || !mappings || (mdFlags & kIOMemoryRedirected)) {
++ return kIOReturnSuccess;
+ }
-+ linux64_last_relax[slot] = now;
-+ linux64_call2(LINUX64_CALL_PREEMPTED, 1, 0);
-+ /*
-+ * Spinning with XNU's interrupts enabled, a CPU takes another CPU's IPI on hardware (its FIQ): the other may be
-+ * waiting for exactly that (a cross-call's acknowledgment) before it lets go of what this one spins on. Take a
-+ * pending one here as the FIQ would, interrupts off around the handler; no AST, no context switch.
-+ */
-+ if (linux64_vint[slot] && getCpuDatap()->cpu_int_state == NULL) {
-+ linux64_vint[slot] = 0;
-+ linux64_ipi_take();
-+ linux64_vint[slot] = 1;
++ mappings->iterateObjects(^(OSObject *object) {
++ IOMemoryMap *m = (IOMemoryMap *)object;
++ if (m == skipMap) {
++ return false;
++ }
++ if (m->fAddress && m->fLength && !(m->fOptions & kIOMapStatic) &&
++ linux64_el0_is_kernel_pmap(m->fAddressMap)) {
++ IOReturn mapErr = linux64_el0_prefault_kernel_map(m->fAddressMap,
++ m->fAddress, m->fLength,
++ (m->fOptions & kIOMapReadOnly) ? VM_PROT_READ : (VM_PROT_READ | VM_PROT_WRITE));
++ if (kIOReturnSuccess == err && kIOReturnSuccess != mapErr) {
++ err = mapErr;
++ }
++ }
++ return false;
++ });
++ return err;
++}
++
+ void
+ IOMemoryMap::free()
+ {
++ bool hadRedirUPL = false;
++
++ if (fRedirUPL) {
++ upl_commit(fRedirUPL, NULL, 0);
++ upl_deallocate(fRedirUPL);
++ fRedirUPL = NULL;
++ hadRedirUPL = true;
++ }
++
++ if (linux64_el0 && hadRedirUPL && fMemory) {
++ LOCK;
++ IOReturn pfErr = el0PrefaultMappingSet(fMemory->_mappings.get(), fMemory->_flags, this);
++ UNLOCK;
++ if (kIOReturnSuccess != pfErr) {
++ IOLog("IOMemoryMap::free: EL0 alias restore failed err=0x%x\n", pfErr);
++ }
++ }
++
+ unmap();
+
+ if (fMemory) {
+@@ -5881,11 +6366,6 @@ IOMemoryMap::free()
+ fSuperMap.reset();
+ }
+
+- if (fRedirUPL) {
+- upl_commit(fRedirUPL, NULL, 0);
+- upl_deallocate(fRedirUPL);
+- }
+-
+ super::free();
+ }
+
+@@ -6125,6 +6605,10 @@ IOMemoryDescriptor::createMappingInTask(
+ IOMemoryMap * result;
+ IOMemoryMap * mapping;
+
++ if ((kIOMapReference | kIOMapUnique) == ((kIOMapReference | kIOMapUnique) & options)) {
++ return nullptr;
++ }
++
+ if (0 == length) {
+ length = getLength();
+ }
+@@ -6184,17 +6668,33 @@ IOMemoryMap::redirect(IOMemoryDescriptor * newBackingMemory,
+ physMem = fMemory;
+ }
+
+- if (!fRedirUPL && fMemory->_memRef && (1 == fMemory->_memRef->count)) {
+- upl_size_t size = (typeof(size))round_page(fLength);
+- upl_control_flags_t flags = UPL_COPYOUT_FROM | UPL_SET_INTERNAL
+- | UPL_SET_LITE | UPL_SET_IO_WIRE | UPL_BLOCK_ACCESS;
+- if (KERN_SUCCESS != memory_object_iopl_request(fMemory->_memRef->entries[0].entry, 0, &size, &fRedirUPL,
+- NULL, NULL,
+- &flags, (vm_tag_t) fMemory->getVMTag(kernel_map))) {
+- fRedirUPL = NULL;
++ bool el0ReleasedAutowire = false;
++ if (linux64_el0 && !fRedirUPL && fMemory && fMemory->_memRef &&
++ (1 == fMemory->_memRef->count) && !(fOptions & kIOMapStatic) &&
++ linux64_el0_is_kernel_pmap(fAddressMap)) {
++ linux64_el0_release_autowire_range(fAddressMap, fAddress, fLength);
++ el0ReleasedAutowire = true;
++ }
++
++ if (!fRedirUPL) {
++ if (!fMemory || !fMemory->_memRef || (1 != fMemory->_memRef->count)) {
++ err = kIOReturnNotReadable;
++ } else {
++ upl_size_t size = (typeof(size))round_page(fLength);
++ upl_control_flags_t flags = UPL_COPYOUT_FROM | UPL_SET_INTERNAL
++ | UPL_SET_LITE | UPL_SET_IO_WIRE | UPL_BLOCK_ACCESS;
++ kern_return_t uplErr = memory_object_iopl_request(fMemory->_memRef->entries[0].entry, 0, &size, &fRedirUPL,
++ NULL, NULL,
++ &flags, (vm_tag_t) fMemory->getVMTag(kernel_map));
++ if (KERN_SUCCESS != uplErr) {
++ fRedirUPL = NULL;
++ err = uplErr;
++ } else if (NULL == fRedirUPL) {
++ err = kIOReturnError;
++ }
+ }
+
+- if (physMem) {
++ if (fRedirUPL && physMem) {
+ IOUnmapPages( fAddressMap, fAddress, fLength );
+ if ((false)) {
+ physMem->redirect(NULL, true);
+@@ -6202,12 +6702,25 @@ IOMemoryMap::redirect(IOMemoryDescriptor * newBackingMemory,
+ }
+ }
+
++ if (el0ReleasedAutowire && !fRedirUPL && !newBackingMemory &&
++ fMemory && !(fMemory->_flags & kIOMemoryRedirected)) {
++ IOReturn pfErr = linux64_el0_prefault_kernel_map(fAddressMap, fAddress, fLength,
++ (fOptions & kIOMapReadOnly) ? VM_PROT_READ : (VM_PROT_READ | VM_PROT_WRITE));
++ if (kIOReturnSuccess == err && kIOReturnSuccess != pfErr) {
++ err = pfErr;
++ }
++ }
++
+ if (newBackingMemory) {
+- if (newBackingMemory != fMemory) {
++ OSSharedPtr<IOMemoryDescriptor> oldMemory = fMemory;
++ const mach_vm_size_t savedOffset = fOffset;
++ bool committedRedirUPL = false;
++ if (kIOReturnSuccess == err && newBackingMemory != fMemory) {
+ fOffset = 0;
+ if (this != newBackingMemory->makeMapping(newBackingMemory, fAddressTask, (IOVirtualAddress) this,
+ options | kIOMapUnique | kIOMapReference | kIOMap64Bit,
+ offset, fLength)) {
++ fOffset = savedOffset;
+ err = kIOReturnError;
+ }
+ }
+@@ -6215,6 +6728,36 @@ IOMemoryMap::redirect(IOMemoryDescriptor * newBackingMemory,
+ upl_commit(fRedirUPL, NULL, 0);
+ upl_deallocate(fRedirUPL);
+ fRedirUPL = NULL;
++ committedRedirUPL = true;
++ }
++ if (linux64_el0 && (committedRedirUPL || el0ReleasedAutowire || (kIOReturnSuccess == err))) {
++ if (fMemory && !(fOptions & kIOMapStatic) &&
++ !(fMemory->_flags & kIOMemoryRedirected) &&
++ linux64_el0_is_kernel_pmap(fAddressMap)) {
++ IOReturn selfErr = linux64_el0_prefault_kernel_map(fAddressMap, fAddress, fLength,
++ (fOptions & kIOMapReadOnly) ? VM_PROT_READ : (VM_PROT_READ | VM_PROT_WRITE));
++ if (kIOReturnSuccess == err && kIOReturnSuccess != selfErr) {
++ err = selfErr;
++ }
++ }
++ if (oldMemory) {
++ IOReturn oldErr = el0PrefaultMappingSet(oldMemory->_mappings.get(), oldMemory->_flags);
++ if (kIOReturnSuccess == err && kIOReturnSuccess != oldErr) {
++ err = oldErr;
++ }
++ }
++ if (fMemory && fMemory != oldMemory) {
++ IOReturn memErr = el0PrefaultMappingSet(fMemory->_mappings.get(), fMemory->_flags);
++ if (kIOReturnSuccess == err && kIOReturnSuccess != memErr) {
++ err = memErr;
++ }
++ }
++ if (newBackingMemory != oldMemory.get() && newBackingMemory != fMemory.get()) {
++ IOReturn newErr = el0PrefaultMappingSet(newBackingMemory->_mappings.get(), newBackingMemory->_flags);
++ if (kIOReturnSuccess == err && kIOReturnSuccess != newErr) {
++ err = newErr;
++ }
++ }
+ }
+ if ((false) && physMem) {
+ physMem->redirect(NULL, false);
+@@ -6247,6 +6790,9 @@ IOMemoryDescriptor::makeMapping(
+ __block IOMemoryMap * result = NULL;
+
+ IOMemoryMap * mapping = (IOMemoryMap *) __address;
++ const bool borrowedMapping = (mapping->fMemory != nullptr) &&
++ ((kIOMapReference | kIOMapUnique) == ((kIOMapReference | kIOMapUnique) & options));
++ const mach_vm_size_t origOffset = mapping->fOffset;
+ mach_vm_size_t offset = mapping->fOffset + __offset;
+ mach_vm_size_t length = mapping->fLength;
+
+@@ -6272,12 +6818,24 @@ IOMemoryDescriptor::makeMapping(
+ || ((_flags & kIOMemoryTypeMask) == kIOMemoryTypePhysical64)) {
+ phys = getPhysicalSegment(offset, &physLen, kIOMemoryMapperNone);
+ if (!phys || (physLen < length)) {
++ if (borrowedMapping) {
++ mapping->fOffset = origOffset;
++ } else {
++ mapping->release();
++ mapping = NULL;
++ }
+ continue;
+ }
+
+ mapDesc = IOMemoryDescriptor::withAddressRange(
+ phys, length, getDirection() | kIOMemoryMapperNone, NULL);
+ if (!mapDesc) {
++ if (borrowedMapping) {
++ mapping->fOffset = origOffset;
++ } else {
++ mapping->release();
++ mapping = NULL;
++ }
+ continue;
+ }
+ offset = 0;
+@@ -6315,6 +6873,8 @@ IOMemoryDescriptor::makeMapping(
+ result = mapping;
+ mapDesc->addMapping(result);
+ result->setMemoryDescriptor(mapDesc.get(), offset);
++ } else if (borrowedMapping) {
++ mapping->fOffset = origOffset;
+ } else {
+ mapping->release();
+ mapping = NULL;
+@@ -6643,3 +7203,376 @@ _IOMemoryDescriptorMixedData::getLength() const
+ {
+ return _data ? _length : 0;
+ }
++
++static bool
++el0GrowOverwriteChunks(
++ struct linux64_el0_mem_entry_chunk **chunksIO,
++ size_t *capIO,
++ size_t need)
++{
++ if (need <= *capIO) {
++ return true;
++ }
++ size_t newCap = (*capIO == 0) ? 16 : *capIO;
++ while (newCap < need) {
++ if (os_mul_overflow(newCap, 2, &newCap)) {
++ return false;
++ }
++ }
++ struct linux64_el0_mem_entry_chunk *nb = IONew(struct linux64_el0_mem_entry_chunk, newCap);
++ if (nb == NULL) {
++ return false;
+ }
++ if (*chunksIO != NULL) {
++ bcopy(*chunksIO, nb, (*capIO) * sizeof(*nb));
++ IODelete(*chunksIO, struct linux64_el0_mem_entry_chunk, *capIO);
++ }
++ *chunksIO = nb;
++ *capIO = newCap;
++ return true;
+}
+
-+void
-+linux64_ipi_take(void)
++static bool
++el0GrowPendingPagers(
++ struct linux64_el0_pending_pager **pagersIO,
++ size_t *capIO,
++ size_t need)
+{
-+ unsigned int slot = linux64_cpu_slot();
++ if (need <= *capIO) {
++ return true;
++ }
++ size_t newCap = (*capIO == 0) ? 8 : *capIO;
++ while (newCap < need) {
++ if (os_mul_overflow(newCap, 2, &newCap)) {
++ return false;
++ }
++ }
++ struct linux64_el0_pending_pager *nb = IONew(struct linux64_el0_pending_pager, newCap);
++ if (nb == NULL) {
++ return false;
++ }
++ if (*pagersIO != NULL) {
++ bcopy(*pagersIO, nb, (*capIO) * sizeof(struct linux64_el0_pending_pager));
++ IODelete(*pagersIO, struct linux64_el0_pending_pager, *capIO);
++ }
++ *pagersIO = nb;
++ *capIO = newCap;
++ return true;
++}
+
-+ if (os_atomic_load(&linux64_ipi_pending[slot], relaxed) && os_atomic_xchg(&linux64_ipi_pending[slot], 0, acquire)) {
-+ cpu_signal_handler();
++IOReturn
++el0PopulatePendingPagers(
++ const struct linux64_el0_pending_pager *pagers,
++ size_t npagers)
++{
++ for (size_t i = 0; i < npagers; i++) {
++ IOReturn err = populateDevicePagerObject(pagers[i].md, pagers[i].pager,
++ pagers[i].offset, pagers[i].length, pagers[i].pager_contig,
++ pagers[i].md_flags, VM_MAP_NULL, 0, 0);
++ if (kIOReturnSuccess != err) {
++ return err;
++ }
+ }
++ return kIOReturnSuccess;
+}
+
-+void
-+linux64_cpu_signal(unsigned int cpu)
++IOReturn
++el0CollectOverwriteChunks(
++ IOMemoryDescriptor *desc,
++ vm_map_t map,
++ IOMemoryMap *mapping,
++ IOOptionBits options,
++ mach_vm_size_t offset,
++ mach_vm_size_t length,
++ mach_vm_address_t baseAddr,
++ mach_vm_size_t allowedMapSize,
++ mach_vm_address_t *curLogicalAddrIO,
++ struct linux64_el0_mem_entry_chunk **chunksIO,
++ size_t *nchunksIO,
++ size_t *capIO,
++ mach_vm_size_t *totalMapSizeIO,
++ struct linux64_el0_pending_pager **pagersIO,
++ size_t *npagersIO,
++ size_t *pagerCapIO)
+{
-+ cpu_data_t *target = CpuDataEntries[cpu].cpu_data_vaddr;
-+ uint64_t mpidr;
++ if (desc == NULL || map == VM_MAP_NULL || mapping == NULL || curLogicalAddrIO == NULL ||
++ pagersIO == NULL || npagersIO == NULL || pagerCapIO == NULL) {
++ return kIOReturnBadArgument;
++ }
++ if (length == 0) {
++ return kIOReturnSuccess;
++ }
+
-+ if (target == NULL) {
-+ return;
++ if (IOMultiMemoryDescriptor *mmd = OSDynamicCast(IOMultiMemoryDescriptor, desc)) {
++ mach_vm_size_t mapOffset = offset;
++ mach_vm_size_t bytesRemaining = length;
++ IOOptionBits subOptions = (options & ~kIOMapAnywhere) | kIOMapOverwrite;
++ if (mapOffset > mmd->_length) {
++ return kIOReturnBadArgument;
++ }
++ for (unsigned index = 0; bytesRemaining && (index < mmd->_descriptorsCount); index++) {
++ if (mmd->_descriptors[index] == NULL) {
++ return kIOReturnBadArgument;
++ }
++ mach_vm_size_t chunk = mmd->_descriptors[index]->getLength();
++ if (mapOffset >= chunk) {
++ mapOffset -= chunk;
++ continue;
++ }
++ chunk -= mapOffset;
++ if (chunk > bytesRemaining) {
++ chunk = bytesRemaining;
++ }
++ IOReturn subErr = el0CollectOverwriteChunks(mmd->_descriptors[index],
++ map, mapping, subOptions, mapOffset, chunk,
++ baseAddr, allowedMapSize, curLogicalAddrIO,
++ chunksIO, nchunksIO, capIO, totalMapSizeIO,
++ pagersIO, npagersIO, pagerCapIO);
++ if (kIOReturnSuccess != subErr) {
++ return subErr;
++ }
++ bytesRemaining -= chunk;
++ mapOffset = 0;
++ }
++ if (bytesRemaining != 0) {
++ return kIOReturnUnderrun;
++ }
++ return kIOReturnSuccess;
+ }
-+ 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 +1500,12 @@ ml_wait_max_cpus(void)
- {
- assert(lockdown_done);
- lck_mtx_lock(&max_cpus_lock);
-+ {
-+ /* LINUX64 (xnulinux): hosted without the CPU kext that calls ml_set_max_cpus(); one CPU, known now. */
-+ if (linux64_hook) {
-+ max_cpus_initialized = MAX_CPUS_SET;
++ if (IOSubMemoryDescriptor *smd = OSDynamicCast(IOSubMemoryDescriptor, desc)) {
++ if (smd->_parent == NULL || offset > smd->_length || length > smd->_length - offset) {
++ return kIOReturnBadArgument;
++ }
++ mach_vm_size_t parentOffset = 0;
++ if (os_add_overflow(smd->_start, offset, &parentOffset)) {
++ return kIOReturnBadArgument;
+ }
++ return el0CollectOverwriteChunks(smd->_parent, map, mapping, options,
++ parentOffset, length, baseAddr, allowedMapSize, curLogicalAddrIO,
++ chunksIO, nchunksIO, capIO, totalMapSizeIO,
++ pagersIO, npagersIO, pagerCapIO);
+ }
- while (max_cpus_initialized != MAX_CPUS_SET) {
- max_cpus_initialized = MAX_CPUS_WAIT;
- lck_mtx_sleep(&max_cpus_lock, LCK_SLEEP_DEFAULT, &max_cpus_initialized, THREAD_UNINT);
-diff --git a/osfmk/arm/pmap/pmap.c b/osfmk/arm/pmap/pmap.c
-index 79d0bc1..fc50363 100644
---- a/osfmk/arm/pmap/pmap.c
-+++ b/osfmk/arm/pmap/pmap.c
-@@ -327,6 +327,32 @@ const struct page_table_attr * const native_pt_attr = &pmap_pt_attr_16k;
- const struct page_table_attr * const native_pt_attr = &pmap_pt_attr_4k;
- #endif /* !__ARM_16K_PG__ */
++
++ IOGeneralMemoryDescriptor *gmd = OSDynamicCast(IOGeneralMemoryDescriptor, desc);
++ if (gmd == NULL) {
++ return kIOReturnUnsupported;
++ }
++
++ if (offset >= gmd->_length || length > gmd->_length - offset) {
++ return kIOReturnBadArgument;
++ }
++ if (kIOMemoryRemote & gmd->_flags) {
++ return kIOReturnUnsupported;
++ }
++ IOOptionBits leafOptions = options;
++ if ((gmd->reserved != NULL) && (gmd->reserved->dp.devicePager) && (gmd->_wireCount != 0)) {
++ leafOptions &= ~kIOMapPrefault;
++ }
++ if ((leafOptions & kIOMapPrefault) && ((gmd->_wireCount == 0) || (gmd->_memoryEntries == NULL))) {
++ return kIOReturnBadArgument;
++ }
++ if (!gmd->_memRef) {
++ IOReturn mrErr = gmd->memoryReferenceCreate(
++ gmd->memoryReferenceCreateOptions(leafOptions, mapping), &gmd->_memRef);
++ if (kIOReturnSuccess != mrErr) {
++ return mrErr;
++ }
++ }
++
++ mach_vm_offset_t mapMask = vm_map_page_mask(map);
++ memory_object_t pager = (memory_object_t)(gmd->reserved ? gmd->reserved->dp.devicePager : NULL);
++ if (pager) {
++ if (vm_map_trunc_page(*curLogicalAddrIO, mapMask) != baseAddr + *totalMapSizeIO) {
++ return kIOReturnNotAligned;
++ }
++ mach_vm_address_t segBase = baseAddr + *totalMapSizeIO;
++ IOReturn pErr = el0PreflightDevicePager(gmd, map, segBase, offset, length, leafOptions,
++ gmd->reserved->dp.pagerContig, gmd->_flags);
++ if (kIOReturnSuccess != pErr) {
++ return pErr;
++ }
++ if (!(kIOMemoryRedirected & gmd->_flags)) {
++ if (!el0GrowPendingPagers(pagersIO, pagerCapIO, *npagersIO + 1)) {
++ return kIOReturnNoMemory;
++ }
++ struct linux64_el0_pending_pager *pp = &(*pagersIO)[*npagersIO];
++ pp->md = gmd;
++ pp->pager = pager;
++ pp->offset = offset;
++ pp->length = length;
++ pp->pager_contig = gmd->reserved->dp.pagerContig;
++ pp->md_flags = gmd->_flags;
++ (*npagersIO)++;
++ }
++ }
++
++ IOMemoryReference *ref = gmd->_memRef;
++ while (ref != NULL && ref->mapRef != NULL) {
++ ref = ref->mapRef;
++ }
++ if (ref == NULL || ref->count == 0) {
++ return kIOReturnBadArgument;
++ }
++
++ vm_prot_t prot = VM_PROT_READ;
++ if (!(kIOMapReadOnly & leafOptions)) {
++ prot |= VM_PROT_WRITE;
++ }
++ prot &= ref->prot;
++
++ IOOptionBits cacheMode = ((leafOptions & kIOMapCacheMask) >> kIOMapCacheShift);
++ vm_prot_t memEntryCacheMode = 0;
++ if (kIODefaultCache != cacheMode) {
++ memEntryCacheMode = (MAP_MEM_ONLY | VM_PROT_WRITE | prot | vmProtForCacheMode(cacheMode));
++ }
++ vm_tag_t tag = (vm_tag_t)gmd->getVMTag(map);
++
++ if (offset > (mach_vm_size_t)INT64_MAX) {
++ return kIOReturnBadArgument;
++ }
++ int64_t sOffset = (int64_t)offset;
++ uint32_t entryIdx = 0;
++ for (; entryIdx < ref->count; entryIdx++) {
++ if (ref->entries[entryIdx].size > (mach_vm_size_t)INT64_MAX) {
++ return kIOReturnBadArgument;
++ }
++ int64_t eStart = ref->entries[entryIdx].offset;
++ int64_t eEnd = 0;
++ if (os_add_overflow(eStart, (int64_t)ref->entries[entryIdx].size, &eEnd)) {
++ return kIOReturnBadArgument;
++ }
++ if (sOffset >= eStart && sOffset < eEnd) {
++ break;
++ }
++ }
++ if (entryIdx >= ref->count) {
++ return kIOReturnBadArgument;
++ }
++
++ bool useDataAddr = ((MAP_MEM_USE_DATA_ADDR & ref->prot) != 0);
++ mach_vm_size_t preRemain = length;
++ int64_t preOffset = sOffset;
++ mach_vm_size_t prePageOffset = 0;
++
++ if (!useDataAddr) {
++ IOOptionBits type = gmd->_flags & kIOMemoryTypeMask;
++ mach_vm_address_t nextAddr = 0;
++ mach_vm_size_t nextLen = 0;
++ mach_vm_size_t rrem = offset;
++ if (gmd->_task) {
++ if (!gmd->_rangesCount) {
++ return kIOReturnBadArgument;
++ }
++ uint32_t rangeIdx = 0;
++ for (rangeIdx = 0; rangeIdx < gmd->_rangesCount; rangeIdx++) {
++ getAddrLenForInd(nextAddr, nextLen, type, gmd->_ranges, rangeIdx, gmd->_task);
++ if (rrem < nextLen) {
++ break;
++ }
++ rrem -= nextLen;
++ }
++ if (rrem >= nextLen) {
++ return kIOReturnBadArgument;
++ }
++ nextAddr += rrem;
++ } else {
++ IOByteCount physLen = 0;
++ nextAddr = gmd->getPhysicalSegment(offset, &physLen, kIOMemoryMapperNone);
++ }
++#if __ARM_MIXED_PAGE_SIZE__
++ prePageOffset = (mapMask & nextAddr);
++#else
++ prePageOffset = (page_mask & nextAddr);
++#endif
++ if (os_add_overflow(preRemain, prePageOffset, &preRemain)) {
++ return kIOReturnBadArgument;
++ }
++ }
++
++ IOMemoryEntry *preEntry = &ref->entries[entryIdx];
++ uint32_t preIdx = entryIdx;
++ while (preRemain) {
++ if (preIdx >= ref->count) {
++ return kIOReturnOverrun;
++ }
++ int64_t diff = 0;
++ if (os_sub_overflow(preOffset, preEntry->offset, &diff) || diff < 0) {
++ return kIOReturnBadArgument;
++ }
++ mach_vm_size_t preEntryOffset = (mach_vm_size_t)diff;
++ if (!useDataAddr) {
++ if ((IOMin(mapMask, page_mask) & preEntryOffset) != prePageOffset) {
++ return kIOReturnNotAligned;
++ }
++ preEntryOffset -= prePageOffset;
++ }
++ if (preEntryOffset >= preEntry->size) {
++ return kIOReturnBadArgument;
++ }
++ mach_vm_size_t preChunk = preEntry->size - preEntryOffset;
++ if (preChunk) {
++ if (preChunk > preRemain) {
++ preChunk = preRemain;
++ }
++ if (vm_map_trunc_page(*curLogicalAddrIO, mapMask) != baseAddr + *totalMapSizeIO) {
++ return kIOReturnNotAligned;
++ }
++ if (!useDataAddr && ((*curLogicalAddrIO & mapMask) != prePageOffset)) {
++ return kIOReturnNotAligned;
++ }
++ mach_vm_size_t entryMapSize = 0;
++ if (useDataAddr) {
++ kern_return_t sErr = mach_memory_entry_map_size(
++ preEntry->entry, map, preEntryOffset, preChunk, &entryMapSize);
++ if (KERN_SUCCESS != sErr) {
++ return sErr;
++ }
++ } else {
++ entryMapSize = vm_map_round_page(preChunk, mapMask);
++ }
++ if (entryMapSize == 0) {
++ return kIOReturnBadArgument;
++ }
++ mach_vm_size_t newTotal = 0;
++ if (os_add_overflow(*totalMapSizeIO, entryMapSize, &newTotal) ||
++ newTotal > allowedMapSize) {
++ return kIOReturnNotAligned;
++ }
++ if (!el0GrowOverwriteChunks(chunksIO, capIO, *nchunksIO + 1)) {
++ return kIOReturnNoMemory;
++ }
++ struct linux64_el0_mem_entry_chunk *c = &(*chunksIO)[*nchunksIO];
++ c->port = preEntry->entry;
++ c->offset = preEntryOffset;
++ c->size = preChunk;
++ c->map_size = entryMapSize;
++ c->prot = prot;
++ c->tag = tag;
++ c->return_data_addr = useDataAddr;
++ c->check_data_addr = true;
++ c->expected_data_addr = useDataAddr ? *curLogicalAddrIO : vm_map_trunc_page(*curLogicalAddrIO, mapMask);
++ c->cache_perm = memEntryCacheMode;
++ c->data_addr_out = 0;
++ (*nchunksIO)++;
++ *totalMapSizeIO = newTotal;
++ mach_vm_size_t chunkLogicalBytes = useDataAddr ? preChunk : (preChunk - prePageOffset);
++ if (os_add_overflow(*curLogicalAddrIO, chunkLogicalBytes, curLogicalAddrIO)) {
++ return kIOReturnBadArgument;
++ }
++ preRemain -= preChunk;
++ if (!preRemain) {
++ break;
++ }
++ if (chunkLogicalBytes > (mach_vm_size_t)INT64_MAX ||
++ os_add_overflow(preOffset, (int64_t)chunkLogicalBytes, &preOffset)) {
++ return kIOReturnBadArgument;
++ }
++ }
++ prePageOffset = 0;
++ preEntry++;
++ preIdx++;
++ }
++
++ return kIOReturnSuccess;
++}
+diff --git a/iokit/Kernel/IOMultiMemoryDescriptor.cpp b/iokit/Kernel/IOMultiMemoryDescriptor.cpp
+index eeb44f4..9f8073f 100644
+--- a/iokit/Kernel/IOMultiMemoryDescriptor.cpp
++++ b/iokit/Kernel/IOMultiMemoryDescriptor.cpp
+@@ -321,6 +321,53 @@ IOMultiMemoryDescriptor::doMap(vm_map_t __addressMap,
+ mapping->fAddress = address;
+ }
-+#if !__ARM_16K_PG__ && !ARM_PARAMETERIZED_PMAP
-+/*
-+ * LINUX64 (xnulinux): user pmaps of a 4 KiB build walk from level 0 and span the 47 bits TTBR0 runs with (T0SZ_HW), as a macOS
-+ * userland expects (ThreadSanitizer's shadow, nano malloc and MACH_VM_MAX_ADDRESS all sit above the 39 bits a level-1 root reaches).
-+ * The kernel pmap keeps pmap_pt_attr_4k (TTBR1, level-1 root).
-+ */
-+const struct page_table_attr pmap_pt_attr_4k_user = {
-+ .pta_level_info = pmap_table_level_info_4k,
-+ .pta_root_level = PMAP_TT_L0_LEVEL,
-+ .pta_commpage_level = PMAP_TT_L1_LEVEL,
-+ .pta_max_level = PMAP_TT_L3_LEVEL,
-+ .pta_ops = &native_pt_ops,
-+ .ap_ro = ARM_PTE_AP(AP_RORO),
-+ .ap_rw = ARM_PTE_AP(AP_RWRW),
-+ .ap_rona = ARM_PTE_AP(AP_RONA),
-+ .ap_rwna = ARM_PTE_AP(AP_RWNA),
-+ .ap_xn = ARM_PTE_PNX | ARM_PTE_NX,
-+ .ap_x = ARM_PTE_PNX,
-+ .pta_page_size = 4096,
-+ .pta_pagezero_size = 4096,
-+ .pta_page_shift = 12,
-+ .pta_va_valid_mask = (1ULL << (64 - T0SZ_HW)) - 1,
-+};
-+const struct page_table_attr * const user_pt_attr = &pmap_pt_attr_4k_user;
-+#endif /* !__ARM_16K_PG__ && !ARM_PARAMETERIZED_PMAP */
++ if (linux64_el0 && linux64_el0_is_kernel_pmap(map) && (options & kIOMapOverwrite)) {
++ mach_vm_offset_t mapMask = vm_map_page_mask(map);
++ mach_vm_address_t baseAddr = vm_map_trunc_page(address, mapMask);
++ mach_vm_address_t rawEnd = 0;
++ if (os_add_overflow(address, length, &rawEnd)) {
++ err = kIOReturnBadArgument;
++ break;
++ }
++ mach_vm_address_t endAddr = vm_map_round_page(rawEnd, mapMask);
++ if (endAddr < rawEnd) {
++ err = kIOReturnBadArgument;
++ break;
++ }
++ mach_vm_size_t allowedMapSize = endAddr - baseAddr;
++ mach_vm_address_t curLogicalAddr = address;
++ struct linux64_el0_mem_entry_chunk *chunks = NULL;
++ size_t nchunks = 0;
++ size_t cap = 0;
++ mach_vm_size_t totalMapSize = 0;
++ struct linux64_el0_pending_pager *pagers = NULL;
++ size_t npagers = 0;
++ size_t pagerCap = 0;
++
++ err = el0CollectOverwriteChunks(this, map, mapping, options, offset, length,
++ baseAddr, allowedMapSize, &curLogicalAddr,
++ &chunks, &nchunks, &cap, &totalMapSize,
++ &pagers, &npagers, &pagerCap);
++ if (kIOReturnSuccess == err &&
++ (curLogicalAddr != rawEnd || totalMapSize != allowedMapSize)) {
++ err = kIOReturnNotAligned;
++ }
++ if (kIOReturnSuccess == err && npagers > 0) {
++ err = el0PopulatePendingPagers(pagers, npagers);
++ }
++ if (kIOReturnSuccess == err && nchunks > 0) {
++ err = linux64_el0_map_mem_entries_overwrite(map, baseAddr, allowedMapSize,
++ chunks, nchunks, prot, (vm_tag_t)IOMemoryTag(map), true, true);
++ }
++ if (pagers != NULL) {
++ IODelete(pagers, struct linux64_el0_pending_pager, pagerCap);
++ }
++ if (chunks != NULL) {
++ IODelete(chunks, struct linux64_el0_mem_entry_chunk, cap);
++ }
++ break;
++ }
+
+ mapOffset = offset;
+ bytesRemaining = length;
+ nextAddress = address;
+diff --git a/iokit/Kernel/IOSubMemoryDescriptor.cpp b/iokit/Kernel/IOSubMemoryDescriptor.cpp
+index 5c807d1..e25a8e7 100644
+--- a/iokit/Kernel/IOSubMemoryDescriptor.cpp
++++ b/iokit/Kernel/IOSubMemoryDescriptor.cpp
+@@ -28,6 +28,7 @@
- #if DEVELOPMENT || DEBUG
- int vm_footprint_suspend_allowed = 1;
-@@ -520,7 +546,7 @@ _Static_assert((ARM64_MAX_OFFSET_DEVICE_LARGE > ARM64_MIN_MAX_ADDRESS) && (ARM64
- _Static_assert((ARM64_MAX_OFFSET_DEVICE_SMALL > ARM64_MIN_MAX_ADDRESS) && (ARM64_MAX_OFFSET_DEVICE_SMALL <= MACH_VM_MAX_ADDRESS),
- "Small device address space size outside allowable range");
+ #include <IOKit/IOSubMemoryDescriptor.h>
+ #include <IOKit/IOLib.h>
++#include <kern/kalloc.h>
--# ifdef XNU_TARGET_OS_OSX
-+# if defined(XNU_TARGET_OS_OSX) || !__ARM_16K_PG__ /* LINUX64: macOS userland gets the whole 47-bit space by default */
- SECURITY_READ_ONLY_LATE(vm_map_offset_t) arm64_pmap_max_offset_default = MACH_VM_MAX_ADDRESS;
- # else
- SECURITY_READ_ONLY_LATE(vm_map_offset_t) arm64_pmap_max_offset_default = 0x0;
-@@ -2983,7 +3009,8 @@ pmap_root_alloc_size(pmap_t pmap)
- const pt_attr_t * const pt_attr = pmap_get_pt_attr(pmap);
- unsigned int root_level = pt_attr_root_level(pt_attr);
- const uint64_t index = pt_attr_va_valid_mask(pt_attr);
-- return ((index >> pt_attr_ln_shift(pt_attr, root_level)) + 1) * sizeof(tt_entry_t);
-+ vm_size_t size = ((index >> pt_attr_ln_shift(pt_attr, root_level)) + 1) * sizeof(tt_entry_t);
-+ return (size < PMAP_ROOT_ALLOC_SIZE) ? PMAP_ROOT_ALLOC_SIZE : size; /* LINUX64: a level-0 root fills half a page */
+ #include "IOKitKernelInternal.h"
+
+@@ -39,9 +40,24 @@ IOReturn
+ IOSubMemoryDescriptor::redirect( task_t safeTask, bool doRedirect )
+ {
+ #ifdef __LP64__
+- super::redirect( safeTask, doRedirect );
+-#endif /* __LP64__ */
++ IOMemoryDescriptor *chain[64];
++ uint32_t count = 0;
++
++ chain[count++] = this;
++ IOMemoryDescriptor *cur = _parent;
++ while (cur != NULL && count < 64) {
++ chain[count++] = cur;
++ IOSubMemoryDescriptor *sub = OSDynamicCast(IOSubMemoryDescriptor, cur);
++ cur = sub ? sub->_parent : NULL;
++ }
++ if (cur != NULL) {
++ return kIOReturnOverrun;
++ }
++
++ return el0IOMemoryDescriptorRedirectList(chain, count, safeTask, doRedirect);
++#else /* !__LP64__ */
+ return _parent->redirect( safeTask, doRedirect );
++#endif /* __LP64__ */
}
+ IOSubMemoryDescriptor *
+diff --git a/libkern/crypto/corecrypto_rand.c b/libkern/crypto/corecrypto_rand.c
+index d46815b..acea296 100644
+--- a/libkern/crypto/corecrypto_rand.c
++++ b/libkern/crypto/corecrypto_rand.c
+@@ -27,9 +27,19 @@
+ */
-@@ -3108,6 +3135,16 @@ pmap_create_options_internal(
- }
-
- p->ttep = ml_static_vtop((vm_offset_t)p->tte);
-+ if (pt_attr_root_level(pmap_get_pt_attr(p)) == PMAP_TT_L0_LEVEL) {
-+ /* LINUX64: the root already is the level-0 table TTBR0 walks from */
-+ p->hw_tte = p->tte;
-+ p->hw_ttep = p->ttep;
-+ for (i = 0; i < tte_index_max; i++) {
-+ p->tte[i] = ARM_TTE_TYPE_FAULT;
-+ }
-+ FLUSH_PTE();
-+ goto root_ready;
-+ }
- p->hw_tte = pmap_tt1_allocate(p, pmap_root_alloc_size(p), 0);
- if (!p->hw_tte) {
- pmap_tt1_deallocate(p, p->tte, pmap_root_alloc_size(p), 0);
-@@ -3129,6 +3166,7 @@ pmap_create_options_internal(
- p->hw_tte[0] = (p->ttep & ARM_TTE_TABLE_MASK) | ARM_TTE_TYPE_TABLE | ARM_TTE_VALID;
-
- FLUSH_PTE();
-+root_ready:
-
- /*
- * initialize the rest of the structure
-@@ -3406,6 +3444,10 @@ pmap_destroy_internal(
-
+ #include <libkern/crypto/crypto_internal.h>
++#include <linux64/linux64.h>
+ #include <corecrypto/ccrng.h>
++#include <string.h>
+ #include <libkern/crypto/rand.h>
++/*
++ * LINUX64 (xnulinux): until the corecrypto kext registers g_crypto_funcs (and on a hosted kernel without it), random
++ * bytes come from the host's generator (Linux's get_random_bytes, LINUX64_CALL_RANDOM). A context made before then
++ * holds nothing (linux64_rng_ctx_size).
++ */
++#define linux64_rng_fallback() (g_crypto_funcs == NULL && linux64_hook != 0)
++#define linux64_rng_ctx_size (2 * sizeof(uint64_t))
++
+ int
+ cc_rand_generate(void *out, size_t outlen)
+ {
+@@ -41,6 +51,9 @@ cc_rand_generate(void *out, size_t outlen)
+ if (rng_state != NULL) {
+ error = ccrng_generate(rng_state, outlen, out);
+ }
++ } else if (linux64_rng_fallback()) {
++ linux64_random(out, outlen);
++ error = 0;
+ }
-+ if (pmap->hw_tte == pmap->tte) {
-+ pmap->hw_tte = (tt_entry_t *) NULL; /* LINUX64: a level-0 root is both; free it once, below */
-+ pmap->hw_ttep = 0;
+ return error;
+@@ -58,6 +71,10 @@ crypto_random_generate(
+ void *random,
+ size_t random_size)
+ {
++ if (linux64_rng_fallback()) {
++ linux64_random(random, random_size);
++ return;
+ }
- if (pmap->tte) {
- pmap_tt1_deallocate(pmap, pmap->tte, pmap_root_alloc_size(pmap), 0);
- pmap->tte = (tt_entry_t *) NULL;
-@@ -12980,6 +13022,8 @@ pmap_user_va_bits(pmap_t pmap __unused)
- #if __ARM_MIXED_PAGE_SIZE__
- uint64_t tcr_value = pmap_get_pt_attr(pmap)->pta_tcr_value;
- return 64 - ((tcr_value >> TCR_T0SZ_SHIFT) & TCR_TSZ_MASK);
-+#elif !__ARM_16K_PG__ && !ARM_PARAMETERIZED_PMAP
-+ return 64 - T0SZ_HW; /* LINUX64: user pmaps walk from level 0 (pmap_pt_attr_4k_user) */
- #else
- return 64 - T0SZ_BOOT;
- #endif
-diff --git a/osfmk/arm/pmap/pmap_pt_geometry.h b/osfmk/arm/pmap/pmap_pt_geometry.h
-index fc64830..aaff3fb 100644
---- a/osfmk/arm/pmap/pmap_pt_geometry.h
-+++ b/osfmk/arm/pmap/pmap_pt_geometry.h
-@@ -169,7 +169,14 @@ extern const struct page_table_ops native_pt_ops;
- #else /* ARM_PARAMETERIZED_PMAP */
+ g_crypto_funcs->random_generate_fn(ctx, random, random_size);
+ }
- /* The page table attributes are fixed (to allow for const propagation) */
-+#if !__ARM_16K_PG__
-+/* LINUX64 (xnulinux): user pmaps walk from level 0 over 47 bits, the kernel pmap from level 1 (pmap.c, pmap_pt_attr_4k_user) */
-+extern const struct page_table_attr * const user_pt_attr;
-+extern const pmap_t kernel_pmap; /* as in vm/pmap.h, which not every includer of this header has */
-+#define pmap_get_pt_attr(pmap) ((pmap) == kernel_pmap ? native_pt_attr : user_pt_attr)
-+#else
- #define pmap_get_pt_attr(pmap) (native_pt_attr)
-+#endif
- #define pmap_get_pt_ops(pmap) (&native_pt_ops)
+@@ -67,12 +84,19 @@ crypto_random_uniform(
+ uint64_t bound,
+ uint64_t *random)
+ {
++ if (linux64_rng_fallback()) {
++ *random = linux64_random_uniform(bound);
++ return;
++ }
+ g_crypto_funcs->random_uniform_fn(ctx, bound, random);
+ }
- #endif /* ARM_PARAMETERIZED_PMAP */
-diff --git a/osfmk/arm/rtclock.c b/osfmk/arm/rtclock.c
-index a17a07d..bf9934d 100644
---- a/osfmk/arm/rtclock.c
-+++ b/osfmk/arm/rtclock.c
-@@ -38,6 +38,7 @@
- */
+ size_t
+ crypto_random_kmem_ctx_size(void)
+ {
++ if (linux64_rng_fallback()) {
++ return linux64_rng_ctx_size;
++ }
+ return g_crypto_funcs->random_kmem_ctx_size_fn();
+ }
- #include <mach/mach_types.h>
+@@ -80,5 +104,9 @@ void
+ crypto_random_kmem_init(
+ crypto_random_ctx_t ctx)
+ {
++ if (linux64_rng_fallback()) {
++ memset(ctx, 0, linux64_rng_ctx_size);
++ return;
++ }
+ g_crypto_funcs->random_kmem_init_fn(ctx);
+ }
+diff --git a/osfmk/arm/arm_init.c b/osfmk/arm/arm_init.c
+index ac1713e..6c10f36 100644
+--- a/osfmk/arm/arm_init.c
++++ b/osfmk/arm/arm_init.c
+@@ -1,4 +1,5 @@
+ #include <kern/boot_progress.h>
+#include <linux64/linux64.h>
+ /*
+ * Copyright (c) 2007-2024 Apple Inc. All rights reserved.
+ *
+@@ -228,6 +229,26 @@ extern vm_offset_t segLOWESTKC, segHIGHESTKC, segLOWESTROKC, segHIGHESTROKC;
+ extern vm_offset_t segLOWESTAuxKC, segHIGHESTAuxKC, segLOWESTROAuxKC, segHIGHESTROAuxKC;
+ extern vm_offset_t segLOWESTRXAuxKC, segHIGHESTRXAuxKC, segHIGHESTNLEAuxKC;
- #include <kern/clock.h>
- #include <kern/thread.h>
-@@ -327,6 +328,7 @@ rtclock_intr(__unused unsigned int is_user_context)
- struct arm_saved_state * regs;
- unsigned int user_mode;
- uintptr_t pc;
-+ linux64_count(LINUX64_CTR_RTCLOCK); /* LINUX64: for the host's monitor */
-
- #if XNU_NATIVE_DWC3_CONSOLE
- extern void unixnu_dwc3_poll(void);
-@@ -366,6 +368,15 @@ rtclock_intr(__unused unsigned int is_user_context)
- pc = 0;
- user_mode = 0;
- }
-+ uint64_t sample_fp = regs ? get_saved_state_fp(regs) : 0;
-+ if (regs == NULL && linux64_hook) {
-+ /*
-+ * LINUX64: hosted, a kernel-mode timer is delivered by a call from where XNU re-enables interrupts (or from idle),
-+ * not by an exception with a saved state: profile the caller (pc-sample charges it to the code that masked).
-+ */
-+ pc = (uintptr_t)__builtin_return_address(0);
-+ sample_fp = *(uint64_t *)__builtin_frame_address(0);
++/* 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_el0;
++unsigned int linux64_el0_caps;
++const unsigned int linux64_abi_version = LINUX64_ABI_VERSION;
++unsigned int linux64_host_abi_version;
++unsigned int linux64_vint[LINUX64_CPU_SLOTS];
++unsigned int linux64_ipi_pending[LINUX64_CPU_SLOTS];
++unsigned long linux64_dbg[LINUX64_NCOUNTERS];
++
++void linux64_el0_icache_flush(unsigned long va, unsigned long size);
++void
++linux64_el0_icache_flush(unsigned long va, unsigned long size)
++{
++ if (linux64_el0) {
++ linux64_call2(LINUX64_CALL_ICACHE_FLUSH, va, size);
+ }
- if (abstime >= cdp->rtcPop) {
- /* Log the interrupt service latency (-ve value expected by tool) */
- KDBG_RELEASE(DECR_TRAP_LATENCY | DBG_FUNC_NONE,
-@@ -375,7 +386,7 @@ rtclock_intr(__unused unsigned int is_user_context)
++}
++
+ static void
+ arm_slide_rebase_and_sign_image(void)
+ {
+@@ -285,10 +306,14 @@ arm_slide_rebase_and_sign_image(void)
+ * using hardcoded kernel link address
+ */
+ slide = (uintptr_t)k_mh - VM_KERNEL_LINK_ADDRESS;
++ if (linux64_hook) {
++ /* LINUX64: xnu.ko loaded, slid (load commands too) and signed the image already. */
++ slide = linux64_slide;
++ }
- /* bring-up profiling (boot-arg pc-sample, osfmk/kern/exception.c) */
- extern void virt_pc_sample(uint64_t pc, uint64_t fp, unsigned int user_mode, uint32_t decrementer, bool due);
-- virt_pc_sample(pc, regs ? get_saved_state_fp(regs) : 0, user_mode, cdp->cpu_decrementer, abstime >= cdp->rtcPop);
-+ virt_pc_sample(pc, sample_fp, user_mode, cdp->cpu_decrementer, abstime >= cdp->rtcPop);
+ /* rebase and sign jops */
+ static_kernelcache = &__thread_starts_sect_end[0] != &__thread_starts_sect_start[0];
+- if (static_kernelcache) {
++ if (static_kernelcache && !linux64_hook) {
+ 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 +366,28 @@ arm_auxkc_init(void *mh, void *base)
+ #endif /* defined(HAS_APPLE_PAC) */
+ }
- /* call the generic etimer */
- timer_intr(user_mode, pc);
-diff --git a/osfmk/arm64/arm_vm_init.c b/osfmk/arm64/arm_vm_init.c
-index f7f387e..cd928a3 100644
---- a/osfmk/arm64/arm_vm_init.c
-+++ b/osfmk/arm64/arm_vm_init.c
-@@ -28,6 +28,7 @@
++/*
++ * 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)
++{
++ struct linux64_assert_info a = { file, line, expr };
++ linux64_call(LINUX64_CALL_ASSERT, &a);
++}
++
+ /*
+ * Routine: arm_init
+ * Function: Runs on the boot CPU, once, on entry from iBoot.
+@@ -361,6 +408,10 @@ arm_init(
+ port_crumb = 100;
+ arm_slide_rebase_and_sign_image();
+ port_crumb = 101;
++ if (linux64_el0 && linux64_host_abi_version != LINUX64_ABI_VERSION) {
++ panic("LINUX64_ABI_VERSION handshake failed: host=%u kernel=%u",
++ linux64_host_abi_version, LINUX64_ABI_VERSION);
++ }
- extern volatile unsigned long long port_crumb; /* port bring-up breadcrumb (link_compat.c) */
- #include <mach_kdp.h>
-+#include <linux64/linux64.h>
- #include <debug.h>
+ arm_static_if_init(args);
+ port_crumb = 102;
+@@ -431,6 +482,17 @@ arm_init(
+ /* Native non-Apple 4K builds expose the hardware page size at any RAM size. */
+ #if !defined(APPLE_ARM64_ARCH_FAMILY) && !__ARM_16K_PG__
+ PAGE_SHIFT_CONST = ARM_PGSHIFT;
++ /*
++ * LINUX64 (xnulinux): hosted, the host's 4 KB translation granule is the hardware page; boot-arg linux64_vm16k=1
++ * makes the kernel's VM page 16 KB over it (PAGE_RATIO 4, as Apple's 4 KB-granule SoCs run with more than 1 GB):
++ * a quarter of the page faults, and the page size macOS binaries are built for.
++ */
++ {
++ uint32_t vm16k = 0;
++ if (linux64_hook && PE_parse_boot_argn("linux64_vm16k", &vm16k, sizeof(vm16k)) && vm16k) {
++ PAGE_SHIFT_CONST = PAGE_MAX_SHIFT;
++ }
++ }
+ #else
+ /*
+ * Select the advertised kernel page size.
+@@ -554,7 +616,9 @@ arm_init(
+ PE_parse_boot_argn("immediate_NMI", &force_immediate_debug_halt, sizeof(force_immediate_debug_halt));
- #include <kern/assert.h>
-@@ -1089,7 +1090,8 @@ arm_vm_page_granular_helper(vm_offset_t start, vm_offset_t _end, vm_offset_t va,
- /*
- * Set the 'guarded page' flag to enable ARM BTI enforcement.
- */
-- if (guarded) {
-+ /* LINUX64: Linux enables SCTLR_EL1.BT1, and this kernel is not built with BTI landing pads. */
-+ if (guarded && !linux64_hook) {
- ptmp |= ARM_PTE_GP;
- }
- #endif /* BTI_ENFORCED */
-@@ -2194,14 +2196,28 @@ arm_vm_init(uint64_t memory_size, boot_args * args)
+ #if __ARM_PAN_AVAILABLE__
+- __builtin_arm_wsr("pan", 1);
++ if (!linux64_el0) {
++ __builtin_arm_wsr("pan", 1);
++ }
+ #endif /* __ARM_PAN_AVAILABLE__ */
- arm_vm_physmap_init(args);
- port_crumb = 38;
-- set_mmu_ttb_alternate(cpu_ttep & TTBR_BADDR_MASK);
-+ {
-+ if (linux64_hook) {
-+ /*
-+ * LINUX64 (xnulinux): TTBR1 is Linux's. The host installs XNU's kernel L1 entries
-+ * (the kernel VA range only) into Linux's top-level L1 table; TTBR0 stays Linux's.
-+ */
-+ linux64_call(LINUX64_CALL_KERNEL_TABLES, cpu_tte);
-+ } else {
-+ set_mmu_ttb_alternate(cpu_ttep & TTBR_BADDR_MASK);
-+ }
+ #if HAS_MTE
+@@ -732,7 +796,9 @@ arm_init_cpu(
+ uint64_t __unused hib_header_phys)
+ {
+ #if __ARM_PAN_AVAILABLE__
+- __builtin_arm_wsr("pan", 1);
++ if (!linux64_el0) {
++ __builtin_arm_wsr("pan", 1);
+ }
- port_crumb = 39;
+ #endif
- #if XNU_MONITOR
- ml_enable_monitor();
+ #ifdef __arm64__
+@@ -876,7 +942,9 @@ arm_init_idle_cpu(
+ cpu_data_t *cpu_data_ptr)
+ {
+ #if __ARM_PAN_AVAILABLE__
+- __builtin_arm_wsr("pan", 1);
++ if (!linux64_el0) {
++ __builtin_arm_wsr("pan", 1);
++ }
#endif
-- set_mmu_ttb(invalid_ttep & TTBR_BADDR_MASK);
-+ {
-+ if (!linux64_hook) {
-+ set_mmu_ttb(invalid_ttep & TTBR_BADDR_MASK);
-+ }
+ machine_set_current_thread(cpu_data_ptr->cpu_active_thread);
+diff --git a/osfmk/arm/commpage/commpage.c b/osfmk/arm/commpage/commpage.c
+index 1f672e9..49d6024 100644
+--- a/osfmk/arm/commpage/commpage.c
++++ b/osfmk/arm/commpage/commpage.c
+@@ -155,8 +155,9 @@ commpage_populate(void)
+ *((uint8_t*)(_COMM_PAGE_USER_PAGE_SHIFT_32_LEGACY + _COMM_PAGE_RW_OFFSET)) = (uint8_t) page_shift_user32;
+ *((uint8_t*)(_COMM_PAGE_USER_PAGE_SHIFT_32 + _COMM_PAGE_RO_OFFSET)) = (uint8_t) page_shift_user32;
+ #if !defined(APPLE_ARM64_ARCH_FAMILY) && !__ARM_16K_PG__
+- *((uint8_t*)(_COMM_PAGE_USER_PAGE_SHIFT_64_LEGACY + _COMM_PAGE_RW_OFFSET)) = (uint8_t) FOURK_PAGE_SHIFT;
+- *((uint8_t*)(_COMM_PAGE_USER_PAGE_SHIFT_64 + _COMM_PAGE_RO_OFFSET)) = (uint8_t) FOURK_PAGE_SHIFT;
++ /* LINUX64: user maps take the kernel's VM page (mach_loader.c) */
++ *((uint8_t*)(_COMM_PAGE_USER_PAGE_SHIFT_64_LEGACY + _COMM_PAGE_RW_OFFSET)) = (uint8_t) PAGE_SHIFT;
++ *((uint8_t*)(_COMM_PAGE_USER_PAGE_SHIFT_64 + _COMM_PAGE_RO_OFFSET)) = (uint8_t) PAGE_SHIFT;
+ #else
+ *((uint8_t*)(_COMM_PAGE_USER_PAGE_SHIFT_64_LEGACY + _COMM_PAGE_RW_OFFSET)) = (uint8_t) SIXTEENK_PAGE_SHIFT;
+ *((uint8_t*)(_COMM_PAGE_USER_PAGE_SHIFT_64 + _COMM_PAGE_RO_OFFSET)) = (uint8_t) SIXTEENK_PAGE_SHIFT;
+@@ -846,6 +847,11 @@ commpage_init_arm_optional_features_misc(__unused uint64_t *commpage_bits)
+ static void
+ commpage_init_arm_optional_features(uint64_t *commpage_bits)
+ {
++ extern unsigned int linux64_el0;
++ if (linux64_el0) {
++ commpage_init_arm_optional_features_fpcr(commpage_bits);
++ return;
+ }
+ commpage_init_arm_optional_features_isar0(commpage_bits);
+ commpage_init_arm_optional_features_isar1(commpage_bits);
+ commpage_init_arm_optional_features_isar2();
+diff --git a/osfmk/arm/cpu_data.h b/osfmk/arm/cpu_data.h
+index 743117b..62a5a9a 100644
+--- a/osfmk/arm/cpu_data.h
++++ b/osfmk/arm/cpu_data.h
+@@ -61,8 +61,9 @@ current_thread_fast(void)
+ *
+ * and ignores the "attribute const", so do it the "dumb" way.
+ */
++ /* LINUX64 (xnulinux): TPIDR_EL1 belongs to Linux (or is EL1-only); XNU's kernel keeps its thread pointer in TPIDR_EL0 */
+ unsigned long result;
+- __asm__ ("mrs %0, TPIDR_EL1" : "=r" (result));
++ __asm__ ("mrs %0, TPIDR_EL0" : "=r" (result));
+ return __unsafe_forge_single(thread_t, result);
+ #else
+ // TPIDRPRW
+@@ -101,7 +102,7 @@ current_thread_volatile(void)
+ */
+ #if defined(__arm64__)
+ unsigned long result;
+- __asm__ volatile ("mrs %0, TPIDR_EL1" : "=r" (result));
++ __asm__ volatile ("mrs %0, TPIDR_EL0" : "=r" (result)); /* LINUX64: see current_thread_fast */
+ return __unsafe_forge_single(thread_t, result);
+ #else
+ // TPIDRPRW
+@@ -114,7 +115,21 @@ current_thread_volatile(void)
+ static inline vm_offset_t
+ exception_stack_pointer(void)
+ {
+- vm_offset_t result = 0;
++ extern unsigned int linux64_el0;
++ vm_offset_t result = 0, spsel;
++ if (linux64_el0) {
++ __asm__ volatile ("mov %0, sp" : "=r" (result));
++ return result;
++ }
++ /*
++ * LINUX64 (xnulinux): hosted XNU runs on Linux's SP_EL1 stack, and SP_EL0 is
++ * Linux's `current`; never flip SPSel. When already on SP_EL1, sp is the answer.
++ */
++ __asm__ volatile ("mrs %0, SPSel" : "=r" (spsel));
++ if (spsel & 1) {
++ __asm__ volatile ("mov %0, sp" : "=r" (result));
++ return result;
++ }
+ __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
- flush_mmu_tlb();
- port_crumb = 40;
-@@ -2267,9 +2283,14 @@ arm_vm_init(uint64_t memory_size, boot_args * args)
- vm_kernel_etext = segTEXTEXECB + segSizeTEXTEXEC;
- vm_kernel_slid_top = vm_slinkedit;
- } else {
-- assert(segDATACONSTB == segTEXTB + segSizeTEXT);
-- assert(segTEXTEXECB == segDATACONSTB + segSizeDATACONST);
-- vm_kernel_etext = segTEXTB + segSizeTEXT + segSizeDATACONST + segSizeTEXTEXEC;
-+ if (linux64_hook) {
-+ /* LINUX64: this kernel is linked with the KC segment layout (k27): segments are not adjacent. */
-+ vm_kernel_etext = segTEXTEXECB + segSizeTEXTEXEC;
-+ } else {
-+ assert(segDATACONSTB == segTEXTB + segSizeTEXT);
-+ assert(segTEXTEXECB == segDATACONSTB + segSizeDATACONST);
-+ vm_kernel_etext = segTEXTB + segSizeTEXT + segSizeDATACONST + segSizeTEXTEXEC;
-+ }
- vm_kernel_slid_top = vm_prelink_einfo;
- }
-
-diff --git a/osfmk/arm64/asm.h b/osfmk/arm64/asm.h
-index 84deb3f..2579711 100644
---- a/osfmk/arm64/asm.h
-+++ b/osfmk/arm64/asm.h
-@@ -135,7 +135,7 @@
- .endmacro
-
- .macro READ_THREAD
-- mrs $0, TPIDR_EL1
-+ mrs $0, TPIDRRO_EL0
- .endmacro
+-#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(); })
- .macro BRANCH_EXTERN
-diff --git a/osfmk/arm64/cpu.c b/osfmk/arm64/cpu.c
-index d10d7a1..0c3e1ed 100644
---- a/osfmk/arm64/cpu.c
-+++ b/osfmk/arm64/cpu.c
-@@ -32,6 +32,7 @@
- */
+ #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
++++ b/osfmk/arm/machdep_call.c
+@@ -38,6 +38,7 @@
- #include <pexpert/arm64/board_config.h>
+ #include <kern/thread.h>
+ #include <mach/mach_types.h>
+#include <linux64/linux64.h>
- #include <kern/kalloc.h>
- #include <kern/machine.h>
- #include <kern/cpu_number.h>
-@@ -100,6 +101,7 @@ extern void __attribute__((noreturn)) arm64_prepare_for_sleep(boolean_t deep_sle
- extern void __attribute__((noreturn)) arm64_prepare_for_sleep(boolean_t deep_sleep);
- #endif
- extern void arm64_force_wfi_clock_gate(void);
-+extern void rtclock_intr(unsigned int);
- #if defined(APPLETYPHOON)
- // <rdar://problem/15827409>
- extern void typhoon_prepare_for_wfi(void);
-@@ -430,6 +432,11 @@ wfe_to_deadline_or_interrupt(uint32_t cid, uint64_t wfe_deadline, cpu_data_t *cd
- * another core/cluster in a powergated state.
- * Hence, optionally unmask IRQs+FIQs across WFE.
- */
-+ {
-+ if (linux64_hook) {
-+ unmask = false; /* LINUX64: never unmask hardware IRQs while hosted */
-+ }
+ #include <arm/machdep_call.h>
+ #if __arm64__
+ #include <arm64/machine_machdep.h>
+@@ -49,6 +50,10 @@ uintptr_t
+ get_tpidrro(void)
+ {
+ uintptr_t uthread;
++ if (linux64_hook) {
++ /* LINUX64 (xnulinux): in the kernel TPIDRRO_EL0 is the thread pointer; EL0 gets cthread_self on return */
++ return current_thread()->machine.cthread_self;
+ }
- if (unmask) {
- /* Latch SW IRQ+FIQ counter prior to unmasking
- * interrupts.
-@@ -494,6 +501,37 @@ wfe_to_deadline_or_interrupt(uint32_t cid, uint64_t wfe_deadline, cpu_data_t *cd
- return ipending || (nirqc != irqc);
+ __asm__ volatile ("mrs %0, TPIDRRO_EL0" : "=r" (uthread));
+ return uthread;
+ }
+@@ -56,6 +61,9 @@ get_tpidrro(void)
+ void
+ set_tpidrro(uintptr_t uthread)
+ {
++ if (linux64_hook) {
++ return; /* LINUX64: loaded from cthread_self on the way back to user space (linux64_el0_run) */
++ }
+ __asm__ volatile ("msr TPIDRRO_EL0, %0" : : "r" (uthread));
}
-+/*
-+ * LINUX64 (xnulinux): hosted, idle goes straight to the host, which runs Linux until XNU's next timer deadline and
-+ * comes back; the due timer is then delivered here as its interrupt would be. No WFE/WFI and no timer interrupt of
-+ * XNU's own apply (idle_enable stays FALSE without the CPU kext: cpu_machine_init never runs).
-+ */
-+static void
-+linux64_cpu_idle(cpu_data_t *cpu_data_ptr)
-+{
-+ uint64_t now = mach_absolute_time();
-+ uint64_t deadline = cpu_data_ptr->rtcPop;
-+ uint64_t ns = 0; /* a timer already due: no sleep, only let Linux take its interrupts */
-+
-+ linux64_count(LINUX64_CTR_CPU_IDLE);
-+ if (deadline == 0 || deadline == EndOfAllTime) {
-+ ns = NSEC_PER_MSEC; /* no timer armed: check the run queue again in 1 ms */
-+ } else if (deadline > now) {
-+ /* relative: XNU's timebase (mach_absolute_time) is offset from the host's counter */
-+ absolutetime_to_nanoseconds(deadline - now, &ns);
+diff --git a/osfmk/arm/machine_cpuid.c b/osfmk/arm/machine_cpuid.c
+index 128d5f6..b655090 100644
+--- a/osfmk/arm/machine_cpuid.c
++++ b/osfmk/arm/machine_cpuid.c
+@@ -30,6 +30,7 @@
+ #include <machine/atomic.h>
+ #include <machine/machine_cpuid.h>
+ #include <arm/cpu_data_internal.h>
++#include <linux64/linux64.h>
+
+ static arm_mvfp_info_t cpuid_mvfp_info;
+ static arm_debug_info_t cpuid_debug_info;
+@@ -38,6 +39,9 @@ MARK_AS_FIXUP_TEXT uint32_t
+ machine_read_midr(void)
+ {
+ uint64_t midr;
++ if (linux64_el0) {
++ return 0x410fd034U;
+ }
-+ 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 */
+ __asm__ volatile ("mrs %0, MIDR_EL1" : "=r" (midr));
+
+ return (uint32_t)midr;
+@@ -47,6 +51,9 @@ uint32_t
+ machine_read_clidr(void)
+ {
+ uint64_t clidr;
++ if (linux64_el0) {
++ return 0x09200023U;
+ }
-+ linux64_count(LINUX64_CTR_HOST_IDLE);
-+ 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);
-+}
-+
- /*
- * Routine: cpu_idle
- * Function:
-@@ -506,6 +544,9 @@ cpu_idle(void)
- uint64_t new_idle_timeout_ticks = 0x0ULL, lastPop;
- bool idle_disallowed = false;
+ __asm__ volatile ("mrs %0, CLIDR_EL1" : "=r" (clidr));
-+ if (linux64_hook) {
-+ linux64_cpu_idle(cpu_data_ptr);
+ return (uint32_t)clidr;
+@@ -56,6 +63,9 @@ uint32_t
+ machine_read_ccsidr(void)
+ {
+ uint64_t ccsidr;
++ if (linux64_el0) {
++ return 0x700fe01aU;
+ }
- 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 */
+ __asm__ volatile ("mrs %0, CCSIDR_EL1" : "=r" (ccsidr));
-- 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);
-+ }
+ return (uint32_t)ccsidr;
+@@ -64,6 +74,9 @@ machine_read_ccsidr(void)
+ void
+ machine_write_csselr(csselr_cache_level level, csselr_cache_type type)
+ {
++ if (linux64_el0) {
++ return;
++ }
+ uint64_t csselr = (uint64_t)level | (uint64_t)type;
+ __asm__ volatile ("msr CSSELR_EL1, %0" : : "r" (csselr));
- }
- }
-diff --git a/osfmk/arm64/cswitch.s b/osfmk/arm64/cswitch.s
-index a191eb3..035b1a8 100644
---- a/osfmk/arm64/cswitch.s
-+++ b/osfmk/arm64/cswitch.s
-@@ -185,7 +185,7 @@
- * arg2 - Scratch register
+@@ -73,6 +86,9 @@ machine_write_csselr(csselr_cache_level level, csselr_cache_type type)
+ void
+ machine_do_debugid(void)
+ {
++ if (linux64_el0) {
++ return;
++ }
+ arm_cpuid_id_aa64dfr0_el1 id_dfr0;
+
+ /* read ID_AA64DFR0_EL1 */
+diff --git a/osfmk/arm/machine_routines_common.c b/osfmk/arm/machine_routines_common.c
+index b65f76c..2d18613 100644
+--- a/osfmk/arm/machine_routines_common.c
++++ b/osfmk/arm/machine_routines_common.c
+@@ -27,6 +27,7 @@
*/
- .macro set_thread_registers
-- msr TPIDR_EL1, $0 // Write new thread pointer to TPIDR_EL1
-+ msr TPIDRRO_EL0, $0 // LINUX64: the thread pointer (TPIDR_EL1 is Linux's; EL0's TPIDRRO is set on return to user space)
- ldr $1, [$0, ACT_CPUDATAP]
- str $0, [$1, CPU_ACTIVE_THREAD]
-@@ -217,8 +217,6 @@
- bfi $1, $2, #0, #MACHDEP_TPIDR_CPU_DATA_COUNT
- msr TPIDR_EL0, $1 // ... into the lower bits.
+ #include <arm/machine_cpu.h>
++#include <linux64/linux64.h>
+ #include <arm/cpu_internal.h>
+ #include <arm/cpuid.h>
+ #include <arm/cpuid_internal.h>
+@@ -1094,6 +1095,59 @@ ml_set_interrupts_enabled_with_debug(boolean_t enable, boolean_t __unused debug)
-- ldr $1, [$0, TH_CTH_SELF] // Get cthread pointer
-- msr TPIDRRO_EL0, $1
-
- ldr $1, [$0, TH_THREAD_ID] // Save the bottom 32-bits of the thread ID into
- msr CONTEXTIDR_EL1, $1 // CONTEXTIDR_EL1 (top 32-bits are RES0).
-@@ -333,7 +331,7 @@ LEXT(machine_load_context)
-
- LEXT(Call_continuation)
- ARM64_PROLOG
-- mrs x4, TPIDR_EL1 // Get the current thread pointer
-+ mrs x4, TPIDRRO_EL0 // Get the current thread pointer
-
- /* ARM64_TODO arm loads the kstack top instead of arg4. What should we use? */
- LOAD_KERN_STACK_TOP dst=x5, src=x4, tmp=x6
-@@ -359,7 +357,7 @@ LEXT(Call_continuation)
- #else
- blr x20 // Branch to the continuation
- #endif
-- mrs x0, TPIDR_EL1 // Get the current thread pointer
-+ mrs x0, TPIDRRO_EL0 // Get the current thread pointer
- b EXT(thread_terminate) // Kill the thread
-
-
-@@ -394,7 +392,7 @@ Lswitch_threads:
-
- LEXT(Shutdown_context)
- ARM64_PROLOG
-- mrs x10, TPIDR_EL1 // Get thread pointer
-+ mrs x10, TPIDRRO_EL0 // Get thread pointer
- LOAD_KERN_STACK_TOP dst=x11, src=x10, tmp=x12 // Get the top of the kernel stack
- save_general_registers x11, 12
- msr DAIFSet, #(DAIFSC_STANDARD_DISABLE) // Disable interrupts
-@@ -412,7 +410,7 @@ LEXT(Shutdown_context)
-
- LEXT(Idle_context)
- ARM64_PROLOG
-- mrs x0, TPIDR_EL1 // Get thread pointer
-+ mrs x0, TPIDRRO_EL0 // Get thread pointer
- LOAD_KERN_STACK_TOP dst=x1, src=x0, tmp=x2 // Get the top of the kernel stack
- save_general_registers x1, 2
- LOAD_INT_STACK_THREAD dst=x2, src=x0, tmp=x1
-@@ -429,7 +427,7 @@ LEXT(Idle_context)
+ thread = current_thread();
- LEXT(Idle_load_context)
- ARM64_PROLOG
-- mrs x0, TPIDR_EL1 // Get thread pointer
-+ mrs x0, TPIDRRO_EL0 // Get thread pointer
- LOAD_KERN_STACK_TOP dst=x1, src=x0, tmp=x2 // Get the top of the kernel stack
- load_general_registers x1, 2
- set_process_dependent_keys_and_sync_context x0, x1, x2, x3, w4
-@@ -444,3 +442,199 @@ LEXT(machine_set_current_thread)
++ {
++ /*
++ * 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 (per CPU); timer "interrupts" are delivered from cpu_idle.
++ */
++ if (linux64_hook) {
++ 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; and take an
++ * IPI another CPU sent.
++ */
++ static uint64_t linux64_last_kyield[LINUX64_CPU_SLOTS];
++ uint64_t now = mach_absolute_time();
++ 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;
++ /*
++ * Not with preemption off (a spinlock held): Linux may reschedule this CPU's thread
++ * away for as long as it likes, and every other CPU spins on the lock until XNU's
++ * ticket-lock timeout panics.
++ */
++ if (get_preemption_level() == 0) {
++ linux64_call2(LINUX64_CALL_PREEMPTED, 1, 0);
++ }
++ if (cdp->rtcPop != 0 && cdp->rtcPop != 0xFFFFFFFFFFFFFFFFULL && mach_absolute_time() >= cdp->rtcPop) {
++ cdp->cpu_decrementer = -1;
++ rtclock_intr(FALSE);
++ }
++ }
++ linux64_ipi_take();
++ }
++ if (get_preemption_level() == 0) {
++ while (thread->machine.CpuDatap->cpu_pending_ast & AST_URGENT) {
++ ast_taken_kernel();
++ }
++ }
++ /* 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[slot] = 0;
++ }
++ return was;
++ }
++ }
++
+ state = __builtin_arm_rsr("DAIF");
+ if (__improbable(!(state & DAIF_DEBUGF))) {
+@@ -1366,6 +1420,68 @@ ml_early_cpu_max_number(void)
+ return ml_get_max_cpu_number();
+ }
- /* vim: set ts=4: */
-+
+/*
-+ * LINUX64 (xnulinux): user space while hosted. linux64_el0_run(ss) enters EL0 with the user state in ss
-+ * (IRQs stay masked at EL0), on this CPU, with VBAR_EL1 pointing at linux64_el0_vectors and SP_EL0 holding the
-+ * user sp. What the kernels need back on the next exception from EL0 (XNU's thread pointer, which TPIDRRO_EL0 holds in
-+ * the kernel and the user's TSD at EL0; Linux's vectors, its `current` in SP_EL0, its shadow call stack in x18 and
-+ * SCTLR_EL1) goes in a block at the top of the thread's kernel stack, where SP_EL1 points at that exception: per thread,
-+ * so per CPU. The exception builds a register frame below it, puts all that back and calls
-+ * linux64_el0_exception(frame) (sleh.c), which hands it to sleh_synchronous and returns to user space again.
++ * 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.
+ */
-+#define LINUX64_EL0_BLOCK 64 // thread, SP_EL0, VBAR_EL1, x18, SCTLR_EL1
-+#define LINUX64_EL0_FRAME (36 * 8 + 528) // struct linux64_el0_frame (sleh.c)
++/*
++ * 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();
+
-+ .text
-+ .align 2
-+ .globl EXT(linux64_el0_run)
-+LEXT(linux64_el0_run)
-+ ARM64_PROLOG
-+ mrs x11, TPIDRRO_EL0 // this CPU's thread
-+ LOAD_KERN_STACK_TOP dst=x12, src=x11, tmp=x13
-+ sub x15, x12, #LINUX64_EL0_BLOCK
-+ str x11, [x15, #0]
-+ mrs x10, SP_EL0
-+ str x10, [x15, #8]
-+ mrs x10, VBAR_EL1
-+ str x10, [x15, #16]
-+ str x18, [x15, #24]
-+ mrs x10, SCTLR_EL1
-+ str x10, [x15, #32]
-+ adrp x10, EXT(linux64_el0_vectors)@page
-+ add x10, x10, EXT(linux64_el0_vectors)@pageoff
-+ msr VBAR_EL1, x10
-+ ldr x10, [x0, SS64_SP]
-+ msr SP_EL0, x10
-+ ldr x10, [x0, SS64_PC]
-+ msr ELR_EL1, x10
-+ ldr w10, [x0, SS64_CPSR]
-+ orr w10, w10, #0x40 // FIQ stays masked at EL0 while hosted; a (Linux) IRQ preempts user code
-+ msr SPSR_EL1, x10
-+ // the user's NEON/FP state (arm_context_t ns, right after ss): upcalls may let Linux schedule, which reuses the registers
-+ add x9, x0, NS64_Q0
-+ ldp q0, q1, [x9, #0]
-+ ldp q2, q3, [x9, #32]
-+ ldp q4, q5, [x9, #64]
-+ ldp q6, q7, [x9, #96]
-+ ldp q8, q9, [x9, #128]
-+ ldp q10, q11, [x9, #160]
-+ ldp q12, q13, [x9, #192]
-+ ldp q14, q15, [x9, #224]
-+ ldp q16, q17, [x9, #256]
-+ ldp q18, q19, [x9, #288]
-+ ldp q20, q21, [x9, #320]
-+ ldp q22, q23, [x9, #352]
-+ ldp q24, q25, [x9, #384]
-+ ldp q26, q27, [x9, #416]
-+ ldp q28, q29, [x9, #448]
-+ ldp q30, q31, [x9, #480]
-+ ldr w10, [x9, #512]
-+ msr FPSR, x10
-+ ldr w10, [x9, #516]
-+ msr FPCR, x10
-+ mov sp, x15 // the next exception from EL0 starts below the block
-+ ldr x10, [x11, TH_CTH_SELF] // the user's TSD (Darwin reads it from TPIDRRO_EL0)
-+ msr TPIDRRO_EL0, x10
++ 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);
+ /*
-+ * x1: JOP off for this thread (arm64, not arm64e): EnIA (31) and EnDA (27) off at EL0. Only after the last
-+ * kernel pointer authentication (LOAD_KERN_STACK_TOP authenticates; with EnDA off it would trap to brk).
++ * Spinning with XNU's interrupts enabled, a CPU takes another CPU's IPI on hardware (its FIQ): the other may be
++ * waiting for exactly that (a cross-call's acknowledgment) before it lets go of what this one spins on. Take a
++ * pending one here as the FIQ would, interrupts off around the handler; no AST, no context switch.
+ */
-+ cbz x1, 1f
-+ mrs x10, SCTLR_EL1
-+ mov x11, #((1 << 31) | (1 << 27))
-+ bic x10, x10, x11
-+ msr SCTLR_EL1, x10
-+1:
-+ isb
-+ add x30, x0, SS64_X0
-+ ldp x2, x3, [x30, #16]
-+ ldp x4, x5, [x30, #32]
-+ ldp x6, x7, [x30, #48]
-+ ldp x8, x9, [x30, #64]
-+ ldp x10, x11, [x30, #80]
-+ ldp x12, x13, [x30, #96]
-+ ldp x14, x15, [x30, #112]
-+ ldp x16, x17, [x30, #128]
-+ ldp x18, x19, [x30, #144]
-+ ldp x20, x21, [x30, #160]
-+ ldp x22, x23, [x30, #176]
-+ ldp x24, x25, [x30, #192]
-+ ldp x26, x27, [x30, #208]
-+ ldp x28, x29, [x30, #224]
-+ ldp x0, x1, [x30, #0]
-+ ldr x30, [x30, #240]
-+ eret
++ if (linux64_vint[slot] && getCpuDatap()->cpu_int_state == NULL) {
++ linux64_vint[slot] = 0;
++ linux64_ipi_take();
++ linux64_vint[slot] = 1;
++ }
++}
+
-+ .text
-+ .align 11
-+ .globl EXT(linux64_el0_vectors)
-+LEXT(linux64_el0_vectors)
-+ .rept 8 // current EL (SP0, SPx): not expected while at EL0
-+ b Llinux64_el0_bad
-+ .align 7
-+ .endr
-+ b Llinux64_el0_entry // lower EL, AArch64: sync
-+ .align 7
-+ b Llinux64_el0_irq // IRQ: the host's interrupt arrived while user code ran
-+ .align 7
-+ .rept 2 // FIQ, SError
-+ b Llinux64_el0_entry
-+ .align 7
-+ .endr
-+ .rept 4 // lower EL, AArch32
-+ b .
-+ .align 7
-+ .endr
++void
++linux64_ipi_take(void)
++{
++ unsigned int slot = linux64_cpu_slot();
+
-+Llinux64_el0_bad: // note it for the monitor (linux64_dbg[14] = ESR) and stop here
-+ adrp x9, _linux64_dbg@PAGE
-+ add x9, x9, _linux64_dbg@PAGEOFF
-+ mrs x10, ESR_EL1
-+ str x10, [x9, #112]
-+ b .
++ if (os_atomic_load(&linux64_ipi_pending[slot], relaxed) && os_atomic_xchg(&linux64_ipi_pending[slot], 0, acquire)) {
++ cpu_signal_handler();
++ }
++}
+
-+Llinux64_el0_irq: // as an exception, with ESR = ~0 (LINUX64_EL0_ESR_IRQ: no ESR has bits 63:32 set)
++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 +1500,12 @@ ml_wait_max_cpus(void)
+ {
+ assert(lockdown_done);
+ lck_mtx_lock(&max_cpus_lock);
++ {
++ /* LINUX64 (xnulinux): hosted without the CPU kext that calls ml_set_max_cpus(); one CPU, known now. */
++ if (linux64_hook) {
++ max_cpus_initialized = MAX_CPUS_SET;
++ }
++ }
+ while (max_cpus_initialized != MAX_CPUS_SET) {
+ max_cpus_initialized = MAX_CPUS_WAIT;
+ lck_mtx_sleep(&max_cpus_lock, LCK_SLEEP_DEFAULT, &max_cpus_initialized, THREAD_UNINT);
+diff --git a/osfmk/arm/pmap/pmap.c b/osfmk/arm/pmap/pmap.c
+index 79d0bc1..40de86f 100644
+--- a/osfmk/arm/pmap/pmap.c
++++ b/osfmk/arm/pmap/pmap.c
+@@ -51,6 +51,7 @@
+ #include <os/overflow.h>
+
+ #include <vm/pmap.h>
++#include <linux64/linux64.h>
+ #include <vm/pmap_cs.h>
+ #include <vm/vm_map_xnu.h>
+ #include <vm/vm_kern.h>
+@@ -327,6 +328,32 @@ const struct page_table_attr * const native_pt_attr = &pmap_pt_attr_16k;
+ const struct page_table_attr * const native_pt_attr = &pmap_pt_attr_4k;
+ #endif /* !__ARM_16K_PG__ */
+
++#if !__ARM_16K_PG__ && !ARM_PARAMETERIZED_PMAP
++/*
++ * LINUX64 (xnulinux): user pmaps of a 4 KiB build walk from level 0 and span the 47 bits TTBR0 runs with (T0SZ_HW), as a macOS
++ * userland expects (ThreadSanitizer's shadow, nano malloc and MACH_VM_MAX_ADDRESS all sit above the 39 bits a level-1 root reaches).
++ * The kernel pmap keeps pmap_pt_attr_4k (TTBR1, level-1 root).
++ */
++const struct page_table_attr pmap_pt_attr_4k_user = {
++ .pta_level_info = pmap_table_level_info_4k,
++ .pta_root_level = PMAP_TT_L0_LEVEL,
++ .pta_commpage_level = PMAP_TT_L1_LEVEL,
++ .pta_max_level = PMAP_TT_L3_LEVEL,
++ .pta_ops = &native_pt_ops,
++ .ap_ro = ARM_PTE_AP(AP_RORO),
++ .ap_rw = ARM_PTE_AP(AP_RWRW),
++ .ap_rona = ARM_PTE_AP(AP_RONA),
++ .ap_rwna = ARM_PTE_AP(AP_RWNA),
++ .ap_xn = ARM_PTE_PNX | ARM_PTE_NX,
++ .ap_x = ARM_PTE_PNX,
++ .pta_page_size = 4096,
++ .pta_pagezero_size = 4096,
++ .pta_page_shift = 12,
++ .pta_va_valid_mask = (1ULL << (64 - T0SZ_HW)) - 1,
++};
++const struct page_table_attr * const user_pt_attr = &pmap_pt_attr_4k_user;
++#endif /* !__ARM_16K_PG__ && !ARM_PARAMETERIZED_PMAP */
++
+
+ #if DEVELOPMENT || DEBUG
+ int vm_footprint_suspend_allowed = 1;
+@@ -520,7 +547,7 @@ _Static_assert((ARM64_MAX_OFFSET_DEVICE_LARGE > ARM64_MIN_MAX_ADDRESS) && (ARM64
+ _Static_assert((ARM64_MAX_OFFSET_DEVICE_SMALL > ARM64_MIN_MAX_ADDRESS) && (ARM64_MAX_OFFSET_DEVICE_SMALL <= MACH_VM_MAX_ADDRESS),
+ "Small device address space size outside allowable range");
+
+-# ifdef XNU_TARGET_OS_OSX
++# if defined(XNU_TARGET_OS_OSX) || !__ARM_16K_PG__ /* LINUX64: macOS userland gets the whole 47-bit space by default */
+ SECURITY_READ_ONLY_LATE(vm_map_offset_t) arm64_pmap_max_offset_default = MACH_VM_MAX_ADDRESS;
+ # else
+ SECURITY_READ_ONLY_LATE(vm_map_offset_t) arm64_pmap_max_offset_default = 0x0;
+@@ -635,6 +662,145 @@ pte_is_xs(const pt_attr_t *pt_attr, pt_entry_t pte)
+ arm64_sync_tlb(strong); \
+ }
+
++static inline void
++linux64_el0_mirror_pte(pmap_t pmap, vm_map_address_t va, pt_entry_t pte, uint64_t size)
++{
++ if (!linux64_el0 || !pmap || !size) {
++ return;
++ }
++ __builtin_arm_dmb(DMB_ISH);
++ if (pmap == kernel_pmap) {
++ if (physmap_end > physmap_base && va >= physmap_base && va < physmap_end) {
++ return;
++ }
++ struct linux64_map_req req = { .va = va, .size = size };
++ if (pte_is_valid(pte)) {
++ pmap_paddr_t pa = pte_to_pa(pte);
++ if (pa_valid(pa)) {
++ req.pa = pa;
++ req.prot = LINUX64_PROT_READ;
++ if ((pte & ARM_PTE_APMASK) == ARM_PTE_AP(AP_RWNA) ||
++ (pte & ARM_PTE_APMASK) == ARM_PTE_AP(AP_RWRW)) {
++ req.prot |= LINUX64_PROT_WRITE;
++ }
++ if (!(pte & ARM_PTE_PNX)) {
++ req.prot |= LINUX64_PROT_EXEC;
++ }
++ linux64_call(LINUX64_CALL_KMAP, &req);
++ if (req.result < 0) {
++ panic("linux64_el0: kernel KMAP failed va=0x%llx pa=0x%llx size=0x%llx prot=0x%x err=%lld",
++ (unsigned long long)va, (unsigned long long)pa,
++ (unsigned long long)size, (unsigned int)req.prot,
++ (long long)req.result);
++ }
++ }
++ } else {
++ linux64_call(LINUX64_CALL_KUNMAP, &req);
++ }
++ return;
++ }
++ if (pmap->type == PMAP_TYPE_NESTED || pmap->type == PMAP_TYPE_COMMPAGE) {
++ struct linux64_map_req req = { .as_handle = 0, .va = va, .size = size };
++ linux64_call(LINUX64_CALL_AS_UNMAP, &req);
++ return;
++ }
++ if (!pmap->linux64_as) {
++ return;
++ }
++ struct linux64_map_req req = { .as_handle = pmap->linux64_as, .va = va, .size = size };
++ uint64_t ap = pte & ARM_PTE_APMASK;
++ bool user_read = (ap == ARM_PTE_AP(AP_RORO) || ap == ARM_PTE_AP(AP_RWRW));
++ bool user_write = (ap == ARM_PTE_AP(AP_RWRW));
++ bool user_exec = !(pte & ARM_PTE_NX);
++ if (pte_is_valid(pte) && (pte & ARM_PTE_AF) && (user_read || user_exec)) {
++ pmap_paddr_t pa = pte_to_pa(pte);
++ if (pa_valid(pa)) {
++ req.pa = pa;
++ req.prot = (user_read ? LINUX64_PROT_READ : 0) |
++ (user_write ? LINUX64_PROT_WRITE : 0) |
++ (user_exec ? LINUX64_PROT_EXEC : 0);
++ linux64_call(LINUX64_CALL_AS_MAP, &req);
++ return;
++ }
++ }
++ linux64_call(LINUX64_CALL_AS_UNMAP, &req);
++}
++
++bool
++pmap_el0_kmap_range_supported(vm_map_address_t va, pmap_paddr_t pa, vm_map_size_t size)
++{
++ vm_map_address_t va_end;
++ pmap_paddr_t pa_end;
++
++ if (!linux64_el0 || size == 0) {
++ return true;
++ }
++ if (os_add_overflow(va, size, &va_end) || os_add_overflow(pa, size, &pa_end)) {
++ return false;
++ }
++ for (vm_map_size_t off = 0; off < size; off += PAGE_SIZE) {
++ vm_map_address_t cva = va + off;
++ pmap_paddr_t cpa = pa + off;
++ if (physmap_end > physmap_base && cva >= physmap_base && cva < physmap_end) {
++ continue;
++ }
++ if (!pa_valid(cpa)) {
++ return false;
++ }
++ }
++ return true;
++}
++
++bool
++pmap_el0_kmap_pte_supported(pmap_t pmap, vm_map_address_t va)
++{
++ ppnum_t pn;
++
++ if (!linux64_el0 || pmap != kernel_pmap) {
++ return true;
++ }
++ if (physmap_end > physmap_base && va >= physmap_base && va < physmap_end) {
++ return true;
++ }
++ pn = pmap_find_phys(pmap, va);
++ if (pn == 0) {
++ return true;
++ }
++ return pa_valid(((pmap_paddr_t)pn) << PAGE_SHIFT);
++}
++
++bool
++pmap_el0_kmap_pte_ready(pmap_t pmap, vm_map_address_t va, vm_prot_t req_prot)
++{
++ pt_entry_t *ptep;
++ pt_entry_t pte;
++
++ if (!linux64_el0 || pmap != kernel_pmap) {
++ return true;
++ }
++ pmap_lock(pmap, PMAP_LOCK_SHARED);
++ ptep = pmap_pte(pmap, va);
++ pte = ptep ? *ptep : ARM_PTE_EMPTY;
++ pmap_unlock(pmap, PMAP_LOCK_SHARED);
++
++ if (!pte_is_valid(pte)) {
++ return false;
++ }
++ if (!(physmap_end > physmap_base && va >= physmap_base && va < physmap_end) &&
++ !pa_valid(pte_to_pa(pte))) {
++ return false;
++ }
++ if ((req_prot & VM_PROT_WRITE) &&
++ (pte & ARM_PTE_APMASK) != ARM_PTE_AP(AP_RWNA) &&
++ (pte & ARM_PTE_APMASK) != ARM_PTE_AP(AP_RWRW)) {
++ return false;
++ }
++ if ((req_prot & VM_PROT_EXECUTE) && (pte & ARM_PTE_PNX)) {
++ return false;
++ }
++ return true;
++}
++
+ /*
+ * Synchronize updates to PTEs that were previously invalid or had the AF bit cleared,
+ * therefore not requiring TLBI. Use a store-load barrier to ensure subsequent loads
+@@ -2014,6 +2180,17 @@ pmap_map_bd_with_options(
+
+ assert(!ARM_PTE_IS_COMPRESSED(*ptep, ptep));
+ write_pte_strong(ptep, pte);
++ if (linux64_el0 && pa_valid(paddr)) {
++ struct linux64_map_req req = {
++ .va = vaddr, .pa = paddr, .size = PAGE_SIZE,
++ .prot = LINUX64_PROT_READ | ((prot & VM_PROT_WRITE) ? LINUX64_PROT_WRITE : 0),
++ };
++ linux64_call(LINUX64_CALL_KMAP, &req);
++ if (req.result < 0) {
++ panic("linux64_el0: pmap_map_bd KMAP failed va=0x%llx pa=0x%llx err=%lld",
++ (unsigned long long)vaddr, (unsigned long long)paddr, (long long)req.result);
++ }
++ }
+
+ pte_increment_pa(tmplate);
+ vaddr += PAGE_SIZE;
+@@ -2110,6 +2287,17 @@ scan:
+ pte |= ARM_PTE_NG;
+ #endif /* __ARM_KERNEL_PROTECT__ */
+ write_pte_strong(ptep, pte);
++ if (linux64_el0 && pa_valid(pa_start)) {
++ struct linux64_map_req req = {
++ .va = va, .pa = pa_start, .size = PAGE_SIZE,
++ .prot = LINUX64_PROT_READ | ((prot & VM_PROT_WRITE) ? LINUX64_PROT_WRITE : 0),
++ };
++ linux64_call(LINUX64_CALL_KMAP, &req);
++ if (req.result < 0) {
++ panic("linux64_el0: pmap_map_high_window_bd KMAP failed va=0x%llx pa=0x%llx err=%lld",
++ (unsigned long long)va, (unsigned long long)pa_start, (long long)req.result);
++ }
++ }
+ }
+ PMAP_UPDATE_TLBS(kernel_pmap, va_start, va_start + len, false, true);
+ #if KASAN
+@@ -2983,7 +3171,8 @@ pmap_root_alloc_size(pmap_t pmap)
+ const pt_attr_t * const pt_attr = pmap_get_pt_attr(pmap);
+ unsigned int root_level = pt_attr_root_level(pt_attr);
+ const uint64_t index = pt_attr_va_valid_mask(pt_attr);
+- return ((index >> pt_attr_ln_shift(pt_attr, root_level)) + 1) * sizeof(tt_entry_t);
++ vm_size_t size = ((index >> pt_attr_ln_shift(pt_attr, root_level)) + 1) * sizeof(tt_entry_t);
++ return (size < PMAP_ROOT_ALLOC_SIZE) ? PMAP_ROOT_ALLOC_SIZE : size; /* LINUX64: a level-0 root fills half a page */
+ }
+
+
+@@ -3108,6 +3297,16 @@ pmap_create_options_internal(
+ }
+
+ p->ttep = ml_static_vtop((vm_offset_t)p->tte);
++ if (pt_attr_root_level(pmap_get_pt_attr(p)) == PMAP_TT_L0_LEVEL) {
++ /* LINUX64: the root already is the level-0 table TTBR0 walks from */
++ p->hw_tte = p->tte;
++ p->hw_ttep = p->ttep;
++ for (i = 0; i < tte_index_max; i++) {
++ p->tte[i] = ARM_TTE_TYPE_FAULT;
++ }
++ FLUSH_PTE();
++ goto root_ready;
++ }
+ p->hw_tte = pmap_tt1_allocate(p, pmap_root_alloc_size(p), 0);
+ if (!p->hw_tte) {
+ pmap_tt1_deallocate(p, p->tte, pmap_root_alloc_size(p), 0);
+@@ -3129,6 +3328,7 @@ pmap_create_options_internal(
+ p->hw_tte[0] = (p->ttep & ARM_TTE_TABLE_MASK) | ARM_TTE_TYPE_TABLE | ARM_TTE_VALID;
+
+ FLUSH_PTE();
++root_ready:
+
+ /*
+ * initialize the rest of the structure
+@@ -3141,6 +3341,12 @@ pmap_create_options_internal(
+ p->nested_no_bounds_ref_state = NESTED_NO_BOUNDS_REF_NONE;
+ p->nested_no_bounds_refcnt = 0;
+ p->nested_bounds_set = false;
++ p->linux64_as = 0;
++ if (linux64_el0 && p != kernel_pmap && p->type == PMAP_TYPE_USER) {
++ struct linux64_map_req req = {0};
++ linux64_call(LINUX64_CALL_AS_CREATE, &req);
++ p->linux64_as = req.as_handle;
++ }
+
+
+ #if MACH_ASSERT
+@@ -3406,6 +3612,24 @@ pmap_destroy_internal(
+
+
+
++ if (linux64_el0 && pmap->type == PMAP_TYPE_NESTED && pmap->nested_region_size) {
++ __builtin_arm_dmb(DMB_ISH);
++ struct linux64_map_req req = {
++ .as_handle = 0,
++ .va = pmap->nested_region_addr,
++ .size = pmap->nested_region_size,
++ };
++ linux64_call(LINUX64_CALL_AS_UNMAP, &req);
++ }
++ if (linux64_el0 && pmap->linux64_as) {
++ struct linux64_map_req req = { .as_handle = pmap->linux64_as };
++ linux64_call(LINUX64_CALL_AS_DESTROY, &req);
++ pmap->linux64_as = 0;
++ }
++ if (pmap->hw_tte == pmap->tte) {
++ pmap->hw_tte = (tt_entry_t *) NULL; /* LINUX64: a level-0 root is both; free it once, below */
++ pmap->hw_ttep = 0;
++ }
+ if (pmap->tte) {
+ pmap_tt1_deallocate(pmap, pmap->tte, pmap_root_alloc_size(pmap), 0);
+ pmap->tte = (tt_entry_t *) NULL;
+@@ -4126,8 +4350,22 @@ pmap_remove_range(
+ int num_changed = pmap_remove_range_options(pmap, va, bpte, epte, NULL,
+ &need_strong_sync, PMAP_OPTIONS_REMOVE);
+ if (num_changed > 0) {
+- PMAP_UPDATE_TLBS(pmap, va,
+- va + (pt_attr_page_size(pmap_get_pt_attr(pmap)) * (epte - bpte)), need_strong_sync, true);
++ uint64_t rlen = pt_attr_page_size(pmap_get_pt_attr(pmap)) * (epte - bpte);
++ if (linux64_el0) {
++ if (pmap == kernel_pmap) {
++ struct linux64_map_req req = { .va = va, .size = rlen };
++ linux64_call(LINUX64_CALL_KUNMAP, &req);
++ } else if (pmap->type == PMAP_TYPE_NESTED || pmap->type == PMAP_TYPE_COMMPAGE) {
++ __builtin_arm_dmb(DMB_ISH);
++ struct linux64_map_req req = { .as_handle = 0, .va = va, .size = rlen };
++ linux64_call(LINUX64_CALL_AS_UNMAP, &req);
++ } else if (pmap->linux64_as) {
++ __builtin_arm_dmb(DMB_ISH);
++ struct linux64_map_req req = { .as_handle = pmap->linux64_as, .va = va, .size = rlen };
++ linux64_call(LINUX64_CALL_AS_UNMAP, &req);
++ }
++ }
++ PMAP_UPDATE_TLBS(pmap, va, va + rlen, need_strong_sync, true);
+ }
+ return num_changed;
+ }
+@@ -4484,6 +4722,21 @@ pmap_remove_options_internal(
+ remove_count = pmap_remove_range_options(pmap, start, bpte, epte, &eva,
+ &need_strong_sync, options);
+
++ if (linux64_el0 && remove_count > 0 && eva > start) {
++ if (pmap == kernel_pmap) {
++ struct linux64_map_req req = { .va = start, .size = eva - start };
++ linux64_call(LINUX64_CALL_KUNMAP, &req);
++ } else if (pmap->type == PMAP_TYPE_NESTED || pmap->type == PMAP_TYPE_COMMPAGE) {
++ __builtin_arm_dmb(DMB_ISH);
++ struct linux64_map_req req = { .as_handle = 0, .va = start, .size = eva - start };
++ linux64_call(LINUX64_CALL_AS_UNMAP, &req);
++ } else if (pmap->linux64_as) {
++ __builtin_arm_dmb(DMB_ISH);
++ struct linux64_map_req req = { .as_handle = pmap->linux64_as, .va = start, .size = eva - start };
++ linux64_call(LINUX64_CALL_AS_UNMAP, &req);
++ }
++ }
++
+ if ((pmap->type == PMAP_TYPE_USER) && (ptep_get_info(pte_p)->refcnt == 0)) {
+ pmap_tte_deallocate(pmap, start, eva, need_strong_sync, tte_p, pt_attr_twig_level(pt_attr));
+ remove_count = 0; // pmap_tte_deallocate has flushed the TLB for us
+@@ -5070,6 +5323,7 @@ pmap_page_protect_options_with_flush_range(
+
+ assert(spte != tmplate);
+ write_pte_fast(pte_p, tmplate);
++ linux64_el0_mirror_pte(pmap, va, tmplate, pt_attr_page_size(pmap_get_pt_attr(pmap)) * PAGE_RATIO);
+ update = true;
+ ++pass1_updated;
+
+@@ -5151,6 +5405,7 @@ pmap_page_protect_options_with_flush_range(
+ assert(spte != ARM_PTE_EMPTY);
+ assert(!ARM_PTE_IS_COMPRESSED(spte, pte_p));
+
++
+ if (spte != tmplate) {
+ /*
+ * Mark the PTE so that we'll know this mapping requires a TLB flush in pass 2.
+@@ -5159,7 +5414,13 @@ pmap_page_protect_options_with_flush_range(
+ * should always be cleared by this function.
+ */
+ pte_set_was_writeable(tmplate, true);
++ if (linux64_el0 && pmap == kernel_pmap) {
++ linux64_el0_mirror_pte(pmap, va, tmplate, pt_attr_page_size(pmap_get_pt_attr(pmap)) * PAGE_RATIO);
++ }
+ write_pte_fast(pte_p, tmplate);
++ if (linux64_el0 && pmap != kernel_pmap) {
++ linux64_el0_mirror_pte(pmap, va, tmplate, pt_attr_page_size(pmap_get_pt_attr(pmap)) * PAGE_RATIO);
++ }
+ update = true;
+ ++pass1_updated;
+ } else if (pte_was_writeable(tmplate)) {
+@@ -5456,6 +5717,10 @@ pmap_has_prot_policy(__unused pmap_t pmap, __unused bool translated_allow_execut
+ static inline bool
+ pmap_allows_xo(pmap_t pmap __unused)
+ {
++ if (linux64_el0 &&
++ !(linux64_el0_caps & (LINUX64_EL0_CAP_EXEC_ONLY | LINUX64_EL0_CAP_XO_COMPAT))) {
++ return false;
++ }
+ return true;
+ }
+
+@@ -5503,11 +5768,13 @@ pmap_protect_options_internal(
+
+ #if DEVELOPMENT || DEBUG
+ if (options & PMAP_OPTIONS_PROTECT_IMMEDIATE) {
++#else
++ if (linux64_el0 && pmap == kernel_pmap && (options & PMAP_OPTIONS_PROTECT_IMMEDIATE)) {
++#endif
+ if ((prot & VM_PROT_ALL) == VM_PROT_NONE) {
+ should_have_removed = TRUE;
+ }
+ } else
+-#endif
+ {
+ /* Determine the new protection. */
+ switch (prot) {
+@@ -5516,6 +5783,9 @@ pmap_protect_options_internal(
+ break;
+ case VM_PROT_READ | VM_PROT_WRITE:
+ case VM_PROT_ALL:
++ if (linux64_el0 && pmap == kernel_pmap) {
++ break;
++ }
+ return end; /* nothing to do */
+ case VM_PROT_EXECUTE:
+ set_XO = true;
+@@ -5570,9 +5840,7 @@ pmap_protect_options_internal(
+ break;
+ }
+ pt_entry_t spte;
+-#if DEVELOPMENT || DEBUG
+ boolean_t force_write = FALSE;
+-#endif
+
+ spte = *((volatile pt_entry_t*)pte_p);
+
+@@ -5613,6 +5881,10 @@ pmap_protect_options_internal(
+ pt_entry_t tmplate;
+
+ if (pmap == kernel_pmap) {
++ if (linux64_el0 && (options & PMAP_OPTIONS_PROTECT_IMMEDIATE) && (prot & VM_PROT_WRITE)) {
++ force_write = TRUE;
++ tmplate = ((spte & ~ARM_PTE_APMASK) | ARM_PTE_AP(AP_RWNA));
++ } else
+ #if DEVELOPMENT || DEBUG
+ if ((options & PMAP_OPTIONS_PROTECT_IMMEDIATE) && (prot & VM_PROT_WRITE)) {
+ force_write = TRUE;
+@@ -5654,14 +5926,31 @@ pmap_protect_options_internal(
+ } else {
+ /* do NOT clear "NX"! */
+ tmplate |= pt_attr_leaf_x(pt_attr);
+- if (__improbable(set_XO)) {
++ if (__improbable(set_XO) &&
++ !(linux64_el0 && !(linux64_el0_caps & LINUX64_EL0_CAP_EXEC_ONLY) &&
++ (linux64_el0_caps & LINUX64_EL0_CAP_XO_COMPAT))) {
+ tmplate &= ~ARM_PTE_APMASK;
+ tmplate |= pt_attr_leaf_rona(pt_attr);
+ }
+ }
+ }
+
+-#if DEVELOPMENT || DEBUG
++ if (managed && (force_write || (options & PMAP_OPTIONS_PROTECT_IMMEDIATE))) {
++ tmplate |= ARM_PTE_AF;
++ }
++
++ /* We do not expect to write fast fault the entry. */
++ pte_set_was_writeable(tmplate, false);
++#if HAS_FEAT_XS
++ if (pte_is_xs(pt_attr, spte)) {
++ need_strong_sync = true;
++ }
++#endif /* HAS_FEAT_XS */
++
++ if (linux64_el0 && pmap == kernel_pmap) {
++ linux64_el0_mirror_pte(pmap, va, tmplate, pmap_page_size);
++ }
++
+ if (force_write) {
+ /*
+ * TODO: Run CS/Monitor checks here.
+@@ -5673,7 +5962,6 @@ pmap_protect_options_internal(
+ * referenced.
+ */
+ ppattr_pa_set_bits(pa, PP_ATTR_REFERENCED | PP_ATTR_MODIFIED);
+- tmplate |= ARM_PTE_AF;
+
+ if (ppattr_test_reffault(pai)) {
+ ppattr_clear_reffault(pai);
+@@ -5691,32 +5979,27 @@ pmap_protect_options_internal(
+ */
+ if (managed) {
+ ppattr_pa_set_bits(pa, PP_ATTR_REFERENCED);
+- tmplate |= ARM_PTE_AF;
+
+ if (ppattr_test_reffault(pai)) {
+ ppattr_clear_reffault(pai);
+ }
+ }
+ }
+-#endif
+-
+- /* We do not expect to write fast fault the entry. */
+- pte_set_was_writeable(tmplate, false);
+-#if HAS_FEAT_XS
+- if (pte_is_xs(pt_attr, spte)) {
+- need_strong_sync = true;
+- }
+-#endif /* HAS_FEAT_XS */
+
+ write_pte_fast(pte_p, tmplate);
++ if (linux64_el0 && pmap != kernel_pmap) {
++ linux64_el0_mirror_pte(pmap, va, tmplate, pmap_page_size);
++ }
+
+ if (managed) {
+ pvh_assert_locked(pai);
+ pvh_unlock(pai);
+ }
+ }
+- FLUSH_PTE_STRONG();
+- PMAP_UPDATE_TLBS(pmap, start, va, need_strong_sync, true);
++ if (va > start) {
++ FLUSH_PTE_STRONG();
++ PMAP_UPDATE_TLBS(pmap, start, va, need_strong_sync, true);
++ }
+ } else {
+ va = end;
+ }
+@@ -5755,12 +6038,14 @@ pmap_protect_options(
+
+ #if DEVELOPMENT || DEBUG
+ if (options & PMAP_OPTIONS_PROTECT_IMMEDIATE) {
++#else
++ if (linux64_el0 && pmap == kernel_pmap && (options & PMAP_OPTIONS_PROTECT_IMMEDIATE)) {
++#endif
+ if ((prot & VM_PROT_ALL) == VM_PROT_NONE) {
+ pmap_remove_options(pmap, b, e, options);
+ return;
+ }
+ } else
+-#endif
+ {
+ /* Determine the new protection. */
+ switch (prot) {
+@@ -5862,6 +6147,18 @@ pmap_map_block_addr(
+ const uint64_t pmap_page_size = PAGE_SIZE;
+ #endif
+
++ addr64_t orig_va = va;
++ uint64_t byte_len = 0;
++ addr64_t end_va = 0;
++ if (os_mul_overflow((uint64_t)size, pmap_page_size, &byte_len) ||
++ os_add_overflow(orig_va, byte_len, &end_va)) {
++ return KERN_INVALID_ADDRESS;
++ }
++ if (linux64_el0 && pmap == kernel_pmap && size > 0 &&
++ !pmap_el0_kmap_range_supported(orig_va, pa, byte_len)) {
++ return KERN_NOT_SUPPORTED;
++ }
++
+ for (ppnum_t page = 0; page < size; page++) {
+ if (pmap_enter_addr(pmap, va, pa, prot, VM_PROT_NONE, attr, TRUE) != KERN_SUCCESS) {
+ panic("%s: failed pmap_enter_addr, "
+@@ -5917,6 +6214,255 @@ pmap_enter(
+ return pmap_enter_addr(pmap, v, ((pmap_paddr_t)pn) << PAGE_SHIFT, prot, fault_type, flags, wired);
+ }
+
++static unsigned int
++pmap_el0_attrindx_to_wimg(unsigned int attrindx, pt_entry_t pte)
++{
++ if (attrindx == CACHE_ATTRINDX_DISABLE) {
++ return VM_WIMG_IO;
++ }
++#if HAS_FEAT_XS
++ if (attrindx == CACHE_ATTRINDX_DISABLE_XS) {
++ return VM_WIMG_IO;
++ }
++ if (attrindx == CACHE_ATTRINDX_POSTED_COMBINED_REORDERED_XS) {
++ return VM_WIMG_POSTED_COMBINED_REORDERED;
++ }
++#endif
++ if (attrindx == CACHE_ATTRINDX_POSTED) {
++ return VM_WIMG_POSTED;
++ }
++ if (attrindx == CACHE_ATTRINDX_POSTED_REORDERED) {
++ return VM_WIMG_POSTED_REORDERED;
++ }
++ if (attrindx == CACHE_ATTRINDX_POSTED_COMBINED_REORDERED) {
++ return VM_WIMG_POSTED_COMBINED_REORDERED;
++ }
++ if (attrindx == CACHE_ATTRINDX_WRITECOMB) {
++ return VM_WIMG_WCOMB;
++ }
++ if (attrindx == CACHE_ATTRINDX_WRITETHRU) {
++ return VM_WIMG_WTHRU;
++ }
++ if (attrindx == CACHE_ATTRINDX_WRITEBACK) {
++ if ((pte & ARM_PTE_SHMASK) == ARM_PTE_SH(SH_INNER_MEMORY)) {
++ return VM_WIMG_INNERWBACK;
++ }
++ return VM_WIMG_COPYBACK;
++ }
++ return VM_WIMG_USE_DEFAULT;
++}
++
++bool
++pmap_el0_wimg_supported(unsigned int wimg)
++{
++ return !linux64_el0 || wimg == VM_WIMG_DEFAULT ||
++ wimg == VM_WIMG_COPYBACK || wimg == VM_WIMG_USE_DEFAULT;
++}
++
++kern_return_t
++pmap_el0_update_cache_mode(
++ pmap_t pmap,
++ vm_map_address_t va,
++ unsigned int wimg_flags,
++ bool use_default)
++{
++ pt_entry_t *ptep;
++ pt_entry_t pte;
++
++ if (!linux64_el0 || pmap != kernel_pmap) {
++ return KERN_INVALID_ARGUMENT;
++ }
++
++ pmap_lock(pmap, PMAP_LOCK_SHARED);
++ ptep = pmap_pte(pmap, va);
++ pte = ptep ? *ptep : ARM_PTE_EMPTY;
++ pmap_unlock(pmap, PMAP_LOCK_SHARED);
++
++ if (!pte_is_valid(pte)) {
++ return KERN_FAILURE;
++ }
++
++ pmap_paddr_t pa = pte_to_pa(pte);
++ if (!pa_valid(pa)) {
++ return KERN_NOT_SUPPORTED;
++ }
++ ppnum_t pn = atop(pa);
++#if HAS_MTE
++ if (pmap_is_tagged_page(pn)) {
++ return KERN_INVALID_ARGUMENT;
++ }
++#endif
++ unsigned int attr = use_default ? pmap_cache_attributes(pn) : wimg_flags;
++ if (!pmap_el0_wimg_supported(attr)) {
++ return KERN_NOT_SUPPORTED;
++ }
++ pmap_set_cache_attributes(pn, attr);
++ return KERN_SUCCESS;
++}
++
++bool
++pmap_el0_read_pte_snapshot(
++ pmap_t pmap,
++ vm_map_address_t va,
++ uint64_t *pte_out,
++ pmap_paddr_t *pa_out,
++ bool *pa_is_valid_out)
++{
++ _Static_assert(sizeof(pt_entry_t) <= sizeof(uint64_t), "pt_entry_t must fit in uint64_t");
++ pt_entry_t *ptep;
++ pt_entry_t pte;
++
++ pmap_lock(pmap, PMAP_LOCK_SHARED);
++ ptep = pmap_pte(pmap, va);
++ pte = ptep ? *ptep : ARM_PTE_EMPTY;
++ pmap_unlock(pmap, PMAP_LOCK_SHARED);
++
++ if (pte_is_valid(pte)) {
++ pmap_paddr_t pa = pte_to_pa(pte);
++ if (pte_out != NULL) {
++ *pte_out = (uint64_t)pte;
++ }
++ if (pa_out != NULL) {
++ *pa_out = pa;
++ }
++ if (pa_is_valid_out != NULL) {
++ *pa_is_valid_out = pa_valid(pa);
++ }
++ return true;
++ }
++ if (pte_out != NULL) {
++ *pte_out = (uint64_t)ARM_PTE_EMPTY;
++ }
++ if (pa_out != NULL) {
++ *pa_out = 0;
++ }
++ if (pa_is_valid_out != NULL) {
++ *pa_is_valid_out = false;
++ }
++ return false;
++}
++
++bool
++pmap_el0_pte_restorable(
++ pmap_t pmap,
++ uint64_t saved_pte_u64)
++{
++ pt_entry_t saved_pte = (pt_entry_t)saved_pte_u64;
++ if (!pte_is_valid(saved_pte)) {
++ return true;
++ }
++ if (pmap == kernel_pmap && !(saved_pte & ARM_PTE_PNX)) {
++#if DEVELOPMENT || DEBUG
++ if (!nx_enabled || !pmap->nx_enabled) {
++ return true;
++ }
++#endif
++ return false;
++ }
++ return true;
++}
++
++kern_return_t
++pmap_el0_restore_pte_snapshot(
++ pmap_t pmap,
++ vm_map_address_t va,
++ uint64_t saved_pte_u64)
++{
++ pt_entry_t saved_pte = (pt_entry_t)saved_pte_u64;
++ if (!pte_is_valid(saved_pte)) {
++ return KERN_SUCCESS;
++ }
++ pmap_paddr_t pa = pte_to_pa(saved_pte);
++ ppnum_t pn = atop(pa);
++ vm_prot_t prot = VM_PROT_READ;
++ if ((saved_pte & ARM_PTE_APMASK) == ARM_PTE_AP(AP_RWNA) ||
++ (saved_pte & ARM_PTE_APMASK) == ARM_PTE_AP(AP_RWRW)) {
++ prot |= VM_PROT_WRITE;
++ }
++ unsigned int wimg = pa_valid(pa) ?
++ pmap_cache_attributes(pn) :
++ pmap_el0_attrindx_to_wimg(ARM_PTE_EXTRACT_ATTRINDX(saved_pte), saved_pte);
++ boolean_t wired = ((saved_pte & ARM_PTE_WIRED) != 0);
++ return pmap_enter_addr(pmap, va, pa, prot, VM_PROT_NONE, wimg, wired);
++}
++
++kern_return_t
++pmap_el0_kmap_txn_begin(
++ vm_map_address_t va,
++ vm_map_size_t size,
++ uint64_t *handle_out)
++{
++ if (handle_out == NULL) {
++ return KERN_INVALID_ARGUMENT;
++ }
++ *handle_out = 0;
++ if (!linux64_el0 || size == 0) {
++ return KERN_SUCCESS;
++ }
++ struct linux64_map_req req = {
++ .as_handle = 0,
++ .va = va,
++ .pa = 0,
++ .size = size,
++ .prot = LINUX64_KMAP_TXN_BEGIN,
++ .result = 0,
++ };
++ linux64_call(LINUX64_CALL_KMAP_TXN, &req);
++ if (req.result < 0) {
++ switch (req.result) {
++ case -12: /* -ENOMEM */
++ return KERN_RESOURCE_SHORTAGE;
++ case -16: /* -EBUSY */
++ return KERN_ABORTED;
++ case -22: /* -EINVAL */
++ return KERN_INVALID_ARGUMENT;
++ case -95: /* -EOPNOTSUPP */
++ return KERN_NOT_SUPPORTED;
++ default:
++ return KERN_FAILURE;
++ }
++ }
++ if (req.as_handle == 0) {
++ return KERN_FAILURE;
++ }
++ *handle_out = req.as_handle;
++ return KERN_SUCCESS;
++}
++
++void
++pmap_el0_kmap_txn_begin_restore(uint64_t handle)
++{
++ if (!linux64_el0 || handle == 0) {
++ return;
++ }
++ struct linux64_map_req req = {
++ .as_handle = handle,
++ .va = 0,
++ .pa = 0,
++ .size = 0,
++ .prot = LINUX64_KMAP_TXN_RESTORE,
++ .result = 0,
++ };
++ linux64_call(LINUX64_CALL_KMAP_TXN, &req);
++}
++
++void
++pmap_el0_kmap_txn_end(uint64_t handle)
++{
++ if (!linux64_el0 || handle == 0) {
++ return;
++ }
++ struct linux64_map_req req = {
++ .as_handle = handle,
++ .va = 0,
++ .pa = 0,
++ .size = 0,
++ .prot = LINUX64_KMAP_TXN_END,
++ .result = 0,
++ };
++ linux64_call(LINUX64_CALL_KMAP_TXN, &req);
++}
++
+ /*
+ * Attempt to commit the pte.
+ * Succeeds iff able to change *pte_p from old_pte to new_pte.
+@@ -5926,7 +6472,20 @@ static inline bool
+ pmap_enter_pte(pmap_t pmap, pt_entry_t *pte_p, pt_entry_t *old_pte, pt_entry_t new_pte, vm_map_address_t v)
+ {
+ const pt_attr_t * const pt_attr = pmap_get_pt_attr(pmap);
++ uint64_t amount = pt_attr_page_size(pt_attr) * PAGE_RATIO;
+ bool success = false, changed_wiring = false;
++ bool mirrored_before = false;
++
++ if (linux64_el0 && pmap == kernel_pmap && pte_is_valid(new_pte)) {
++ pmap_assert_locked(pmap, PMAP_LOCK_EXCLUSIVE);
++ *old_pte = *pte_p;
++ if (*old_pte != new_pte &&
++ !(pa_valid(pte_to_pa(new_pte)) && pte_is_valid(*old_pte) &&
++ pte_to_pa(*old_pte) != pte_to_pa(new_pte))) {
++ linux64_el0_mirror_pte(pmap, v, new_pte, amount);
++ mirrored_before = true;
++ }
++ }
+
+ __unreachable_ok_push
+ if (TEST_PAGE_RATIO_4) {
+@@ -5954,7 +6513,11 @@ pmap_enter_pte(pmap_t pmap, pt_entry_t *pte_p, pt_entry_t *old_pte, pt_entry_t n
+ __unreachable_ok_pop
+
+ if (success && *old_pte != new_pte) {
+- uint64_t amount = pt_attr_page_size(pt_attr) * PAGE_RATIO;
++ if (!mirrored_before &&
++ ((pmap->type != PMAP_TYPE_NESTED && pmap->type != PMAP_TYPE_COMMPAGE) ||
++ pte_is_valid(*old_pte))) {
++ linux64_el0_mirror_pte(pmap, v, new_pte, amount);
++ }
+
+ if (pte_is_valid(*old_pte)) {
+ bool need_strong_sync = false;
+@@ -6195,7 +6758,9 @@ pmap_construct_pte(
+ *pp_attr_bits |= PP_ATTR_REFERENCED;
+ }
+ } else {
+- if (__improbable(set_XO)) {
++ if (__improbable(set_XO) &&
++ !(linux64_el0 && !(linux64_el0_caps & LINUX64_EL0_CAP_EXEC_ONLY) &&
++ (linux64_el0_caps & LINUX64_EL0_CAP_XO_COMPAT))) {
+ pte |= pt_attr_leaf_rona(pt_attr);
+ } else {
+ pte |= pt_attr_leaf_ro(pt_attr);
+@@ -6228,7 +6793,8 @@ pmap_enter_options_internal(
+ bool ro_va = false;
+ unsigned int wimg_bits;
+ bool committed = false, drop_refcnt = false, had_valid_mapping = false, skip_footprint_debit = false;
+- pmap_lock_mode_t lock_mode = PMAP_LOCK_SHARED;
++ pmap_lock_mode_t lock_mode = (linux64_el0 && pmap == kernel_pmap) ?
++ PMAP_LOCK_EXCLUSIVE : PMAP_LOCK_SHARED;
+ kern_return_t kr = KERN_SUCCESS;
+ uint16_t pp_attr_bits;
+ volatile uint16_t *refcnt;
+@@ -6268,6 +6834,12 @@ pmap_enter_options_internal(
+ /* The PA should not extend beyond the architected physical address space */
+ pa &= ARM_PTE_PAGE_MASK;
+
++ if (linux64_el0 && pmap == kernel_pmap && !(options & PMAP_OPTIONS_NOENTER)) {
++ if (!pmap_el0_kmap_range_supported(v, pa, pt_attr_page_size(pt_attr) * PAGE_RATIO)) {
++ return KERN_NOT_SUPPORTED;
++ }
++ }
++
+ if ((prot & VM_PROT_EXECUTE) && (pmap == kernel_pmap)) {
+ #if (defined(KERNEL_INTEGRITY_CTRR) || defined(KERNEL_INTEGRITY_PV_CTRR)) && defined(CONFIG_XNUPOST)
+ extern vm_offset_t ctrr_test_page;
+@@ -6972,6 +7544,366 @@ pmap_find_phys(
+ * @return The physical address if the translation was successful, or zero if
+ * no valid mappings were found for the given virtual address.
+ */
++extern pmap_paddr_t linux64_el0_ptov_vtop(vm_offset_t va);
++pmap_paddr_t linux64_el0_kvtop(vm_offset_t va);
++pmap_paddr_t
++linux64_el0_kvtop(vm_offset_t va)
++{
++ if (kernel_pmap && kernel_pmap->tte) {
++ pmap_paddr_t pa = pmap_vtophys(kernel_pmap, va);
++ if (pa) {
++ return pa;
++ }
++ }
++ return linux64_el0_ptov_vtop(va);
++}
++
++uint64_t
++linux64_el0_ensure_as(pmap_t pmap)
++{
++ if (!linux64_el0 || !pmap || pmap == kernel_pmap) {
++ return 0;
++ }
++ if (!pmap->linux64_as) {
++ pmap_lock(pmap, PMAP_LOCK_EXCLUSIVE);
++ if (!pmap->linux64_as) {
++ struct linux64_map_req req = {0};
++ linux64_call(LINUX64_CALL_AS_CREATE, &req);
++ pmap->linux64_as = req.as_handle;
++ }
++ pmap_unlock(pmap, PMAP_LOCK_EXCLUSIVE);
++ }
++ return pmap->linux64_as;
++}
++
++bool
++linux64_el0_sync_user_pte(pmap_t pmap, vm_offset_t far, uint64_t esr)
++{
++ if (!linux64_el0 || !pmap || pmap == kernel_pmap) {
++ return false;
++ }
++ uint64_t as = linux64_el0_ensure_as(pmap);
++ if (!as) {
++ return false;
++ }
++ uint64_t ufar = (uint64_t)((int64_t)(far << 8) >> 8);
++ if (ufar >= 0x0001000000000000ULL) {
++ return false;
++ }
++ vm_map_address_t va = (vm_map_address_t)(ufar & ~0xfffULL);
++ uint32_t ec = (uint32_t)((esr >> 26) & 0x3f);
++ bool is_exec = (ec == 0x20 || ec == 0x21);
++ bool is_write = (!is_exec) && ((esr & (1u << 6)) != 0) && ((esr & (1u << 8)) == 0);
++
++ pmap_lock(pmap, PMAP_LOCK_SHARED);
++ pt_entry_t *ptep = pmap_pte(pmap, va);
++ if (!ptep) {
++ pmap_unlock(pmap, PMAP_LOCK_SHARED);
++ return false;
++ }
++ pt_entry_t pte = ARM_PTE_EMPTY;
++ pmap_paddr_t pa = 0;
++ unsigned int pai = 0;
++ bool user_read = false, user_write = false, user_exec = false;
++ bool locked_pvh = false;
++ for (int retry = 0; retry < 4; retry++) {
++ pte = *(volatile pt_entry_t *)ptep;
++ if (!pte_is_valid(pte) || !(pte & ARM_PTE_AF)) {
++ pmap_unlock(pmap, PMAP_LOCK_SHARED);
++ return false;
++ }
++ uint64_t ap = pte & ARM_PTE_APMASK;
++ user_read = (ap == ARM_PTE_AP(AP_RORO) || ap == ARM_PTE_AP(AP_RWRW));
++ user_write = (ap == ARM_PTE_AP(AP_RWRW));
++ user_exec = !(pte & ARM_PTE_NX);
++ if (is_exec ? !user_exec : (is_write ? !user_write : !user_read)) {
++ pmap_unlock(pmap, PMAP_LOCK_SHARED);
++ return false;
++ }
++ pa = pte_to_pa(pte);
++ if (!pa_valid(pa)) {
++ pmap_unlock(pmap, PMAP_LOCK_SHARED);
++ return false;
++ }
++ pai = pa_index(pa);
++ pvh_lock(pai);
++ if (*(volatile pt_entry_t *)ptep == pte) {
++ locked_pvh = true;
++ break;
++ }
++ pvh_unlock(pai);
++ }
++ if (!locked_pvh) {
++ pmap_unlock(pmap, PMAP_LOCK_SHARED);
++ return false;
++ }
++
++ struct linux64_map_req req = {
++ .as_handle = as,
++ .va = va,
++ .pa = pa,
++ .size = 4096,
++ .prot = (user_read ? LINUX64_PROT_READ : 0) |
++ (user_write ? LINUX64_PROT_WRITE : 0) |
++ (user_exec ? LINUX64_PROT_EXEC : 0),
++ };
++ linux64_call(LINUX64_CALL_AS_MAP, &req);
++ pvh_unlock(pai);
++ pmap_unlock(pmap, PMAP_LOCK_SHARED);
++ return req.result > 0;
++}
++
++bool
++linux64_el0_user_vtop(pmap_t pmap, vm_offset_t va, bool write, pmap_paddr_t *pa_out)
++{
++ if (!pmap || pmap == kernel_pmap) {
++ return false;
++ }
++ vm_map_address_t page_va = (vm_map_address_t)(va & ~0xfffULL);
++ pmap_lock(pmap, PMAP_LOCK_SHARED);
++ pt_entry_t *ptep = pmap_pte(pmap, page_va);
++ pt_entry_t pte = ptep ? *ptep : ARM_PTE_EMPTY;
++ pmap_unlock(pmap, PMAP_LOCK_SHARED);
++
++ if (!pte_is_valid(pte) || !(pte & ARM_PTE_AF)) {
++ return false;
++ }
++ uint64_t ap = pte & ARM_PTE_APMASK;
++ if (write) {
++ if (ap != ARM_PTE_AP(AP_RWRW)) {
++ return false;
++ }
++ } else {
++ if (ap != ARM_PTE_AP(AP_RORO) && ap != ARM_PTE_AP(AP_RWRW)) {
++ return false;
++ }
++ }
++ pmap_paddr_t pa = pte_to_pa(pte);
++ if (!pa_valid(pa)) {
++ return false;
++ }
++ *pa_out = pa + (va & 0xfffULL);
++ return true;
++}
++
++static bool
++linux64_el0_lock_user_page(pmap_t pmap, vm_offset_t uaddr, bool write, pmap_paddr_t *pa_out, unsigned int *pai_out)
++{
++ if (!pmap || pmap == kernel_pmap) {
++ return false;
++ }
++ vm_map_address_t page_va = (vm_map_address_t)(uaddr & ~0xfffULL);
++ pmap_lock(pmap, PMAP_LOCK_SHARED);
++ pt_entry_t *ptep = pmap_pte(pmap, page_va);
++ if (!ptep) {
++ pmap_unlock(pmap, PMAP_LOCK_SHARED);
++ return false;
++ }
++ for (int retry = 0; retry < 4; retry++) {
++ pt_entry_t pte = *(volatile pt_entry_t *)ptep;
++ if (!pte_is_valid(pte) || !(pte & ARM_PTE_AF)) {
++ pmap_unlock(pmap, PMAP_LOCK_SHARED);
++ return false;
++ }
++ uint64_t ap = pte & ARM_PTE_APMASK;
++ if (write ? (ap != ARM_PTE_AP(AP_RWRW)) :
++ (ap != ARM_PTE_AP(AP_RORO) && ap != ARM_PTE_AP(AP_RWRW))) {
++ pmap_unlock(pmap, PMAP_LOCK_SHARED);
++ return false;
++ }
++ pmap_paddr_t pa = pte_to_pa(pte);
++ if (!pa_valid(pa)) {
++ pmap_unlock(pmap, PMAP_LOCK_SHARED);
++ return false;
++ }
++ unsigned int pai = pa_index(pa);
++ pvh_lock(pai);
++ if (*(volatile pt_entry_t *)ptep == pte) {
++ *pa_out = pa + (uaddr & 0xfffULL);
++ *pai_out = pai;
++ return true;
++ }
++ pvh_unlock(pai);
++ }
++ pmap_unlock(pmap, PMAP_LOCK_SHARED);
++ return false;
++}
++
++bool
++linux64_el0_copyio_chunk(pmap_t pmap, vm_offset_t uaddr, bool write, void *bounce, size_t max_len, size_t *out_len)
++{
++ pmap_paddr_t pa = 0;
++ unsigned int pai = 0;
++ if (!linux64_el0_lock_user_page(pmap, uaddr, write, &pa, &pai)) {
++ return false;
++ }
++ size_t off = (size_t)(uaddr & 0xfffULL);
++ size_t chunk = 4096 - off;
++ if (chunk > max_len) {
++ chunk = max_len;
++ }
++ if (write) {
++ bcopy(bounce, (void *)phystokv(pa), chunk);
++ } else {
++ bcopy((const void *)phystokv(pa), bounce, chunk);
++ }
++ pvh_unlock(pai);
++ pmap_unlock(pmap, PMAP_LOCK_SHARED);
++ *out_len = chunk;
++ return true;
++}
++
++bool
++linux64_el0_atomic_op(pmap_t pmap, vm_offset_t uaddr, bool write, size_t width, uint64_t *val)
++{
++ pmap_paddr_t pa = 0;
++ unsigned int pai = 0;
++ if (!linux64_el0_lock_user_page(pmap, uaddr, write, &pa, &pai)) {
++ return false;
++ }
++ if (width == 4) {
++ if (write) {
++ __atomic_store_n((volatile uint32_t *)phystokv(pa), (uint32_t)*val, __ATOMIC_RELAXED);
++ } else {
++ *val = __atomic_load_n((volatile uint32_t *)phystokv(pa), __ATOMIC_RELAXED);
++ }
++ } else {
++ if (write) {
++ __atomic_store_n((volatile uint64_t *)phystokv(pa), *val, __ATOMIC_RELAXED);
++ } else {
++ *val = __atomic_load_n((volatile uint64_t *)phystokv(pa), __ATOMIC_RELAXED);
++ }
++ }
++ pvh_unlock(pai);
++ pmap_unlock(pmap, PMAP_LOCK_SHARED);
++ return true;
++}
++
++static bool
++linux64_el0_kpage_check_locked(vm_offset_t addr, bool require_write, pmap_paddr_t *pa_out)
++{
++ vm_map_address_t va = (vm_map_address_t)(addr & ~0xfffULL);
++ bool in_physmap = (physmap_end > physmap_base && va >= physmap_base && va < physmap_end);
++ tt_entry_t *ttep = pmap_tte(kernel_pmap, va);
++ if (!ttep) {
++ return false;
++ }
++ tt_entry_t tte = *ttep;
++ uint64_t ap;
++ pmap_paddr_t pa = 0;
++ if ((tte & (ARM_TTE_VALID | ARM_TTE_TYPE_MASK)) == (ARM_TTE_VALID | ARM_TTE_TYPE_BLOCK)) {
++ if (!in_physmap) {
++ return false;
++ }
++ ap = tte & ARM_PTE_APMASK;
++ } else if (tte_is_valid_table(tte)) {
++ pt_entry_t *ptep = pmap_pte(kernel_pmap, va);
++ if (!ptep) {
++ return false;
++ }
++ pt_entry_t pte = os_atomic_load(ptep, relaxed);
++ if (!pte_is_valid(pte)) {
++ return false;
++ }
++ ap = pte & ARM_PTE_APMASK;
++ pa = pte_to_pa(pte);
++ if (!in_physmap && !pa_valid(pa)) {
++ return false;
++ }
++ } else {
++ return false;
++ }
++ if (require_write && ap != ARM_PTE_AP(AP_RWNA) && ap != ARM_PTE_AP(AP_RWRW)) {
++ return false;
++ }
++ if (pa_out) {
++ *pa_out = pa;
++ }
++ return true;
++}
++
++bool
++linux64_el0_verify_write(const void *source, void *dst, size_t size)
++{
++ uint8_t bounce[512];
++ const uint8_t *src_p = (const uint8_t *)source;
++ uint8_t *dst_p = (uint8_t *)dst;
++
++ if (size && (((vm_offset_t)src_p + size < (vm_offset_t)src_p) ||
++ ((vm_offset_t)dst_p + size < (vm_offset_t)dst_p))) {
++ return false;
++ }
++
++ while (size > 0) {
++ size_t src_rem = 4096 - ((vm_offset_t)src_p & 0xfffUL);
++ size_t dst_rem = 4096 - ((vm_offset_t)dst_p & 0xfffUL);
++ size_t chunk = size > sizeof(bounce) ? sizeof(bounce) : size;
++ if (chunk > src_rem) {
++ chunk = src_rem;
++ }
++ if (chunk > dst_rem) {
++ chunk = dst_rem;
++ }
++
++ /* Read phase: pmap_lock(SHARED) + pvh_lock (for managed pages) + PTE re-verify. */
++ pmap_paddr_t src_pa = 0, src_pa2 = 0;
++ bool src_pvh = false;
++ unsigned int src_pai = 0;
++ pmap_lock(kernel_pmap, PMAP_LOCK_SHARED);
++ if (!linux64_el0_kpage_check_locked((vm_offset_t)src_p, false, &src_pa)) {
++ pmap_unlock(kernel_pmap, PMAP_LOCK_SHARED);
++ return false;
++ }
++ if (src_pa && pa_valid(src_pa)) {
++ src_pai = pa_index(src_pa);
++ pvh_lock(src_pai);
++ src_pvh = true;
++ if (!linux64_el0_kpage_check_locked((vm_offset_t)src_p, false, &src_pa2) ||
++ src_pa2 != src_pa) {
++ pvh_unlock(src_pai);
++ pmap_unlock(kernel_pmap, PMAP_LOCK_SHARED);
++ return false;
++ }
++ }
++ bcopy(src_p, bounce, chunk);
++ if (src_pvh) {
++ pvh_unlock(src_pai);
++ }
++ pmap_unlock(kernel_pmap, PMAP_LOCK_SHARED);
++
++ /* Write phase: pmap_lock(SHARED) + pvh_lock (for managed pages) + writable PTE re-verify. */
++ pmap_paddr_t dst_pa = 0, dst_pa2 = 0;
++ bool dst_pvh = false;
++ unsigned int dst_pai = 0;
++ pmap_lock(kernel_pmap, PMAP_LOCK_SHARED);
++ if (!linux64_el0_kpage_check_locked((vm_offset_t)dst_p, true, &dst_pa)) {
++ pmap_unlock(kernel_pmap, PMAP_LOCK_SHARED);
++ return false;
++ }
++ if (dst_pa && pa_valid(dst_pa)) {
++ dst_pai = pa_index(dst_pa);
++ pvh_lock(dst_pai);
++ dst_pvh = true;
++ if (!linux64_el0_kpage_check_locked((vm_offset_t)dst_p, true, &dst_pa2) ||
++ dst_pa2 != dst_pa) {
++ pvh_unlock(dst_pai);
++ pmap_unlock(kernel_pmap, PMAP_LOCK_SHARED);
++ return false;
++ }
++ }
++ bcopy(bounce, dst_p, chunk);
++ if (dst_pvh) {
++ pvh_unlock(dst_pai);
++ }
++ pmap_unlock(kernel_pmap, PMAP_LOCK_SHARED);
++
++ src_p += chunk;
++ dst_p += chunk;
++ size -= chunk;
++ }
++ return true;
++}
++
+ pmap_paddr_t
+ kvtophys(vm_offset_t va)
+ {
+@@ -8173,17 +9105,29 @@ arm_force_fast_fault_with_flush_range(
+ assert(!pte_is_xs(pt_attr, spte));
+ #endif /* HAS_FEAT_XS */
+ if ((allow_mode & VM_PROT_READ) != VM_PROT_READ) {
+- /* read protection sets the pte to fault */
+- tmplate = tmplate & ~ARM_PTE_AF;
+- ref_fault = true;
++ if (linux64_el0 && pmap == kernel_pmap) {
++ /* EL0 has no kernel fast-fault recovery: keep AF set and conservatively mark referenced. */
++ ppattr_pa_set_bits(phys, PP_ATTR_REFERENCED);
++ result = FALSE;
++ } else {
++ /* read protection sets the pte to fault */
++ tmplate = tmplate & ~ARM_PTE_AF;
++ ref_fault = true;
++ }
+ }
+ if ((allow_mode & VM_PROT_WRITE) != VM_PROT_WRITE) {
+ /* take away write permission if set */
+ if (pmap == kernel_pmap) {
+ if ((tmplate & ARM_PTE_APMASK) == ARM_PTE_AP(AP_RWNA)) {
+- tmplate = ((tmplate & ~ARM_PTE_APMASK) | ARM_PTE_AP(AP_RONA));
+- pte_set_was_writeable(tmplate, true);
+- mod_fault = true;
++ if (linux64_el0) {
++ /* Keep kernel page writable on EL0 and conservatively mark modified. */
++ ppattr_pa_set_bits(phys, PP_ATTR_MODIFIED);
++ result = FALSE;
++ } else {
++ tmplate = ((tmplate & ~ARM_PTE_APMASK) | ARM_PTE_AP(AP_RONA));
++ pte_set_was_writeable(tmplate, true);
++ mod_fault = true;
++ }
+ }
+ } else {
+ if ((tmplate & ARM_PTE_APMASK) == pt_attr_leaf_rw(pt_attr)) {
+@@ -8220,6 +9164,7 @@ arm_force_fast_fault_with_flush_range(
+ }
+ }
+ write_pte_fast(pte_p, tmplate);
++ linux64_el0_mirror_pte(pmap, va, tmplate, pt_attr_page_size(pmap_get_pt_attr(pmap)) * PAGE_RATIO);
+ }
+
+ fff_skip_pve_pass1:
+@@ -8500,6 +9445,7 @@ arm_clear_fast_fault(
+ tlb_flush_needed = true;
+ }
+ write_pte_fast(pte_p, tmplate);
++ linux64_el0_mirror_pte(pmap, ptd_get_va(ptdp, pte_p), tmplate, pt_attr_page_size(pmap_get_pt_attr(pmap)) * PAGE_RATIO);
+ result = TRUE;
+ }
+
+@@ -8935,6 +9881,19 @@ pmap_map_cpu_windows_copy_internal(
+ need_strong_sync = pte_is_xs(native_pt_attr, pte);
+ #endif
+ write_pte_fast(ptep, pte);
++ if (linux64_el0 && pa_valid(ptoa(pn))) {
++ struct linux64_map_req req = {
++ .va = cpu_copywindow_vaddr,
++ .pa = ptoa(pn),
++ .size = PAGE_SIZE,
++ .prot = LINUX64_PROT_READ | ((prot & VM_PROT_WRITE) ? LINUX64_PROT_WRITE : 0),
++ };
++ linux64_call(LINUX64_CALL_KMAP, &req);
++ if (req.result < 0) {
++ panic("linux64_el0: cpu_copywindow KMAP failed va=0x%llx pa=0x%llx err=%lld",
++ (unsigned long long)cpu_copywindow_vaddr, (unsigned long long)ptoa(pn), (long long)req.result);
++ }
++ }
+ /*
+ * Invalidate tlb. Cover nested cpu_copywindow_vaddr usage with the interrupted context
+ * in pmap_unmap_cpu_windows_copy() after clearing the pte and before tlb invalidate.
+@@ -8977,6 +9936,10 @@ pmap_unmap_cpu_windows_copy_internal(
+ __builtin_arm_dsb(DSB_SY);
+ ptep = pmap_pte(kernel_pmap, cpu_copywindow_vaddr);
+ write_pte_strong(ptep, ARM_PTE_EMPTY);
++ if (linux64_el0) {
++ struct linux64_map_req req = { .va = cpu_copywindow_vaddr, .size = PAGE_SIZE };
++ linux64_call(LINUX64_CALL_KUNMAP, &req);
++ }
+ PMAP_UPDATE_TLBS(kernel_pmap, cpu_copywindow_vaddr, cpu_copywindow_vaddr + PAGE_SIZE, pmap_cpu_data->copywindow_strong_sync[index], true);
+ }
+
+@@ -9159,6 +10122,11 @@ pmap_set_nested_internal(
+ }
+
+ pmap_get_pt_ops(pmap)->free_id(pmap);
++ if (linux64_el0 && pmap->linux64_as) {
++ struct linux64_map_req req = { .as_handle = pmap->linux64_as };
++ linux64_call(LINUX64_CALL_AS_DESTROY, &req);
++ pmap->linux64_as = 0;
++ }
+ }
+
+ __mockable void
+@@ -9617,6 +10585,23 @@ pmap_sign_user_ptr_internal(void *value, ptrauth_key key, uint64_t discriminator
+ panic("attempt to sign user pointer without process independent key");
+ }
+
++ if (linux64_el0) {
++ struct linux64_user_pac_req req = {
++ .value = (uint64_t)(uintptr_t)value,
++ .discriminator = discriminator,
++ .jop_key = jop_key,
++ .result = 0,
++ .key = (key == ptrauth_key_asia) ? LINUX64_PAC_KEY_IA : LINUX64_PAC_KEY_DA,
++ .is_auth = 0,
++ .err = 0,
++ };
++ linux64_call(LINUX64_CALL_USER_PAC_OP, &req);
++ if (req.err != 0) {
++ panic("linux64_el0: pmap_sign_user_ptr failed (%d)", req.err);
++ }
++ return (void *)(uintptr_t)req.result;
++ }
++
+ void *res = NULL;
+ uint64_t current_intr_state = pmap_interrupts_disable();
+
+@@ -9655,6 +10640,23 @@ pmap_auth_user_ptr_internal(void *value, ptrauth_key key, uint64_t discriminator
+ panic("attempt to auth user pointer without process independent key");
+ }
+
++ if (linux64_el0) {
++ struct linux64_user_pac_req req = {
++ .value = (uint64_t)(uintptr_t)value,
++ .discriminator = discriminator,
++ .jop_key = jop_key,
++ .result = 0,
++ .key = (key == ptrauth_key_asia) ? LINUX64_PAC_KEY_IA : LINUX64_PAC_KEY_DA,
++ .is_auth = 1,
++ .err = 0,
++ };
++ linux64_call(LINUX64_CALL_USER_PAC_OP, &req);
++ if (req.err != 0) {
++ panic("linux64_el0: pmap_auth_user_ptr failed (%d)", req.err);
++ }
++ return (void *)(uintptr_t)req.result;
++ }
++
+ void *res = NULL;
+ uint64_t current_intr_state = pmap_interrupts_disable();
+
+@@ -10442,6 +11444,10 @@ unnest_subord_done:
+ }
+
+ FLUSH_PTE_STRONG();
++ if (linux64_el0 && grand != kernel_pmap && grand->linux64_as && addr > start) {
++ struct linux64_map_req req = { .as_handle = grand->linux64_as, .va = start, .size = addr - start };
++ linux64_call(LINUX64_CALL_AS_UNMAP, &req);
++ }
+ PMAP_UPDATE_TLBS(grand, start, addr, false, false);
+
+ pmap_unlock(grand, PMAP_LOCK_EXCLUSIVE);
+@@ -12980,6 +13986,8 @@ pmap_user_va_bits(pmap_t pmap __unused)
+ #if __ARM_MIXED_PAGE_SIZE__
+ uint64_t tcr_value = pmap_get_pt_attr(pmap)->pta_tcr_value;
+ return 64 - ((tcr_value >> TCR_T0SZ_SHIFT) & TCR_TSZ_MASK);
++#elif !__ARM_16K_PG__ && !ARM_PARAMETERIZED_PMAP
++ return 64 - T0SZ_HW; /* LINUX64: user pmaps walk from level 0 (pmap_pt_attr_4k_user) */
+ #else
+ return 64 - T0SZ_BOOT;
+ #endif
+@@ -14853,7 +15861,9 @@ pmap_test_access(pmap_t pmap, vm_map_address_t va, bool should_fault, bool is_wr
+
+ /* Disable PAN; pmap shouldn't be the kernel pmap. */
+ #if __ARM_PAN_AVAILABLE__
+- __builtin_arm_wsr("pan", 0);
++ if (!linux64_el0) {
++ __builtin_arm_wsr("pan", 0);
++ }
+ #endif /* __ARM_PAN_AVAILABLE__ */
+ }
+
+@@ -14872,7 +15882,9 @@ pmap_test_access(pmap_t pmap, vm_map_address_t va, bool should_fault, bool is_wr
+
+ if (pmap != NULL) {
+ #if __ARM_PAN_AVAILABLE__
+- __builtin_arm_wsr("pan", 1);
++ if (!linux64_el0) {
++ __builtin_arm_wsr("pan", 1);
++ }
+ #endif /* __ARM_PAN_AVAILABLE__ */
+
+ pmap_switch(old_pmap, thread);
+diff --git a/osfmk/arm/pmap/pmap.h b/osfmk/arm/pmap/pmap.h
+index b236ca6..a3fe011 100644
+--- a/osfmk/arm/pmap/pmap.h
++++ b/osfmk/arm/pmap/pmap.h
+@@ -350,6 +350,7 @@ struct pmap {
+ */
+ tt_entry_t *hw_tte;
+ pmap_paddr_t hw_ttep;
++ uint64_t linux64_as; /* EL0 host: opaque user address space handle */
+
+ /*
+ * The min and max fields represent the lowest and highest addressable VAs
+@@ -923,4 +924,13 @@ extern kern_return_t pmap_test_text_corruption(pmap_paddr_t);
+
+ #endif /* __ARM_KERNEL_PROTECT__ */
+
++#if !defined(ASSEMBLER) && !defined(__ASSEMBLER__)
++extern bool linux64_el0_sync_user_pte(pmap_t pmap, vm_offset_t far, uint64_t esr);
++extern bool linux64_el0_user_vtop(pmap_t pmap, vm_offset_t va, bool write, pmap_paddr_t *pa_out);
++extern bool linux64_el0_copyio_chunk(pmap_t pmap, vm_offset_t uaddr, bool write, void *bounce, size_t max_len, size_t *out_len);
++extern bool linux64_el0_atomic_op(pmap_t pmap, vm_offset_t uaddr, bool write, size_t width, uint64_t *val);
++extern bool linux64_el0_verify_write(const void *source, void *dst, size_t size);
++extern uint64_t linux64_el0_ensure_as(pmap_t pmap);
++#endif
++
+ #endif /* #ifndef _ARM_PMAP_H_ */
+diff --git a/osfmk/arm/pmap/pmap_internal.h b/osfmk/arm/pmap/pmap_internal.h
+index 2aa40c1..9a4fe53 100644
+--- a/osfmk/arm/pmap/pmap_internal.h
++++ b/osfmk/arm/pmap/pmap_internal.h
+@@ -433,9 +433,14 @@ pmap_unlock(pmap_t pmap, pmap_lock_mode_t mode)
+ * @return The previous interrupt state, to be restored with
+ * pmap_interrupts_restore().
+ */
++extern unsigned int linux64_el0;
++
+ static inline uint64_t __attribute__((warn_unused_result)) __used
+ pmap_interrupts_disable(void)
+ {
++ if (linux64_el0) {
++ return DAIF_ALL;
++ }
+ uint64_t state = __builtin_arm_rsr64("DAIF");
+
+ /* Ensure that debug exceptions are masked. */
+@@ -456,6 +461,9 @@ pmap_interrupts_disable(void)
+ static inline void __used
+ pmap_interrupts_restore(uint64_t state)
+ {
++ if (linux64_el0) {
++ return;
++ }
+ // no unknown bits?
+ assert((state & ~DAIF_ALL) == 0);
+
+@@ -481,6 +489,9 @@ pmap_interrupts_restore(uint64_t state)
+ static inline bool __attribute__((warn_unused_result)) __used
+ pmap_interrupts_enabled(void)
+ {
++ if (linux64_el0) {
++ return false;
++ }
+ return (__builtin_arm_rsr64("DAIF") & DAIF_ALL) != DAIF_ALL;
+ }
+ #endif /* __arm64__ */
+diff --git a/osfmk/arm/pmap/pmap_pt_geometry.h b/osfmk/arm/pmap/pmap_pt_geometry.h
+index fc64830..aaff3fb 100644
+--- a/osfmk/arm/pmap/pmap_pt_geometry.h
++++ b/osfmk/arm/pmap/pmap_pt_geometry.h
+@@ -169,7 +169,14 @@ extern const struct page_table_ops native_pt_ops;
+ #else /* ARM_PARAMETERIZED_PMAP */
+
+ /* The page table attributes are fixed (to allow for const propagation) */
++#if !__ARM_16K_PG__
++/* LINUX64 (xnulinux): user pmaps walk from level 0 over 47 bits, the kernel pmap from level 1 (pmap.c, pmap_pt_attr_4k_user) */
++extern const struct page_table_attr * const user_pt_attr;
++extern const pmap_t kernel_pmap; /* as in vm/pmap.h, which not every includer of this header has */
++#define pmap_get_pt_attr(pmap) ((pmap) == kernel_pmap ? native_pt_attr : user_pt_attr)
++#else
+ #define pmap_get_pt_attr(pmap) (native_pt_attr)
++#endif
+ #define pmap_get_pt_ops(pmap) (&native_pt_ops)
+
+ #endif /* ARM_PARAMETERIZED_PMAP */
+diff --git a/osfmk/arm/preemption_disable.c b/osfmk/arm/preemption_disable.c
+index 93fe829..2e62b07 100644
+--- a/osfmk/arm/preemption_disable.c
++++ b/osfmk/arm/preemption_disable.c
+@@ -32,6 +32,7 @@
+ */
+
+ #include <arm/cpu_data.h>
++#include <linux64/linux64.h>
+ #include <arm/cpu_data_internal.h>
+ #include <arm/preemption_disable_internal.h>
+ #include <kern/cpu_data.h>
+@@ -68,6 +69,18 @@ kernel_preempt_check(void)
+ {
+ uint64_t state;
+
++ if (linux64_el0) {
++ if (!ml_get_interrupts_enabled()) {
++ return;
++ }
++ ml_set_interrupts_enabled(FALSE);
++ if (current_thread()->machine.CpuDatap->cpu_pending_ast & AST_URGENT) {
++ ast_taken_kernel();
++ }
++ ml_set_interrupts_enabled(TRUE);
++ return;
++ }
++
+ /* If interrupts are masked, we can't take an AST here */
+ state = __builtin_arm_rsr64("DAIF");
+ if (state & DAIF_IRQF) {
+diff --git a/osfmk/arm/rtclock.c b/osfmk/arm/rtclock.c
+index a17a07d..81e5f76 100644
+--- a/osfmk/arm/rtclock.c
++++ b/osfmk/arm/rtclock.c
+@@ -38,6 +38,7 @@
+ */
+
+ #include <mach/mach_types.h>
++#include <linux64/linux64.h>
+
+ #include <kern/clock.h>
+ #include <kern/thread.h>
+@@ -327,6 +328,7 @@ rtclock_intr(__unused unsigned int is_user_context)
+ struct arm_saved_state * regs;
+ unsigned int user_mode;
+ uintptr_t pc;
++ linux64_count(LINUX64_CTR_RTCLOCK); /* LINUX64: for the host's monitor */
+
+ #if XNU_NATIVE_DWC3_CONSOLE
+ extern void unixnu_dwc3_poll(void);
+@@ -366,6 +368,15 @@ rtclock_intr(__unused unsigned int is_user_context)
+ pc = 0;
+ user_mode = 0;
+ }
++ uint64_t sample_fp = regs ? get_saved_state_fp(regs) : 0;
++ if (regs == NULL && linux64_hook) {
++ /*
++ * LINUX64: hosted, a kernel-mode timer is delivered by a call from where XNU re-enables interrupts (or from idle),
++ * not by an exception with a saved state: profile the caller (pc-sample charges it to the code that masked).
++ */
++ pc = (uintptr_t)__builtin_return_address(0);
++ sample_fp = *(uint64_t *)__builtin_frame_address(0);
++ }
+ if (abstime >= cdp->rtcPop) {
+ /* Log the interrupt service latency (-ve value expected by tool) */
+ KDBG_RELEASE(DECR_TRAP_LATENCY | DBG_FUNC_NONE,
+@@ -375,7 +386,7 @@ rtclock_intr(__unused unsigned int is_user_context)
+
+ /* bring-up profiling (boot-arg pc-sample, osfmk/kern/exception.c) */
+ extern void virt_pc_sample(uint64_t pc, uint64_t fp, unsigned int user_mode, uint32_t decrementer, bool due);
+- virt_pc_sample(pc, regs ? get_saved_state_fp(regs) : 0, user_mode, cdp->cpu_decrementer, abstime >= cdp->rtcPop);
++ virt_pc_sample(pc, sample_fp, user_mode, cdp->cpu_decrementer, abstime >= cdp->rtcPop);
+
+ /* call the generic etimer */
+ timer_intr(user_mode, pc);
+diff --git a/osfmk/arm/thread.h b/osfmk/arm/thread.h
+index 29ea6d8..b60ee80 100644
+--- a/osfmk/arm/thread.h
++++ b/osfmk/arm/thread.h
+@@ -180,7 +180,7 @@ struct machine_thread {
+ uint64_t reserved11;
+ #endif
+
+- uint64_t reserved12;
++ uint64_t linux64_user_tpidr;
+
+ #if HAS_ARM_FEAT_SME
+ uint64_t tpidr2_el0;
+diff --git a/osfmk/arm64/arm_vm_init.c b/osfmk/arm64/arm_vm_init.c
+index f7f387e..beedde7 100644
+--- a/osfmk/arm64/arm_vm_init.c
++++ b/osfmk/arm64/arm_vm_init.c
+@@ -28,6 +28,7 @@
+
+ extern volatile unsigned long long port_crumb; /* port bring-up breadcrumb (link_compat.c) */
+ #include <mach_kdp.h>
++#include <linux64/linux64.h>
+ #include <debug.h>
+
+ #include <kern/assert.h>
+@@ -404,6 +405,21 @@ phystokv(pmap_paddr_t pa)
+ return pa - gPhysBase + gVirtBase;
+ }
+
++pmap_paddr_t linux64_el0_ptov_vtop(vm_offset_t va);
++pmap_paddr_t
++linux64_el0_ptov_vtop(vm_offset_t va)
++{
++ for (size_t i = 0; (i < PTOV_TABLE_SIZE) && (ptov_table[i].len != 0); i++) {
++ if ((va >= ptov_table[i].va) && (va < (ptov_table[i].va + ptov_table[i].len))) {
++ return (pmap_paddr_t)(va - ptov_table[i].va) + ptov_table[i].pa;
++ }
++ }
++ if ((va >= gVirtBase) && (va < (gVirtBase + real_phys_size))) {
++ return (pmap_paddr_t)(va - gVirtBase) + gPhysBase;
++ }
++ return 0;
++}
++
+ vm_map_address_t
+ phystokv_range(pmap_paddr_t pa, vm_size_t *max_len)
+ {
+@@ -429,6 +445,7 @@ phystokv_range(pmap_paddr_t pa, vm_size_t *max_len)
+ return pa - gPhysBase + gVirtBase;
+ }
+
++
+ vm_offset_t
+ ml_static_vtop(vm_offset_t va)
+ {
+@@ -1089,7 +1106,8 @@ arm_vm_page_granular_helper(vm_offset_t start, vm_offset_t _end, vm_offset_t va,
+ /*
+ * Set the 'guarded page' flag to enable ARM BTI enforcement.
+ */
+- if (guarded) {
++ /* LINUX64: Linux enables SCTLR_EL1.BT1, and this kernel is not built with BTI landing pads. */
++ if (guarded && !linux64_hook) {
+ ptmp |= ARM_PTE_GP;
+ }
+ #endif /* BTI_ENFORCED */
+@@ -1638,6 +1656,25 @@ arm_vm_physmap_init(boot_args *args)
+ ptov_table_entry temp_ptov_table[PTOV_TABLE_SIZE];
+ bzero(temp_ptov_table, sizeof(temp_ptov_table));
+
++ if (linux64_el0) {
++ /*
++ * Pure EL0 host: reuse the permanent 2 MiB linear aperture
++ * [gVirtBase, gVirtBase + real_phys_size) directly as physmap so
++ * large-RAM boots (>= 6 GiB) do not duplicate physmap VA space.
++ */
++ if (segLOWEST > gVirtBase) {
++ arm_vm_page_granular_RWNX(gVirtBase, segLOWEST - gVirtBase,
++ ARM64_GRANULE_ALLOW_BLOCK | ARM64_GRANULE_ALLOW_HINT);
++ }
++ arm_vm_page_granular_RWNX(end_kern, (gVirtBase + real_phys_size) - end_kern,
++ ARM64_GRANULE_ALLOW_BLOCK | ARM64_GRANULE_ALLOW_HINT);
++ temp_ptov_table[0].pa = gPhysBase;
++ temp_ptov_table[0].va = gVirtBase;
++ temp_ptov_table[0].len = real_phys_size;
++ memcpy(ptov_table, temp_ptov_table, sizeof(ptov_table));
++ return;
++ }
++
+ // Will be handed back to VM layer through ml_static_mfree() in arm_vm_prot_finalize()
+ arm_vm_physmap_slide(temp_ptov_table, gVirtBase, segLOWEST - gVirtBase, AP_RWNA,
+ ARM64_GRANULE_ALLOW_BLOCK | ARM64_GRANULE_ALLOW_HINT);
+@@ -1888,6 +1925,13 @@ arm_vm_init(uint64_t memory_size, boot_args * args)
+ port_crumb = 51;
+
+ physmap_base += physmap_slide;
++ if (linux64_el0) {
++ /*
++ * Pure EL0 host: reuse the already-mapped permanent 2 MiB linear
++ * aperture [gVirtBase, gVirtBase + real_phys_size) as physmap.
++ */
++ physmap_base = gVirtBase;
++ }
+
+ #if XNU_MONITOR
+ physmap_base = ROUND_TWIG(physmap_base);
+@@ -1908,8 +1952,13 @@ arm_vm_init(uint64_t memory_size, boot_args * args)
+ static_memory_end = phystokv(args->topOfKernelData);
+ physmap_end = physmap_base + real_phys_size;
+ #else
+- static_memory_end = physmap_base + mem_size + (PTOV_TABLE_SIZE * ARM_TT_TWIG_SIZE); // worst possible case for block alignment
+- physmap_end = physmap_base + real_phys_size + (PTOV_TABLE_SIZE * ARM_TT_TWIG_SIZE);
++ if (linux64_el0) {
++ physmap_end = gVirtBase + real_phys_size;
++ static_memory_end = ROUND_TWIG(gVirtBase + real_phys_size);
++ } else {
++ static_memory_end = physmap_base + mem_size + (PTOV_TABLE_SIZE * ARM_TT_TWIG_SIZE); // worst possible case for block alignment
++ physmap_end = physmap_base + real_phys_size + (PTOV_TABLE_SIZE * ARM_TT_TWIG_SIZE);
++ }
+ #endif // ARM_LARGE_MEMORY
+ #endif
+
+@@ -2194,14 +2243,53 @@ arm_vm_init(uint64_t memory_size, boot_args * args)
+
+ arm_vm_physmap_init(args);
+ port_crumb = 38;
+- set_mmu_ttb_alternate(cpu_ttep & TTBR_BADDR_MASK);
++ {
++ if (linux64_hook) {
++ if (!linux64_el0) {
++ /*
++ * LINUX64 (xnulinux): TTBR1 is Linux's. The host installs XNU's kernel L1 entries
++ * (the kernel VA range only) into Linux's top-level L1 table; TTBR0 stays Linux's.
++ */
++ linux64_call(LINUX64_CALL_KERNEL_TABLES, cpu_tte);
++ } else {
++ /*
++ * Pure EL0 host: mirror any ptov_table[] entry outside the already-mapped
++ * permanent linear aperture [gVirtBase, gVirtBase + real_phys_size).
++ */
++ for (size_t i = 0; (i < PTOV_TABLE_SIZE) && (ptov_table[i].len != 0); i++) {
++ if (ptov_table[i].va >= gVirtBase &&
++ ptov_table[i].va + ptov_table[i].len <= gVirtBase + real_phys_size) {
++ continue;
++ }
++ struct linux64_map_req req = {
++ .va = ptov_table[i].va,
++ .pa = ptov_table[i].pa,
++ .size = ptov_table[i].len,
++ .prot = LINUX64_PROT_READ | LINUX64_PROT_WRITE,
++ };
++ linux64_call(LINUX64_CALL_KMAP, &req);
++ if (req.result < 0) {
++ panic("linux64_el0: boot physmap KMAP failed va=0x%llx pa=0x%llx len=0x%llx err=%lld",
++ (unsigned long long)req.va, (unsigned long long)req.pa,
++ (unsigned long long)req.size, (long long)req.result);
++ }
++ }
++ }
++ } else {
++ set_mmu_ttb_alternate(cpu_ttep & TTBR_BADDR_MASK);
++ }
++ }
+ port_crumb = 39;
+
+ #if XNU_MONITOR
+ ml_enable_monitor();
+ #endif
+
+- set_mmu_ttb(invalid_ttep & TTBR_BADDR_MASK);
++ {
++ if (!linux64_hook) {
++ set_mmu_ttb(invalid_ttep & TTBR_BADDR_MASK);
++ }
++ }
+
+ flush_mmu_tlb();
+ port_crumb = 40;
+@@ -2267,9 +2355,14 @@ arm_vm_init(uint64_t memory_size, boot_args * args)
+ vm_kernel_etext = segTEXTEXECB + segSizeTEXTEXEC;
+ vm_kernel_slid_top = vm_slinkedit;
+ } else {
+- assert(segDATACONSTB == segTEXTB + segSizeTEXT);
+- assert(segTEXTEXECB == segDATACONSTB + segSizeDATACONST);
+- vm_kernel_etext = segTEXTB + segSizeTEXT + segSizeDATACONST + segSizeTEXTEXEC;
++ if (linux64_hook) {
++ /* LINUX64: this kernel is linked with the KC segment layout (k27): segments are not adjacent. */
++ vm_kernel_etext = segTEXTEXECB + segSizeTEXTEXEC;
++ } else {
++ assert(segDATACONSTB == segTEXTB + segSizeTEXT);
++ assert(segTEXTEXECB == segDATACONSTB + segSizeDATACONST);
++ vm_kernel_etext = segTEXTB + segSizeTEXT + segSizeDATACONST + segSizeTEXTEXEC;
++ }
+ vm_kernel_slid_top = vm_prelink_einfo;
+ }
+
+diff --git a/osfmk/arm64/asm.h b/osfmk/arm64/asm.h
+index 84deb3f..6d9cb11 100644
+--- a/osfmk/arm64/asm.h
++++ b/osfmk/arm64/asm.h
+@@ -135,7 +135,7 @@
+ .endmacro
+
+ .macro READ_THREAD
+- mrs $0, TPIDR_EL1
++ mrs $0, TPIDR_EL0
+ .endmacro
+
+ .macro BRANCH_EXTERN
+diff --git a/osfmk/arm64/caches_asm.s b/osfmk/arm64/caches_asm.s
+index 58a91a8..d0a8fdf 100644
+--- a/osfmk/arm64/caches_asm.s
++++ b/osfmk/arm64/caches_asm.s
+@@ -44,6 +44,13 @@
+ LEXT(InvalidatePoU_Icache)
+ LEXT(invalidate_mmu_icache)
+ ARM64_PROLOG
++ adrp x9, _linux64_el0@PAGE
++ ldr w9, [x9, _linux64_el0@PAGEOFF]
++ cbz w9, 9f
++ mov x0, #0
++ mov x1, #0
++ b EXT(linux64_el0_icache_flush)
++9:
+ dsb sy
+ ic ialluis // Invalidate icache
+ dsb sy
+@@ -61,6 +68,17 @@ LEXT(invalidate_mmu_icache)
+ LEXT(InvalidatePoU_IcacheRegion)
+ ARM64_STACK_PROLOG
+ PUSH_FRAME
++ adrp x9, _linux64_el0@PAGE
++ ldr w9, [x9, _linux64_el0@PAGEOFF]
++ cbz w9, 8f
++ mov w1, w1
++ stp x0, x1, [sp, #-16]!
++ bl EXT(CleanPoU_DcacheRegion)
++ ldp x0, x1, [sp], #16
++ bl EXT(linux64_el0_icache_flush)
++ POP_FRAME
++ ARM64_STACK_EPILOG EXT(InvalidatePoU_IcacheRegion)
++8:
+ bl EXT(CleanPoU_DcacheRegion)
+ #if __ARM_IC_NOALIAS_ICACHE__
+ mov x9, #((1<<MMU_I_CLINE)-1)
+@@ -214,6 +232,12 @@ L_ipui_loop:
+ .globl EXT(clean_mmu_dcache)
+ LEXT(CleanPoC_Dcache)
+ ARM64_PROLOG
++ adrp x9, _linux64_el0@PAGE
++ ldr w9, [x9, _linux64_el0@PAGEOFF]
++ cbz w9, 9f
++ dsb sy
++ ret
++9:
+ #if defined(APPLE_ARM64_ARCH_FAMILY)
+ dsb sy
+ ret
+@@ -234,6 +258,12 @@ LEXT(CleanPoC_Dcache)
+ .globl EXT(CleanPoU_Dcache)
+ LEXT(CleanPoU_Dcache)
+ ARM64_PROLOG
++ adrp x9, _linux64_el0@PAGE
++ ldr w9, [x9, _linux64_el0@PAGEOFF]
++ cbz w9, 9f
++ dsb sy
++ ret
++9:
+ #if defined(APPLE_ARM64_ARCH_FAMILY)
+ dsb sy
+ ret
+@@ -368,6 +398,12 @@ LEXT(CleanPoC_DcacheRegion_Force)
+ .globl EXT(FlushPoC_Dcache)
+ LEXT(FlushPoC_Dcache)
+ ARM64_PROLOG
++ adrp x9, _linux64_el0@PAGE
++ ldr w9, [x9, _linux64_el0@PAGEOFF]
++ cbz w9, 9f
++ dsb sy
++ ret
++9:
+ #if defined(APPLE_ARM64_ARCH_FAMILY)
+ dsb sy
+ ret
+@@ -388,6 +424,12 @@ LEXT(FlushPoC_Dcache)
+ .globl EXT(Flush_Dcache)
+ LEXT(Flush_Dcache)
+ ARM64_PROLOG
++ adrp x9, _linux64_el0@PAGE
++ ldr w9, [x9, _linux64_el0@PAGEOFF]
++ cbz w9, 9f
++ dsb sy
++ ret
++9:
+ mov x0, #6 // Maximum allowable caching level (0-based)
+ DCACHE_SET_WAY cisw
+
+@@ -401,6 +443,12 @@ LEXT(Flush_Dcache)
+ .globl EXT(FlushPoU_Dcache)
+ LEXT(FlushPoU_Dcache)
+ ARM64_PROLOG
++ adrp x9, _linux64_el0@PAGE
++ ldr w9, [x9, _linux64_el0@PAGEOFF]
++ cbz w9, 9f
++ dsb sy
++ ret
++9:
+ #if defined(APPLE_ARM64_ARCH_FAMILY)
+ dsb sy
+ ret
+diff --git a/osfmk/arm64/copyio.c b/osfmk/arm64/copyio.c
+index 506754c..08cab58 100644
+--- a/osfmk/arm64/copyio.c
++++ b/osfmk/arm64/copyio.c
+@@ -37,6 +37,8 @@
+ #include <san/kasan.h>
+ #include <arm/pmap.h>
+ #include <arm64/speculation.h>
++#include <linux64/linux64.h>
++#include <vm/vm_fault.h>
+
+ #undef copyin
+ #undef copyout
+@@ -120,6 +122,9 @@ unprivileged_user_access_disable(__unused user_access_direction_t user_access_di
+ static inline void
+ user_access_enable(__unused user_access_direction_t user_access_direction, pmap_t __unused pmap)
+ {
++ if (linux64_el0) {
++ return;
++ }
+ #if __ARM_PAN_AVAILABLE__
+ assert(__builtin_arm_rsr("pan") != 0);
+ __builtin_arm_wsr("pan", 0);
+@@ -130,12 +135,64 @@ user_access_enable(__unused user_access_direction_t user_access_direction, pmap_
+ static inline void
+ user_access_disable(__unused user_access_direction_t user_access_direction, pmap_t __unused pmap)
+ {
++ if (linux64_el0) {
++ return;
++ }
+ #if __ARM_PAN_AVAILABLE__
+ __builtin_arm_wsr("pan", 1);
+ #endif /* __ARM_PAN_AVAILABLE__ */
+
+ }
+
++static int
++linux64_el0_fault_user_page(vm_map_t map, user_addr_t uaddr, bool write)
++{
++ extern kern_return_t arm_fast_fault(pmap_t pmap, vm_map_address_t va,
++ vm_prot_t fault_type, bool was_af_fault, bool from_user);
++ vm_prot_t fault_type = write ? (VM_PROT_READ | VM_PROT_WRITE) : VM_PROT_READ;
++
++ if (arm_fast_fault(map->pmap, (vm_map_address_t)(uaddr & ~0xfffULL),
++ fault_type, FALSE, FALSE) == KERN_SUCCESS) {
++ return 0;
++ }
++ if (vm_fault(map, (vm_map_offset_t)(uaddr & ~0xfffULL), fault_type,
++ FALSE, VM_KERN_MEMORY_NONE, THREAD_UNINT, NULL, 0) != KERN_SUCCESS) {
++ return EFAULT;
++ }
++ return 0;
++}
++
++static int
++linux64_el0_copy_chunk_with_fault(vm_map_t map, user_addr_t uaddr, bool write,
++ void *bounce, size_t max_len, size_t *out_len)
++{
++ for (int attempt = 0; attempt < 4; attempt++) {
++ if (linux64_el0_copyio_chunk(map->pmap, (vm_offset_t)uaddr, write, bounce, max_len, out_len)) {
++ return 0;
++ }
++ int err = linux64_el0_fault_user_page(map, uaddr, write);
++ if (err) {
++ return err;
++ }
++ }
++ return linux64_el0_copyio_chunk(map->pmap, (vm_offset_t)uaddr, write, bounce, max_len, out_len) ? 0 : EFAULT;
++}
++
++static int
++linux64_el0_atomic_with_fault(vm_map_t map, user_addr_t uaddr, bool write, size_t width, uint64_t *val)
++{
++ for (int attempt = 0; attempt < 4; attempt++) {
++ if (linux64_el0_atomic_op(map->pmap, (vm_offset_t)uaddr, write, width, val)) {
++ return 0;
++ }
++ int err = linux64_el0_fault_user_page(map, uaddr, write);
++ if (err) {
++ return err;
++ }
++ }
++ return linux64_el0_atomic_op(map->pmap, (vm_offset_t)uaddr, write, width, val) ? 0 : EFAULT;
++}
++
+ #if HAS_MTE
+ static inline bool
+ userspace_access_is_tagged(vm_map_t map)
+@@ -422,6 +479,26 @@ copyin(const user_addr_t user_addr, void *kernel_addr, vm_size_t nbytes)
+
+ guarded_user_addr = copy_ensure_address_space_spec(map, user_addr);
+
++ if (linux64_el0) {
++ uint8_t bounce[512];
++ char *dst = (char *)kernel_addr;
++ user_addr_t u = guarded_user_addr;
++ vm_size_t rem = nbytes;
++ while (rem > 0) {
++ size_t want = rem < sizeof(bounce) ? (size_t)rem : sizeof(bounce);
++ size_t chunk = 0;
++ int err = linux64_el0_copy_chunk_with_fault(map, u, false, bounce, want, &chunk);
++ if (err) {
++ return err;
++ }
++ bcopy(bounce, dst, chunk);
++ dst += chunk;
++ u += chunk;
++ rem -= chunk;
++ }
++ return 0;
++ }
++
+ return WRAP_COPYIO(USER_ACCESS_READ, map,
+ _bcopyin(guarded_user_addr, kernel_addr, nbytes));
+ }
+@@ -443,6 +520,16 @@ copyin_atomic32(const user_addr_t user_addr, uint32_t *kernel_addr)
+
+ user_addr_t guarded_user_addr = copy_ensure_address_space_spec(map, user_addr);
+
++ if (linux64_el0) {
++ uint64_t val = 0;
++ int err = linux64_el0_atomic_with_fault(map, guarded_user_addr, false, 4, &val);
++ if (err) {
++ return err;
++ }
++ *kernel_addr = (uint32_t)val;
++ return 0;
++ }
++
+ return WRAP_COPYIO(USER_ACCESS_READ, map,
+ _copyin_atomic32(guarded_user_addr, kernel_addr));
+ }
+@@ -495,6 +582,15 @@ copyin_atomic32_wait_if_equals(const user_addr_t user_addr, uint32_t value)
+
+ user_addr_t guarded_user_addr = copy_ensure_address_space_spec(map, user_addr);
+
++ if (linux64_el0) {
++ uint64_t cur = 0;
++ int err = linux64_el0_atomic_with_fault(map, guarded_user_addr, false, 4, &cur);
++ if (err) {
++ return err;
++ }
++ return ((uint32_t)cur == value) ? 0 : ESTALE;
++ }
++
+ return WRAP_COPYIO(USER_ACCESS_READ, map,
+ _copyin_atomic32_wait_if_equals(guarded_user_addr, value));
+ }
+@@ -511,6 +607,16 @@ copyin_atomic64(const user_addr_t user_addr, uint64_t *kernel_addr)
+
+ user_addr_t guarded_user_addr = copy_ensure_address_space_spec(map, user_addr);
+
++ if (linux64_el0) {
++ uint64_t val = 0;
++ int err = linux64_el0_atomic_with_fault(map, guarded_user_addr, false, 8, &val);
++ if (err) {
++ return err;
++ }
++ *kernel_addr = val;
++ return 0;
++ }
++
+ return WRAP_COPYIO(USER_ACCESS_READ, map,
+ _copyin_atomic64(guarded_user_addr, kernel_addr));
+ }
+@@ -527,6 +633,11 @@ copyout_atomic32(uint32_t value, user_addr_t user_addr)
+
+ user_addr_t guarded_user_addr = copy_ensure_address_space_spec(map, user_addr);
+
++ if (linux64_el0) {
++ uint64_t val = value;
++ return linux64_el0_atomic_with_fault(map, guarded_user_addr, true, 4, &val);
++ }
++
+ return WRAP_COPYIO(USER_ACCESS_WRITE, map,
+ _copyout_atomic32(value, guarded_user_addr));
+ }
+@@ -543,6 +654,11 @@ copyout_atomic64(uint64_t value, user_addr_t user_addr)
+
+ user_addr_t guarded_user_addr = copy_ensure_address_space_spec(map, user_addr);
+
++ if (linux64_el0) {
++ uint64_t val = value;
++ return linux64_el0_atomic_with_fault(map, guarded_user_addr, true, 8, &val);
++ }
++
+ return WRAP_COPYIO(USER_ACCESS_WRITE, map,
+ _copyout_atomic64(value, guarded_user_addr));
+ }
+@@ -566,6 +682,32 @@ copyinstr(const user_addr_t user_addr, char *kernel_addr, vm_size_t nbytes, vm_s
+
+ user_addr_t guarded_user_addr = copy_ensure_address_space_spec(map, user_addr);
+
++ if (linux64_el0) {
++ char bounce[512];
++ user_addr_t u = guarded_user_addr;
++ vm_size_t rem = nbytes;
++ while (rem > 0) {
++ size_t want = rem < sizeof(bounce) ? (size_t)rem : sizeof(bounce);
++ size_t chunk = 0;
++ int err = linux64_el0_copy_chunk_with_fault(map, u, false, bounce, want, &chunk);
++ if (err) {
++ return err;
++ }
++ for (size_t i = 0; i < chunk; i++) {
++ char c = bounce[i];
++ kernel_addr[bytes_copied++] = c;
++ if (c == '\0') {
++ *lencopied = bytes_copied;
++ return 0;
++ }
++ }
++ u += chunk;
++ rem -= chunk;
++ }
++ *lencopied = bytes_copied;
++ return ENAMETOOLONG;
++ }
++
+ result = WRAP_COPYIO(USER_ACCESS_READ, map,
+ _bcopyinstr(guarded_user_addr, kernel_addr, nbytes, &bytes_copied));
+
+@@ -598,6 +740,33 @@ copyout(const void *kernel_addr, user_addr_t user_addr, vm_size_t nbytes)
+
+ guarded_user_addr = copy_ensure_address_space_spec(map, user_addr);
+
++ if (linux64_el0) {
++ uint8_t bounce[512];
++ const char *src = (const char *)kernel_addr;
++ user_addr_t u = guarded_user_addr;
++ vm_size_t rem = nbytes;
++ while (rem > 0) {
++ size_t off = (size_t)(u & 0xfffULL);
++ size_t want = 4096 - off;
++ if (want > sizeof(bounce)) {
++ want = sizeof(bounce);
++ }
++ if (want > rem) {
++ want = (size_t)rem;
++ }
++ bcopy(src, bounce, want);
++ size_t chunk = 0;
++ int err = linux64_el0_copy_chunk_with_fault(map, u, true, bounce, want, &chunk);
++ if (err) {
++ return err;
++ }
++ src += chunk;
++ u += chunk;
++ rem -= chunk;
++ }
++ return 0;
++ }
++
+ return WRAP_COPYIO(USER_ACCESS_WRITE, map,
+ _bcopyout(kernel_addr, guarded_user_addr, nbytes));
+ }
+@@ -619,6 +788,9 @@ int
+ verify_write(const void *source, void *dst, size_t size)
+ {
+ int rc;
++ if (linux64_el0) {
++ return linux64_el0_verify_write(source, dst, size) ? 0 : EFAULT;
++ }
+ disable_preemption();
+ rc = _bcopyout((const char*)source, (user_addr_t)dst, size);
+ enable_preemption();
+diff --git a/osfmk/arm64/cpu.c b/osfmk/arm64/cpu.c
+index d10d7a1..91f6577 100644
+--- a/osfmk/arm64/cpu.c
++++ b/osfmk/arm64/cpu.c
+@@ -32,6 +32,7 @@
+ */
+
+ #include <pexpert/arm64/board_config.h>
++#include <linux64/linux64.h>
+ #include <kern/kalloc.h>
+ #include <kern/machine.h>
+ #include <kern/cpu_number.h>
+@@ -100,6 +101,7 @@ extern void __attribute__((noreturn)) arm64_prepare_for_sleep(boolean_t deep_sle
+ extern void __attribute__((noreturn)) arm64_prepare_for_sleep(boolean_t deep_sleep);
+ #endif
+ extern void arm64_force_wfi_clock_gate(void);
++extern void rtclock_intr(unsigned int);
+ #if defined(APPLETYPHOON)
+ // <rdar://problem/15827409>
+ extern void typhoon_prepare_for_wfi(void);
+@@ -389,6 +391,9 @@ cpu_sleep(void)
+ bool
+ cpu_interrupt_is_pending(void)
+ {
++ if (linux64_el0) {
++ return false;
++ }
+ uint64_t isr_value;
+ isr_value = __builtin_arm_rsr64("ISR_EL1");
+ return isr_value != 0;
+@@ -430,6 +435,11 @@ wfe_to_deadline_or_interrupt(uint32_t cid, uint64_t wfe_deadline, cpu_data_t *cd
+ * another core/cluster in a powergated state.
+ * Hence, optionally unmask IRQs+FIQs across WFE.
+ */
++ {
++ if (linux64_hook) {
++ unmask = false; /* LINUX64: never unmask hardware IRQs while hosted */
++ }
++ }
+ if (unmask) {
+ /* Latch SW IRQ+FIQ counter prior to unmasking
+ * interrupts.
+@@ -494,6 +504,37 @@ wfe_to_deadline_or_interrupt(uint32_t cid, uint64_t wfe_deadline, cpu_data_t *cd
+ return ipending || (nirqc != irqc);
+ }
+
++/*
++ * LINUX64 (xnulinux): hosted, idle goes straight to the host, which runs Linux until XNU's next timer deadline and
++ * comes back; the due timer is then delivered here as its interrupt would be. No WFE/WFI and no timer interrupt of
++ * XNU's own apply (idle_enable stays FALSE without the CPU kext: cpu_machine_init never runs).
++ */
++static void
++linux64_cpu_idle(cpu_data_t *cpu_data_ptr)
++{
++ uint64_t now = mach_absolute_time();
++ uint64_t deadline = cpu_data_ptr->rtcPop;
++ uint64_t ns = 0; /* a timer already due: no sleep, only let Linux take its interrupts */
++
++ linux64_count(LINUX64_CTR_CPU_IDLE);
++ if (deadline == 0 || deadline == EndOfAllTime) {
++ ns = NSEC_PER_MSEC; /* no timer armed: check the run queue again in 1 ms */
++ } else if (deadline > now) {
++ /* relative: XNU's timebase (mach_absolute_time) is offset from the host's counter */
++ absolutetime_to_nanoseconds(deadline - now, &ns);
++ }
++ if (linux64_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 */
++ }
++ linux64_count(LINUX64_CTR_HOST_IDLE);
++ 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);
++}
++
+ /*
+ * Routine: cpu_idle
+ * Function:
+@@ -506,6 +547,9 @@ cpu_idle(void)
+ uint64_t new_idle_timeout_ticks = 0x0ULL, lastPop;
+ bool idle_disallowed = false;
+
++ if (linux64_hook) {
++ linux64_cpu_idle(cpu_data_ptr);
++ }
+ if (__improbable((!idle_enable))) {
+ idle_disallowed = true;
+ os_atomic_inc(&virt_idle_disallowed[0], relaxed);
+@@ -1004,7 +1048,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..ff1f9fc 100644
+--- a/osfmk/arm64/cswitch.s
++++ b/osfmk/arm64/cswitch.s
+@@ -185,7 +185,7 @@
+ * arg2 - Scratch register
+ */
+ .macro set_thread_registers
+- msr TPIDR_EL1, $0 // Write new thread pointer to TPIDR_EL1
++ msr TPIDR_EL0, $0 // LINUX64: kernel thread pointer in TPIDR_EL0 (readable/writable at EL0 & EL1)
+ ldr $1, [$0, ACT_CPUDATAP]
+ str $0, [$1, CPU_ACTIVE_THREAD]
+
+@@ -212,16 +212,14 @@
+ * Note that if any bits are added to TPIDR_EL0 that the bootstrap
+ * or idle thread may care about, this will need to change.
+ */
+- ldr $2, [$1, CPU_TPIDR_EL0] // Load encoded CPU info ...
+- mrs $1, TPIDR_EL0
+- bfi $1, $2, #0, #MACHDEP_TPIDR_CPU_DATA_COUNT
+- msr TPIDR_EL0, $1 // ... into the lower bits.
+-
+- ldr $1, [$0, TH_CTH_SELF] // Get cthread pointer
+- msr TPIDRRO_EL0, $1
+-
++ adrp $2, _linux64_el0@PAGE
++ add $2, $2, _linux64_el0@PAGEOFF
++ ldr $2, [$2]
++ tst $2, #1
++ b.ne 1f
+ ldr $1, [$0, TH_THREAD_ID] // Save the bottom 32-bits of the thread ID into
+ msr CONTEXTIDR_EL1, $1 // CONTEXTIDR_EL1 (top 32-bits are RES0).
++1:
+ .endmacro
+
+ #define CSWITCH_ROP_KEYS (HAS_APPLE_PAC && HAS_PARAVIRTUALIZED_PAC)
+@@ -333,7 +331,7 @@ LEXT(machine_load_context)
+
+ LEXT(Call_continuation)
+ ARM64_PROLOG
+- mrs x4, TPIDR_EL1 // Get the current thread pointer
++ mrs x4, TPIDR_EL0 // Get the current thread pointer
+
+ /* ARM64_TODO arm loads the kstack top instead of arg4. What should we use? */
+ LOAD_KERN_STACK_TOP dst=x5, src=x4, tmp=x6
+@@ -359,7 +357,7 @@ LEXT(Call_continuation)
+ #else
+ blr x20 // Branch to the continuation
+ #endif
+- mrs x0, TPIDR_EL1 // Get the current thread pointer
++ mrs x0, TPIDR_EL0 // Get the current thread pointer
+ b EXT(thread_terminate) // Kill the thread
+
+
+@@ -394,7 +392,7 @@ Lswitch_threads:
+
+ LEXT(Shutdown_context)
+ ARM64_PROLOG
+- mrs x10, TPIDR_EL1 // Get thread pointer
++ mrs x10, TPIDR_EL0 // Get thread pointer
+ LOAD_KERN_STACK_TOP dst=x11, src=x10, tmp=x12 // Get the top of the kernel stack
+ save_general_registers x11, 12
+ msr DAIFSet, #(DAIFSC_STANDARD_DISABLE) // Disable interrupts
+@@ -412,7 +410,7 @@ LEXT(Shutdown_context)
+
+ LEXT(Idle_context)
+ ARM64_PROLOG
+- mrs x0, TPIDR_EL1 // Get thread pointer
++ mrs x0, TPIDR_EL0 // Get thread pointer
+ LOAD_KERN_STACK_TOP dst=x1, src=x0, tmp=x2 // Get the top of the kernel stack
+ save_general_registers x1, 2
+ LOAD_INT_STACK_THREAD dst=x2, src=x0, tmp=x1
+@@ -429,7 +427,7 @@ LEXT(Idle_context)
+
+ LEXT(Idle_load_context)
+ ARM64_PROLOG
+- mrs x0, TPIDR_EL1 // Get thread pointer
++ mrs x0, TPIDR_EL0 // Get thread pointer
+ LOAD_KERN_STACK_TOP dst=x1, src=x0, tmp=x2 // Get the top of the kernel stack
+ load_general_registers x1, 2
+ set_process_dependent_keys_and_sync_context x0, x1, x2, x3, w4
+@@ -444,3 +442,216 @@ LEXT(machine_set_current_thread)
+
+
+ /* vim: set ts=4: */
++
++/*
++ * LINUX64 (xnulinux): user space while hosted. linux64_el0_run(ss) enters EL0 with the user state in ss
++ * (IRQs stay masked at EL0), on this CPU, with VBAR_EL1 pointing at linux64_el0_vectors and SP_EL0 holding the
++ * user sp. What the kernels need back on the next exception from EL0 (XNU's thread pointer, which TPIDRRO_EL0 holds in
++ * the kernel and the user's TSD at EL0; Linux's vectors, its `current` in SP_EL0, its shadow call stack in x18 and
++ * SCTLR_EL1) goes in a block at the top of the thread's kernel stack, where SP_EL1 points at that exception: per thread,
++ * so per CPU. The exception builds a register frame below it, puts all that back and calls
++ * linux64_el0_exception(frame) (sleh.c), which hands it to sleh_synchronous and returns to user space again.
++ */
++#define LINUX64_EL0_BLOCK 64 // thread, SP_EL0, VBAR_EL1, x18, SCTLR_EL1
++#define LINUX64_EL0_FRAME (36 * 8 + 528) // struct linux64_el0_frame (sleh.c)
++
++ .text
++ .align 2
++ .globl EXT(linux64_el0_run)
++LEXT(linux64_el0_run)
++ ARM64_PROLOG
++ mrs x11, TPIDR_EL0 // this CPU's thread
++ LOAD_KERN_STACK_TOP dst=x12, src=x11, tmp=x13
++ adrp x13, _linux64_el0@PAGE
++ add x13, x13, _linux64_el0@PAGEOFF
++ ldr w13, [x13]
++ cbz w13, Llinux64_el0_run_el1
++ mov sp, x12
++ mov x29, xzr
++ b EXT(linux64_el0_utcb_entry)
++Llinux64_el0_run_el1:
++ sub x15, x12, #LINUX64_EL0_BLOCK
++ str x11, [x15, #0]
++ mrs x10, SP_EL0
++ str x10, [x15, #8]
++ mrs x10, VBAR_EL1
++ str x10, [x15, #16]
++ str x18, [x15, #24]
++ mrs x10, SCTLR_EL1
++ str x10, [x15, #32]
++ adrp x10, EXT(linux64_el0_vectors)@page
++ add x10, x10, EXT(linux64_el0_vectors)@pageoff
++ msr VBAR_EL1, x10
++ ldr x10, [x0, SS64_SP]
++ msr SP_EL0, x10
++ ldr x10, [x0, SS64_PC]
++ msr ELR_EL1, x10
++ ldr w10, [x0, SS64_CPSR]
++ orr w10, w10, #0x40 // FIQ stays masked at EL0 while hosted; a (Linux) IRQ preempts user code
++ msr SPSR_EL1, x10
++ // the user's NEON/FP state (arm_context_t ns, right after ss): upcalls may let Linux schedule, which reuses the registers
++ add x9, x0, NS64_Q0
++ ldp q0, q1, [x9, #0]
++ ldp q2, q3, [x9, #32]
++ ldp q4, q5, [x9, #64]
++ ldp q6, q7, [x9, #96]
++ ldp q8, q9, [x9, #128]
++ ldp q10, q11, [x9, #160]
++ ldp q12, q13, [x9, #192]
++ ldp q14, q15, [x9, #224]
++ ldp q16, q17, [x9, #256]
++ ldp q18, q19, [x9, #288]
++ ldp q20, q21, [x9, #320]
++ ldp q22, q23, [x9, #352]
++ ldp q24, q25, [x9, #384]
++ ldp q26, q27, [x9, #416]
++ ldp q28, q29, [x9, #448]
++ ldp q30, q31, [x9, #480]
++ ldr w10, [x9, #512]
++ msr FPSR, x10
++ ldr w10, [x9, #516]
++ msr FPCR, x10
++ mov sp, x15 // the next exception from EL0 starts below the block
++ ldr x10, [x11, TH_CTH_SELF] // the user's TSD (Darwin reads it from TPIDRRO_EL0)
++ msr TPIDRRO_EL0, x10
++ ldr x10, [x11, TH_LINUX64_USER_TPIDR]
++ ldr x9, [x11, ACT_CPUDATAP]
++ ldr x9, [x9, CPU_TPIDR_EL0]
++ and x9, x9, #0xfffff // MACHDEP_TPIDR_CPU_DATA_MASK
++ bic x10, x10, #0xfffff
++ orr x10, x10, x9
++ msr TPIDR_EL0, x10
++ /*
++ * x1: JOP off for this thread (arm64, not arm64e): EnIA (31) and EnDA (27) off at EL0. Only after the last
++ * kernel pointer authentication (LOAD_KERN_STACK_TOP authenticates; with EnDA off it would trap to brk).
++ */
++ cbz x1, 1f
++ mrs x10, SCTLR_EL1
++ mov x11, #((1 << 31) | (1 << 27))
++ bic x10, x10, x11
++ msr SCTLR_EL1, x10
++1:
++ isb
++ add x30, x0, SS64_X0
++ ldp x2, x3, [x30, #16]
++ ldp x4, x5, [x30, #32]
++ ldp x6, x7, [x30, #48]
++ ldp x8, x9, [x30, #64]
++ ldp x10, x11, [x30, #80]
++ ldp x12, x13, [x30, #96]
++ ldp x14, x15, [x30, #112]
++ ldp x16, x17, [x30, #128]
++ ldp x18, x19, [x30, #144]
++ ldp x20, x21, [x30, #160]
++ ldp x22, x23, [x30, #176]
++ ldp x24, x25, [x30, #192]
++ ldp x26, x27, [x30, #208]
++ ldp x28, x29, [x30, #224]
++ ldp x0, x1, [x30, #0]
++ ldr x30, [x30, #240]
++ eret
++
++ .text
++ .align 11
++ .globl EXT(linux64_el0_vectors)
++LEXT(linux64_el0_vectors)
++ .rept 8 // current EL (SP0, SPx): not expected while at EL0
++ b Llinux64_el0_bad
++ .align 7
++ .endr
++ b Llinux64_el0_entry // lower EL, AArch64: sync
++ .align 7
++ b Llinux64_el0_irq // IRQ: the host's interrupt arrived while user code ran
++ .align 7
++ .rept 2 // FIQ, SError
++ b Llinux64_el0_entry
++ .align 7
++ .endr
++ .rept 4 // lower EL, AArch32
++ b .
++ .align 7
++ .endr
++
++Llinux64_el0_bad: // note it for the monitor (linux64_dbg[14] = ESR) and stop here
++ adrp x9, _linux64_dbg@PAGE
++ add x9, x9, _linux64_dbg@PAGEOFF
++ mrs x10, ESR_EL1
++ str x10, [x9, #112]
++ b .
++
++Llinux64_el0_irq: // as an exception, with ESR = ~0 (LINUX64_EL0_ESR_IRQ: no ESR has bits 63:32 set)
+ sub sp, sp, #LINUX64_EL0_FRAME
+ stp x0, x1, [sp, #0]
+ mov x1, #1
@@ -1043,7 +5013,9 @@ index a191eb3..035b1a8 100644
+ str w10, [x9, #516]
+ add x9, sp, #LINUX64_EL0_FRAME // linux64_el0_run's block
+ ldr x10, [x9, #0]
-+ msr TPIDRRO_EL0, x10 // XNU's thread pointer again
++ mrs x11, TPIDR_EL0 // save user's TPIDR_EL0 before restoring kernel's
++ str x11, [x10, TH_LINUX64_USER_TPIDR]
++ msr TPIDR_EL0, x10 // XNU's thread pointer again
+ ldr x10, [x9, #8]
+ msr SP_EL0, x10
+ ldr x10, [x9, #16]
@@ -1057,1335 +5029,7340 @@ index a191eb3..035b1a8 100644
+ bl EXT(linux64_el0_exception)
+ b .
diff --git a/osfmk/arm64/exception_asm.h b/osfmk/arm64/exception_asm.h
-index b0772a7..b2e9f03 100644
+index b0772a7..7c1624f 100644
--- a/osfmk/arm64/exception_asm.h
+++ b/osfmk/arm64/exception_asm.h
@@ -299,7 +299,7 @@ Lspill_registers_skip_elr_far_\@:
* SP0 is expected to already be selected. Clobbers x1 and tmp.
*/
- .macro SWITCH_TO_INT_STACK tmp
-- mrs x1, TPIDR_EL1
-+ mrs x1, TPIDRRO_EL0
- LOAD_INT_STACK_THREAD dst=x1, src=x1, tmp=\tmp
- mov sp, x1 // Set the stack pointer to the interrupt stack
- .endmacro
-diff --git a/osfmk/arm64/locore.s b/osfmk/arm64/locore.s
-index 13d2819..1837c6a 100644
---- a/osfmk/arm64/locore.s
-+++ b/osfmk/arm64/locore.s
-@@ -144,7 +144,7 @@
-
- #endif /* DEVELOPMENT || DEBUG */
- #if CONFIG_XNUPOST
-- mrs x0, TPIDR_EL1
-+ mrs x0, TPIDRRO_EL0
- /*
- * If hitting this with a null TPIDR, it's likely that this was an unexpected
- * exception in early boot rather than an expected one as a part of a test.
-@@ -257,7 +257,7 @@ Lbegin_panic_lockdown_continue_\@:
- * Find the kernelcache table for the exception vectors by accessing
- * the per-CPU data.
- */
-- mrs x18, TPIDR_EL1
-+ mrs x18, TPIDRRO_EL0
- ldr x18, [x18, ACT_CPUDATAP]
- ldr x18, [x18, CPU_EXC_VECTORS]
+ .macro SWITCH_TO_INT_STACK tmp
+- mrs x1, TPIDR_EL1
++ mrs x1, TPIDR_EL0
+ LOAD_INT_STACK_THREAD dst=x1, src=x1, tmp=\tmp
+ mov sp, x1 // Set the stack pointer to the interrupt stack
+ .endmacro
+diff --git a/osfmk/arm64/genassym.c b/osfmk/arm64/genassym.c
+index e80e5f7..2147b47 100644
+--- a/osfmk/arm64/genassym.c
++++ b/osfmk/arm64/genassym.c
+@@ -169,6 +169,7 @@ main(int argc,
+
+ #endif /* HAS_ARM_FEAT_SME */
+ DECLARE("TH_CTH_SELF", offsetof(struct thread, machine.cthread_self));
++ DECLARE("TH_LINUX64_USER_TPIDR", offsetof(struct thread, machine.linux64_user_tpidr));
+ DECLARE("ACT_PREEMPT_CNT", offsetof(struct thread, machine.preemption_count));
+ #if SCHED_HYGIENE_DEBUG
+ DECLARE("SCHED_HYGIENE_MARKER", SCHED_HYGIENE_MARKER);
+diff --git a/osfmk/arm64/locore.s b/osfmk/arm64/locore.s
+index 13d2819..71b1e19 100644
+--- a/osfmk/arm64/locore.s
++++ b/osfmk/arm64/locore.s
+@@ -144,7 +144,7 @@
+
+ #endif /* DEVELOPMENT || DEBUG */
+ #if CONFIG_XNUPOST
+- mrs x0, TPIDR_EL1
++ mrs x0, TPIDR_EL0
+ /*
+ * If hitting this with a null TPIDR, it's likely that this was an unexpected
+ * exception in early boot rather than an expected one as a part of a test.
+@@ -257,7 +257,7 @@ Lbegin_panic_lockdown_continue_\@:
+ * Find the kernelcache table for the exception vectors by accessing
+ * the per-CPU data.
+ */
+- mrs x18, TPIDR_EL1
++ mrs x18, TPIDR_EL0
+ ldr x18, [x18, ACT_CPUDATAP]
+ ldr x18, [x18, CPU_EXC_VECTORS]
+
+@@ -354,7 +354,7 @@ Lbegin_panic_lockdown_continue_\@:
+ str x1, [x0, #24] // spsr
+ mrs x1, SP_EL0
+ str x1, [x0, #32] // sp
+- mrs x1, TPIDR_EL1
++ mrs x1, TPIDR_EL0
+ str x1, [x0, #40] // tpidr (thread pointer)
+
+ /* Get timestamp */
+@@ -396,7 +396,7 @@ Lbegin_panic_lockdown_continue_\@:
+ cmp x1, x2 // If we have a data abort, we need to
+ b.ne Lvalid_stack_\@ // ...validate the stack pointer
+ mrs x0, SP_EL0 // Get SP_EL0
+- mrs x1, TPIDR_EL1 // Get thread pointer
++ mrs x1, TPIDR_EL0 // Get thread pointer
+ /*
+ * Check for either a NULL TPIDR or a NULL kernel stack, both of which
+ * are expected in early boot, but will cause recursive faults if not
+@@ -490,7 +490,7 @@ Lvalid_stack_\@:
+ * Clobbers NZCV.
+ */
+ .macro CHECK_EXCEPTION_STACK invalid_stack_label
+- mrs x18, TPIDR_EL1 // Get thread pointer
++ mrs x18, TPIDR_EL0 // Get thread pointer
+ /*
+ * The thread pointer might be invalid during early boot.
+ * Return zero in x18 to indicate that we failed to execute the check.
+@@ -631,7 +631,7 @@ Lel0_serror_vector_64:
+ // SWITCH_TO_INT_STACK requires a clobberable tmp register, but at this
+ // point in the exception vector we can't spare the extra GPR. Instead note
+ // that EL1_SP0_VECTOR ends with x0 == sp and use this to unclobber x0.
+- mrs x1, TPIDR_EL1
++ mrs x1, TPIDR_EL0
+ LOAD_INT_STACK_THREAD dst=x1, src=x1, tmp=x0
+ mov x0, sp
+ mov sp, x1
+@@ -701,7 +701,7 @@ Lkernel_stack_valid:
+ * Slow path: check/map redzone.
+ * Skip redzone mapping if preemption is disabled (e.g. possibly in SPTM context)
+ */
+- mrs x0, TPIDR_EL1
++ mrs x0, TPIDR_EL0
+ ldr w0, [x0, ACT_PREEMPT_CNT]
+ cbnz w0, Lel1_sp0_redzone_done_\@ // Preemption disabled, skip redzone
+
+@@ -822,7 +822,7 @@ Lel1_sp1_synchronous_vector_continue:
+ *
+ * Ensure that we actually performed the check on a legitmate value now.
+ */
+- mrs x0, TPIDR_EL1
++ mrs x0, TPIDR_EL0
+ LOAD_EXCEP_STACK_THREAD dst=x0, src=x0, tmp=x1
+ cmp x0, x18
+ /* If we aren't equal, something is very wrong and we should lockdown. */
+@@ -875,7 +875,7 @@ LEXT(el1_sp1_synchronous_vector_long_spill_failed)
+ /* Macro returns x0=1 if it performed a simulated lockdown */
+ cbz x0, 0f
+ /* This was a test; return to fault handler so they can fixup the system. */
+- mrs x0, TPIDR_EL1
++ mrs x0, TPIDR_EL0
+ ldr x16, [x0, TH_EXPECTED_FAULT_HANDLER]
+ #if __has_feature(ptrauth_calls)
+ movk x17, #TH_EXPECTED_FAULT_HANDLER_DIVERSIFIER
+@@ -944,7 +944,7 @@ el1_sp1_serror_vector_long:
+ #if __ARM_KERNEL_PROTECT__
+ mov x18, #0 // Zero x18 to avoid leaking data to user SS
+ #endif
+- mrs x0, TPIDR_EL1 // Load the thread register
++ mrs x0, TPIDR_EL0 // Load the thread register
+ LOAD_USER_PCB dst=x0, src=x0, tmp=x1 // Load the user context pointer
+ mrs x1, SP_EL0 // Load the user stack pointer
+ str x1, [x0, SS64_SP] // Store the user stack pointer in the user PCB
+@@ -953,7 +953,7 @@ el1_sp1_serror_vector_long:
+ msr SPSel, #0 // Switch to SP0
+ stp x0, x1, [sp, SS64_X0] // Save x0, x1 to the user PCB
+ stp x2, x3, [sp, SS64_X2] // Save x2, x3 to the user PCB
+- mrs x1, TPIDR_EL1 // Load the thread register
++ mrs x1, TPIDR_EL0 // Load the thread register
+
+
+
+@@ -1321,7 +1321,7 @@ Lblocked_user_sync_exception:
+ * sp - Interrupt stack for the current CPU
+ */
+ .macro BEGIN_INTERRUPT_HANDLER
+- mrs x22, TPIDR_EL1
++ mrs x22, TPIDR_EL0
+ ldr x23, [x22, ACT_CPUDATAP] // Get current cpu
+ /* Update IRQ count; CPU_STAT_IRQ.* is required to be accurate for the WFE idle sequence */
+ ldr w1, [x23, CPU_STAT_IRQ]
+@@ -1529,7 +1529,7 @@ LEXT(fleh_check_map_redzone)
+ PUSH_FRAME
+
+ /* Check if we have a valid thread */
+- mrs x1, TPIDR_EL1
++ mrs x1, TPIDR_EL0
+ cbz x1, Lfleh_check_map_redzone_skip
+
+ /* Get kernel stack bottom */
+@@ -1671,7 +1671,7 @@ Lfleh_synchronous_sp1_skip_panic_lockdown:
+ * still on init_thread) and we try to panic(), we'll end up in an infinite
+ * nested exception, so just stop here instead to preserve the call stack.
+ */
+- mrs x9, TPIDR_EL1
++ mrs x9, TPIDR_EL0
+ cbz x9, 0f
+ ldr x9, [x9, TH_KSTACKPTR]
+ cbz x9, 0f
+@@ -1742,7 +1742,7 @@ LEXT(xnu_return_to_gl2)
+ * If thread->txm_thread_stack is set, we need to tell SPTM dispatch to
+ * resume the TXM thread in x0.
+ */
+- mrs x8, TPIDR_EL1
++ mrs x8, TPIDR_EL0
+ ldr x8, [x8, TH_TXM_THREAD_STACK]
+ cbz x8, 1f
+ mov x0, x8
+@@ -1756,7 +1756,7 @@ LEXT(xnu_return_to_gl2)
+ * we need to tell SPTM dispatch to resume the SK thread.
+ */
+ 1:
+- mrs x8, TPIDR_EL1
++ mrs x8, TPIDR_EL0
+ ldr x9, [x8, TH_EXCLAVES_INTSTATE]
+ and x9, x9, TH_EXCLAVES_EXECUTION
+ cbz x9, 1f
+@@ -1783,7 +1783,7 @@ LEXT(return_to_kernel)
+ UNWIND_PROLOGUE
+ RETURN_TO_KERNEL_UNWIND
+ tbnz w0, #DAIF_IRQF_SHIFT, exception_return // Skip AST check if IRQ disabled
+- mrs x3, TPIDR_EL1 // Load thread pointer
++ mrs x3, TPIDR_EL0 // Load thread pointer
+ ldr w1, [x3, ACT_PREEMPT_CNT] // Load preemption count
+ msr DAIFSet, #DAIFSC_ALL // Disable exceptions
+ cbnz x1, exception_return_unint_tpidr_x3 // If preemption disabled, skip AST check
+@@ -1802,6 +1802,12 @@ LEXT(return_to_kernel)
+ .globl EXT(thread_bootstrap_return)
+ LEXT(thread_bootstrap_return)
+ ARM64_PROLOG
++ // LINUX64 (xnulinux): hosted, a new user thread's first return goes through C (user space is not hosted yet)
++ adrp x9, _linux64_hook@PAGE
++ ldr x9, [x9, _linux64_hook@PAGEOFF]
++ cbz x9, 1f
++ b EXT(linux64_thread_bootstrap_return)
++1:
+ #if CONFIG_DTRACE
+ bl EXT(dtrace_thread_bootstrap)
+ #endif
+@@ -1816,7 +1822,13 @@ LEXT(thread_bootstrap_return)
+ .globl EXT(arm64_thread_exception_return)
+ LEXT(arm64_thread_exception_return)
+ ARM64_PROLOG
+- mrs x0, TPIDR_EL1
++ // LINUX64 (xnulinux): hosted, a return to user space goes through C (user space is not hosted yet)
++ adrp x9, _linux64_hook@PAGE
++ ldr x9, [x9, _linux64_hook@PAGEOFF]
++ cbz x9, 1f
++ b EXT(linux64_thread_bootstrap_return)
++1:
++ mrs x0, TPIDR_EL0
+ LOAD_USER_PCB dst=x21, src=x0, tmp=x28
+ mov x28, xzr
+
+@@ -1835,7 +1847,7 @@ check_user_asts:
+ bl EXT(__asan_handle_no_return)
+ POP_FRAME_WITHOUT_LR
+ #endif /* KASAN_TBI */
+- mrs x3, TPIDR_EL1 // Load thread pointer
++ mrs x3, TPIDR_EL0 // Load thread pointer
+
+ movn w2, #0
+ str w2, [x3, TH_IOTIER_OVERRIDE] // Reset IO tier override to -1 before returning to user
+@@ -1927,7 +1939,7 @@ no_asts:
+ PUSH_FRAME
+ bl EXT(arm_debug_set) // Establish thread debug state in live regs
+ POP_FRAME_WITHOUT_LR
+- mrs x3, TPIDR_EL1 // Reload thread pointer
++ mrs x3, TPIDR_EL0 // Reload thread pointer
+ ldr x4, [x3, ACT_CPUDATAP] // Reload CPU data pointer
+ L_skip_user_set_debug_state:
+
+@@ -1937,7 +1949,7 @@ L_skip_user_set_debug_state:
+ exception_return:
+ msr DAIFSet, #DAIFSC_ALL // Disable exceptions
+ exception_return_unint:
+- mrs x3, TPIDR_EL1 // Load thread pointer
++ mrs x3, TPIDR_EL0 // Load thread pointer
+ exception_return_unint_tpidr_x3:
+ mov sp, x21 // Reload the pcb pointer
+
+@@ -2006,7 +2018,7 @@ Lexception_return_restore_registers:
+ // SPSR_EL1.M != EL0: no SME state to restore
+ bne Lno_sme_saved_state
+
+- mrs x3, TPIDR_EL1
++ mrs x3, TPIDR_EL0
+ add x3, x3, ACT_UMATRIX_HDR
+ ldr x2, [x3]
+ cbz x2, Lno_sme_saved_state
+@@ -2071,7 +2083,7 @@ Lno_gcr_mask_el0_reset:
+ #endif /* HAS_MTE */
+ // If sync_on_cswitch and ERET is not a CSE, issue an ISB now. Unconditionally clear the
+ // sync_on_cswitch flag.
+- mrs x1, TPIDR_EL1
++ mrs x1, TPIDR_EL0
+ ldr x1, [x1, ACT_CPUDATAP]
+
+ // Redefined for backporting.
+@@ -2095,7 +2107,7 @@ Lno_gcr_mask_el0_reset:
+ mrs x2, SPSR_EL1
+ tst x2, #(PSR64_MODE_EL_MASK)
+ b.ne 1f
+- mrs x2, TPIDR_EL1
++ mrs x2, TPIDR_EL0
+ ldr w2, [x2, TH_ARM_MACHINE_FLAGS]
+ tbz w2, #ARM_MACHINE_THREAD_DISABLE_USER_JOP_SHIFT, 1f
+ mrs x2, SCTLR_EL1
+@@ -2184,7 +2196,7 @@ user_take_ast:
+ .text
+ .align 2
+ preempt_underflow:
+- mrs x0, TPIDR_EL1
++ mrs x0, TPIDR_EL0
+ str x0, [sp, #-16]! // We'll print thread pointer
+ adr x0, L_underflow_str // Format string
+ CALL_EXTERN panic // Game over
+@@ -2197,7 +2209,7 @@ L_underflow_str:
+ .text
+ .align 2
+ preempt_count_notzero:
+- mrs x0, TPIDR_EL1
++ mrs x0, TPIDR_EL0
+ str x0, [sp, #-16]! // We'll print thread pointer
+ ldr w0, [x0, ACT_PREEMPT_CNT]
+ str w0, [sp, #8]
+@@ -2457,7 +2469,7 @@ ppl_exit:
+ add x15, x15, x10, lsl #32
+
+ /* Load the preemption count. */
+- mrs x10, TPIDR_EL1
++ mrs x10, TPIDR_EL0
+ ldr w12, [x10, ACT_PREEMPT_CNT]
+
+ /* Detect underflow */
+@@ -2493,7 +2505,7 @@ Lno_preempt_underflow:
+ mov w12, #0
+
+ /* Restore the thread pointer into x10. */
+- mrs x10, TPIDR_EL1
++ mrs x10, TPIDR_EL0
+
+ Lskip_collect_measurement:
+ #endif /* SCHED_HYGIENE_DEBUG */
+@@ -2743,7 +2755,7 @@ LEXT(_sptm_pre_entry_hook)
+ stp x6, x7, [sp, #0x30]
+
+ /* Increase the preemption count. */
+- mrs x9, TPIDR_EL1
++ mrs x9, TPIDR_EL0
+ cbz x9, Lskip_preemption_check_sptmhook
+ ldr w10, [x9, ACT_PREEMPT_CNT]
+ add w10, w10, #1
+@@ -2803,7 +2815,7 @@ LEXT(_sptm_post_exit_hook)
+
+
+ /* Load the preemption count. */
+- mrs x0, TPIDR_EL1
++ mrs x0, TPIDR_EL0
+ cbz x0, Lsptm_skip_ast_taken_sptmhook
+ ldr w12, [x0, ACT_PREEMPT_CNT]
+
+@@ -2834,7 +2846,7 @@ Lno_preempt_underflow_sptmhook:
+ mov w12, #0
+
+ /* Restore x0 as the thread pointer */
+- mrs x0, TPIDR_EL1
++ mrs x0, TPIDR_EL0
+
+ Lskip_collect_measurement_sptmhook:
+ #endif /* SCHED_HYGIENE_DEBUG */
+@@ -2916,7 +2928,7 @@ LEXT(panic_lockdown_record_debug_data)
+ mov x1, sp
+ str x1, [x0, #PANIC_LOCKDOWN_INITIATOR_STATE_INITIATOR_SP]
+
+- mrs x1, TPIDR_EL1
++ mrs x1, TPIDR_EL0
+ str x1, [x0, #PANIC_LOCKDOWN_INITIATOR_STATE_INITIATOR_TPIDR]
+
+ mrs x1, MPIDR_EL1
+diff --git a/osfmk/arm64/machine_routines.c b/osfmk/arm64/machine_routines.c
+index f456377..805c3b4 100644
+--- a/osfmk/arm64/machine_routines.c
++++ b/osfmk/arm64/machine_routines.c
+@@ -27,6 +27,7 @@
+ */
+
+ #include <arm64/machine_machdep.h>
++#include <linux64/linux64.h>
+ #include <arm64/proc_reg.h>
+ #include <arm/machine_cpu.h>
+ #include <arm/cpu_internal.h>
+@@ -385,10 +386,11 @@ wfe_process_recommendation(void)
+ void
+ machine_idle(void)
+ {
++ linux64_count(LINUX64_CTR_MACHINE_IDLE); /* LINUX64: for the host's monitor */
+ /* Interrupts are expected to be masked on entry or re-entry via
+ * Idle_load_context()
+ */
+- assert((__builtin_arm_rsr("DAIF") & DAIF_STANDARD_DISABLE) == DAIF_STANDARD_DISABLE);
++ assert(linux64_el0 || (__builtin_arm_rsr("DAIF") & DAIF_STANDARD_DISABLE) == DAIF_STANDARD_DISABLE);
+ /* Check for, and act on, a WFE recommendation.
+ * Bypasses context spill/fill for a minor perf. increment.
+ * May unmask and restore IRQ+FIQ mask.
+@@ -400,6 +402,13 @@ machine_idle(void)
+ */
+ Idle_context();
+ }
++ {
++ /* LINUX64 (xnulinux): hosted, hardware IRQs stay masked; only the virtual flag changes. */
++ if (linux64_hook) {
++ LINUX64_VINT = 1;
++ return;
++ }
++ }
+ __builtin_arm_wsr("DAIFClr", DAIFSC_STANDARD_DISABLE);
+ }
+
+@@ -414,6 +423,9 @@ get_aux_control(void)
+ {
+ uint64_t value;
+
++ if (linux64_el0) {
++ return 0;
++ }
+ MRS(value, "ACTLR_EL1");
+ return value;
+ }
+@@ -423,6 +435,9 @@ get_mmu_control(void)
+ {
+ uint64_t value;
+
++ if (linux64_el0) {
++ return 0;
++ }
+ MRS(value, "SCTLR_EL1");
+ return value;
+ }
+@@ -432,6 +447,9 @@ get_tcr(void)
+ {
+ uint64_t value;
+
++ if (linux64_el0) {
++ return 0;
++ }
+ MRS(value, "TCR_EL1");
+ return value;
+ }
+@@ -441,6 +459,12 @@ ml_get_interrupts_enabled(void)
+ {
+ uint64_t value;
+
++ {
++ /* LINUX64: interrupts are virtual while hosted (see ml_set_interrupts_enabled_with_debug). */
++ if (linux64_hook) {
++ return LINUX64_VINT ? TRUE : FALSE;
++ }
++ }
+ MRS(value, "DAIF");
+ if ((value & DAIF_STANDARD_DISABLE) == DAIF_STANDARD_DISABLE) {
+ return FALSE;
+@@ -453,6 +477,9 @@ get_mmu_ttb(void)
+ {
+ pmap_paddr_t value;
+
++ if (linux64_el0) {
++ return 0;
++ }
+ MRS(value, "TTBR0_EL1");
+ return value;
+ }
+@@ -471,6 +498,9 @@ ml_feature_supported(uint64_t feature_bit)
+ {
+ uint64_t aidr_el1_value = 0;
+
++ if (linux64_el0) {
++ return false;
++ }
+ MRS(aidr_el1_value, "AIDR_EL1");
+
+ #ifdef APPLEAVALANCHE
+@@ -934,6 +964,13 @@ halt_all_cpus(boolean_t reboot)
+ printf("CPU halted\n");
+ PEHaltRestart(kPEHaltCPU);
+ }
++ if (linux64_hook) {
++ /*
++ * LINUX64 (xnulinux): hosted, spinning here keeps this Linux CPU with its interrupts masked for good (Linux
++ * soft-locks). The host ends the run instead and says whether the system asked for a restart.
++ */
++ linux64_call2(LINUX64_CALL_HALT, reboot ? 1 : 0, 0);
++ }
+ while (1) {
+ ;
+ }
+@@ -1365,9 +1402,9 @@ ml_parse_cpu_topology(void)
+ ((boot_cpu->cluster_id << MACHDEP_TPIDR_CLUSTERID_SHIFT) & MACHDEP_TPIDR_CLUSTERID_MASK);
+ assert(((tpidr_el0 & MACHDEP_TPIDR_CPUNUM_MASK) >> MACHDEP_TPIDR_CPUNUM_SHIFT) == boot_cpu->cpu_id);
+ assert(((tpidr_el0 & MACHDEP_TPIDR_CLUSTERID_MASK) >> MACHDEP_TPIDR_CLUSTERID_SHIFT) == boot_cpu->cluster_id);
+- __builtin_arm_wsr64("TPIDR_EL0", tpidr_el0);
+-
+- __builtin_arm_wsr64("TPIDRRO_EL0", 0);
++ if (!linux64_hook) { /* LINUX64: TPIDR_EL0 holds the kernel thread pointer; never overwrite it */
++ __builtin_arm_wsr64("TPIDRRO_EL0", 0);
++ }
+ }
+
+ const ml_topology_info_t *
+@@ -1460,8 +1497,13 @@ ml_get_cpu_number_local(void)
+ uint64_t mpidr_el1_value = 0;
+ unsigned cpu_id;
+
+- /* We identify the CPU based on the constant bits of MPIDR_EL1. */
+- MRS(mpidr_el1_value, "MPIDR_EL1");
++ /* We identify the CPU based on the constant bits of MPIDR_EL1 (or TPIDRRO_EL0 on EL0 host). */
++ if (linux64_el0) {
++ unsigned slot = linux64_cpu_slot();
++ mpidr_el1_value = (slot & 0xf) | (((uint64_t)((slot >> 4) & 0xf)) << 8);
++ } else {
++ MRS(mpidr_el1_value, "MPIDR_EL1");
++ }
+ cpu_id = ml_get_cpu_number((uint32_t)mpidr_el1_value);
+
+ assert(cpu_id <= (unsigned int)ml_get_max_cpu_number());
+@@ -1475,8 +1517,13 @@ ml_get_cluster_number_local()
+ uint64_t mpidr_el1_value = 0;
+ unsigned cluster_id;
+
+- /* We identify the cluster based on the constant bits of MPIDR_EL1. */
+- MRS(mpidr_el1_value, "MPIDR_EL1");
++ /* We identify the cluster based on the constant bits of MPIDR_EL1 (or TPIDRRO_EL0 on EL0 host). */
++ if (linux64_el0) {
++ unsigned slot = linux64_cpu_slot();
++ mpidr_el1_value = (slot & 0xf) | (((uint64_t)((slot >> 4) & 0xf)) << 8);
++ } else {
++ MRS(mpidr_el1_value, "MPIDR_EL1");
++ }
+ cluster_id = ml_get_cluster_number((uint32_t)mpidr_el1_value);
+
+ assert(cluster_id <= (unsigned int)ml_get_max_cluster_number());
+@@ -2529,6 +2576,12 @@ ml_set_decrementer(uint32_t dec_value)
+ }
+ }
+
++ {
++ /* LINUX64 (xnulinux): the generic timer is Linux's; cpu_idle hands the deadline to the host. */
++ if (linux64_hook) {
++ return;
++ }
++ }
+ if (cdp->cpu_set_decrementer_func) {
+ cdp->cpu_set_decrementer_func((uint32_t)counter_value);
+ } else {
+@@ -2657,6 +2710,9 @@ ml_get_timebase_entropy(void)
+ uint32_t
+ ml_get_decrementer(void)
+ {
++ if (linux64_el0) {
++ return 0;
++ }
+ cpu_data_t *cdp = getCpuDatap();
+ uint32_t dec;
+
+@@ -2683,6 +2739,9 @@ ml_get_decrementer(void)
+ boolean_t
+ ml_get_timer_pending(void)
+ {
++ if (linux64_el0) {
++ return FALSE;
++ }
+ uint64_t cntv_ctl = __builtin_arm_rsr64(KERNEL_CNTV_CTL_EL0);
+ return ((cntv_ctl & CNTV_CTL_EL0_ISTATUS) != 0) ? TRUE : FALSE;
+ }
+@@ -2729,6 +2788,9 @@ platform_syscall(arm_saved_state_t *state)
+ static void
+ _enable_timebase_event_stream(uint32_t bit_index)
+ {
++ if (linux64_el0) {
++ return;
++ }
+ if (bit_index >= 64) {
+ panic("%s: invalid bit index (%u)", __FUNCTION__, bit_index);
+ }
+@@ -2764,6 +2826,9 @@ _enable_timebase_event_stream(uint32_t bit_index)
+ static void
+ _enable_virtual_timer(void)
+ {
++ if (linux64_el0) {
++ return;
++ }
+ uint64_t cntvctl = CNTV_CTL_EL0_ENABLE; /* One wants to use 32 bits, but "mrs" prefers it this way */
+
+ __builtin_arm_wsr64(KERNEL_CNTV_CTL_EL0, cntvctl);
+@@ -3381,10 +3446,14 @@ ml_task_post_signature_processing_hook(__unused task_t task)
+ uint32_t flags = thread->machine.arm_machine_flags;
+
+ if (flags & (ARM_MACHINE_THREAD_PRESERVE_X18_SAVE | ARM_MACHINE_THREAD_PRESERVE_X18_INITIAL)) {
+- uint64_t tpidr = __builtin_arm_rsr64("TPIDR_EL0");
+- if (!(tpidr & MACHDEP_TPIDR_FLAG_PRESERVE_X18)) {
+- tpidr |= MACHDEP_TPIDR_FLAG_PRESERVE_X18;
+- __builtin_arm_wsr64("TPIDR_EL0", tpidr);
++ if (linux64_hook) {
++ thread->machine.linux64_user_tpidr |= MACHDEP_TPIDR_FLAG_PRESERVE_X18;
++ } else {
++ uint64_t tpidr = __builtin_arm_rsr64("TPIDR_EL0");
++ if (!(tpidr & MACHDEP_TPIDR_FLAG_PRESERVE_X18)) {
++ tpidr |= MACHDEP_TPIDR_FLAG_PRESERVE_X18;
++ __builtin_arm_wsr64("TPIDR_EL0", tpidr);
++ }
+ }
+ }
+
+diff --git a/osfmk/arm64/machine_routines_asm.s b/osfmk/arm64/machine_routines_asm.s
+index 96650a0..94ae456 100644
+--- a/osfmk/arm64/machine_routines_asm.s
++++ b/osfmk/arm64/machine_routines_asm.s
+@@ -95,7 +95,7 @@ Lcre_start_\@:
+
+
+ .macro LOAD_CPU_JOP_KEY dst, tmp
+- mrs \tmp, TPIDR_EL1
++ mrs \tmp, TPIDR_EL0
+ ldr \tmp, [\tmp, ACT_CPUDATAP]
+ ldr \dst, [\tmp, CPU_JOP_KEY]
+ .endmacro
+@@ -283,6 +283,11 @@ Lupdate_mdscr_panic_str:
+ .globl EXT(set_mmu_ttb_alternate)
+ LEXT(set_mmu_ttb_alternate)
+ ARM64_PROLOG
++ adrp x9, _linux64_el0@PAGE
++ ldr w9, [x9, _linux64_el0@PAGEOFF]
++ cbz w9, 9f
++ ret
++9:
+ dsb sy
+ #if defined(KERNEL_INTEGRITY_KTRR)
+ mov x1, lr
+@@ -303,6 +308,11 @@ LEXT(set_mmu_ttb_alternate)
+ .globl EXT(set_mmu_ttb)
+ LEXT(set_mmu_ttb)
+ ARM64_PROLOG
++ adrp x9, _linux64_el0@PAGE
++ ldr w9, [x9, _linux64_el0@PAGEOFF]
++ cbz w9, 9f
++ ret
++9:
+ #if __ARM_KERNEL_PROTECT__
+ /* All EL1-mode ASIDs are odd. */
+ orr x0, x0, #(1 << TTBR_ASID_SHIFT)
+@@ -331,6 +341,11 @@ LEXT(ml_get_ppl_cpu_data)
+ .globl EXT(set_aux_control)
+ LEXT(set_aux_control)
+ ARM64_PROLOG
++ adrp x9, _linux64_el0@PAGE
++ ldr w9, [x9, _linux64_el0@PAGEOFF]
++ cbz w9, 9f
++ ret
++9:
+ msr ACTLR_EL1, x0
+ // Synchronize system
+ isb sy
+@@ -342,6 +357,11 @@ LEXT(set_aux_control)
+ .globl EXT(set_vbar_el1)
+ LEXT(set_vbar_el1)
+ ARM64_PROLOG
++ adrp x9, _linux64_el0@PAGE
++ ldr w9, [x9, _linux64_el0@PAGEOFF]
++ cbz w9, 9f
++ ret
++9:
+ #if defined(KERNEL_INTEGRITY_KTRR)
+ b EXT(pinst_set_vbar)
+ #else
+@@ -359,6 +379,11 @@ LEXT(set_vbar_el1)
+ .globl EXT(set_tcr)
+ LEXT(set_tcr)
+ ARM64_PROLOG
++ adrp x9, _linux64_el0@PAGE
++ ldr w9, [x9, _linux64_el0@PAGEOFF]
++ cbz w9, 9f
++ ret
++9:
+ #if defined(APPLE_ARM64_ARCH_FAMILY)
+ #if DEBUG || DEVELOPMENT
+ // Assert that T0Z is always equal to T1Z
+@@ -409,6 +434,11 @@ L_set_locked_reg_panic_str:
+ .globl EXT(mmu_kvtop)
+ LEXT(mmu_kvtop)
+ ARM64_PROLOG
++ adrp x9, _linux64_el0@PAGE
++ ldr w9, [x9, _linux64_el0@PAGEOFF]
++ cbz w9, 9f
++ b EXT(linux64_el0_kvtop)
++9:
+ mrs x2, DAIF // Load current DAIF
+ msr DAIFSet, #(DAIFSC_STANDARD_DISABLE) // Disable all asynchronous exceptions
+ at s1e1r, x0 // Translation Stage 1 EL1
+@@ -431,6 +461,9 @@ L_mmu_kvtop_invalid:
+ .globl EXT(mmu_uvtop)
+ LEXT(mmu_uvtop)
+ ARM64_PROLOG
++ adrp x9, _linux64_el0@PAGE
++ ldr w9, [x9, _linux64_el0@PAGEOFF]
++ cbnz w9, L_mmu_uvtop_invalid
+ lsr x8, x0, #56 // Extract top byte
+ cbnz x8, L_mmu_uvtop_invalid // Tagged pointers are invalid
+ mrs x2, DAIF // Load current DAIF
+@@ -455,6 +488,11 @@ L_mmu_uvtop_invalid:
+ .globl EXT(mmu_kvtop_wpreflight)
+ LEXT(mmu_kvtop_wpreflight)
+ ARM64_PROLOG
++ adrp x9, _linux64_el0@PAGE
++ ldr w9, [x9, _linux64_el0@PAGEOFF]
++ cbz w9, 9f
++ b EXT(linux64_el0_kvtop)
++9:
+ mrs x2, DAIF // Load current DAIF
+ msr DAIFSet, #(DAIFSC_STANDARD_DISABLE) // Disable all asynchronous exceptions
+ at s1e1w, x0 // Translation Stage 1 EL1
+@@ -1748,6 +1786,11 @@ LEXT(arm64_force_wfi_clock_gate)
+ LEXT(arm64_replace_bootstack)
+ ARM64_STACK_PROLOG
+ PUSH_FRAME
++ // LINUX64 (xnulinux): hosted, SP_EL1 is Linux's kernel stack and SP_EL0 is Linux's `current`;
++ // XNU must not touch either. Its exception stacks are unused while hosted.
++ adrp x9, _linux64_hook@PAGE
++ ldr x9, [x9, _linux64_hook@PAGEOFF]
++ cbnz x9, Lreplace_bootstack_hosted
+ // Set the exception stack pointer
+ ldr x0, [x0, CPU_EXCEPSTACK_TOP]
+ mrs x4, DAIF // Load current DAIF; use x4 as pinst may trash x1-x3
+@@ -1763,6 +1806,7 @@ LEXT(arm64_replace_bootstack)
+ mov sp, x0
+ msr SPSel, #0
+ msr DAIF, x4 // Restore interrupt state
++Lreplace_bootstack_hosted:
+ POP_FRAME
+ ARM64_STACK_EPILOG EXT(arm64_replace_bootstack)
+
+@@ -1849,7 +1893,11 @@ LEXT(monitor_call)
+ *
+ * Branches to Lintr_enabled_panic if interrupts are in an unexpected state.
+ */
+-.macro CHECK_THREAD_STATE_INTERRUPTS tmp
++.macro CHECK_THREAD_STATE_INTERRUPTS tmp, wtmp
++ adrp \tmp, _linux64_el0@PAGE
++ add \tmp, \tmp, _linux64_el0@PAGEOFF
++ ldr \wtmp, [\tmp]
++ cbnz \wtmp, Lcheck_ts_el0_skip_\@
+ mrs \tmp, DAIF
+ tbz \tmp, #DAIF_IRQF_SHIFT, Lintr_enabled_panic
+ #if !CONFIG_SPTM
+@@ -1860,6 +1908,7 @@ LEXT(monitor_call)
+ mrs \tmp, SPSel
+ tbz \tmp, #0, Lintr_enabled_panic
+ #endif /* !CONFIG_SPTM */
++Lcheck_ts_el0_skip_\@:
+ .endm
+
+ /**
+@@ -1878,7 +1927,7 @@ LEXT(ml_sign_thread_state)
+ COMPUTE_THREAD_STATE_HASH
+ str x1, [x0, SS64_JOPHASH]
+ #if DEBUG || DEVELOPMENT
+- CHECK_THREAD_STATE_INTERRUPTS tmp=x1
++ CHECK_THREAD_STATE_INTERRUPTS tmp=x1, wtmp=w1
+ #endif
+ ret
+
+@@ -1895,7 +1944,7 @@ LEXT(ml_sign_thread_state)
+ .globl EXT(ml_check_signed_state)
+ LEXT(ml_check_signed_state)
+ ARM64_PROLOG
+- CHECK_THREAD_STATE_INTERRUPTS tmp=x16
++ CHECK_THREAD_STATE_INTERRUPTS tmp=x16, wtmp=w16
+ ldr x16, [x0, SS64_JOPHASH]
+ COMPUTE_THREAD_STATE_HASH
+ cmp x1, x16
+@@ -1970,6 +2019,12 @@ Linvalid_cpsr_str:
+ .globl EXT(ml_pac_safe_interrupts_disable)
+ LEXT(ml_pac_safe_interrupts_disable)
+ ARM64_PROLOG
++ adrp x16, _linux64_el0@PAGE
++ ldr w16, [x16, _linux64_el0@PAGEOFF]
++ cbz w16, 9f
++ mov x0, #0
++ ret
++9:
+ mrs x16, DAIF
+ and x17, x16, DAIF_STANDARD_DISABLE
+ cmp x17, DAIF_STANDARD_DISABLE
+@@ -1991,6 +2046,11 @@ Lalready_disabled:
+ .globl EXT(ml_pac_safe_interrupts_restore)
+ LEXT(ml_pac_safe_interrupts_restore)
+ ARM64_PROLOG
++ adrp x16, _linux64_el0@PAGE
++ ldr w16, [x16, _linux64_el0@PAGEOFF]
++ cbz w16, 9f
++ ret
++9:
+ msr DAIF, x0
+ ret
+
+diff --git a/osfmk/arm64/pac_asm.h b/osfmk/arm64/pac_asm.h
+index d211433..72e22a4 100644
+--- a/osfmk/arm64/pac_asm.h
++++ b/osfmk/arm64/pac_asm.h
+@@ -216,7 +216,7 @@
+ * Expects interrupts to be disabled.
+ */
+ .macro PACGA_IRG_RESEED x, y, z
+- mrs \x, TPIDR_EL1
++ mrs \x, TPIDR_EL0
+ ldr \x, [\x, ACT_CPUDATAP]
+
+ // No need for atomic - These are per CPU and interrupts are disabled
+diff --git a/osfmk/arm64/pcb.c b/osfmk/arm64/pcb.c
+index 4538d50..e2897d3 100644
+--- a/osfmk/arm64/pcb.c
++++ b/osfmk/arm64/pcb.c
+@@ -53,6 +53,7 @@
+ #include <arm64/sop.h>
+ #endif
+ #include <arm/cpu_data_internal.h>
++#include <linux64/linux64.h>
+ #include <arm/machdep_call.h>
+ #include <arm/misc_protos.h>
+ #include <arm/cpuid.h>
+@@ -364,6 +365,29 @@ machine_thread_switch_cpu_data(thread_t old, thread_t new)
+ static inline void
+ machine_switch_cpu_data(thread_t old, thread_t new)
+ {
++ /* LINUX64: kernel thread pointer lives in TPIDR_EL0; never overwrite it with CPU id */
++ machine_thread_switch_cpu_data(old, new);
++#if !__ARM_KERNEL_PROTECT__
++ {
++ uint32_t const old_flags = old->machine.arm_machine_flags;
++ if (get_threadtask(old)->preserve_x18_entitled) {
++ uint64_t tpidr = old->machine.linux64_user_tpidr;
++ if ((bool)(old_flags & ARM_MACHINE_THREAD_PRESERVE_X18_SAVE) !=
++ (bool)(tpidr & MACHDEP_TPIDR_FLAG_PRESERVE_X18)) {
++ old->machine.arm_machine_flags ^= ARM_MACHINE_THREAD_PRESERVE_X18_SAVE;
++ }
++ }
++ if (new->machine.arm_machine_flags & ARM_MACHINE_THREAD_PRESERVE_X18_INITIAL) {
++ new->machine.linux64_user_tpidr |= MACHDEP_TPIDR_FLAG_PRESERVE_X18;
++ new->machine.arm_machine_flags &= ~ARM_MACHINE_THREAD_PRESERVE_X18_INITIAL;
++ } else if (new->machine.arm_machine_flags & ARM_MACHINE_THREAD_PRESERVE_X18_SAVE) {
++ new->machine.linux64_user_tpidr |= MACHDEP_TPIDR_FLAG_PRESERVE_X18;
++ } else {
++ new->machine.linux64_user_tpidr &= ~MACHDEP_TPIDR_FLAG_PRESERVE_X18;
++ }
++ }
++#endif
++ return;
+ #if !__ARM_KERNEL_PROTECT__
+ /*
+ * If the old thread was entitled for x18 preservation, save away
+@@ -438,6 +462,8 @@ machine_switch_pmap_and_extended_context(thread_t old, thread_t new)
+ {
+ pmap_t new_pmap;
+
++ linux64_el0_fpu_switch_out(old);
++
+
+
+
+@@ -503,7 +529,7 @@ machine_switch_context(thread_t old,
+ thread_t retval;
+
+ #if __ARM_PAN_AVAILABLE__
+- if (__improbable(__builtin_arm_rsr("pan") == 0)) {
++ if (__improbable(!linux64_el0 && __builtin_arm_rsr("pan") == 0)) {
+ panic("context switch with PAN disabled");
+ }
+ #endif
+@@ -587,6 +613,7 @@ machine_thread_create(thread_t thread, task_t task, bool first_thread)
+ thread->machine.arm_machine_flags = 0;
+ thread->machine.preemption_count = 0;
+ thread->machine.cthread_self = 0;
++ thread->machine.linux64_user_tpidr = 0;
+ thread->machine.kpcb = NULL;
+ thread->machine.exception_trace_code = 0;
+ #if defined(HAS_APPLE_PAC)
+@@ -756,6 +783,8 @@ machine_thread_destroy(thread_t thread)
+ {
+ arm_context_t *thread_user_ss;
+
++ linux64_el0_fpu_invalidate(thread);
++
+ if (thread->machine.contextData) {
+ /* Disassociate the user save state from the thread before we free it. */
+ thread_user_ss = thread->machine.contextData;
+@@ -1006,7 +1035,7 @@ machine_stack_attach(thread_t thread,
+
+ machine_stack_attach_kprintf("kstackptr: %lx\n", (vm_address_t)kstackptr);
+
+- current_el = (uint32_t) __builtin_arm_rsr64("CurrentEL");
++ current_el = linux64_el0 ? PSR64_MODE_EL1 : (uint32_t) __builtin_arm_rsr64("CurrentEL");
+ context = &((thread_kernel_state_t) thread->machine.kstackptr)->machine;
+ savestate = &context->ss;
+ savestate->fp = 0;
+@@ -1048,7 +1077,7 @@ machine_stack_handoff(thread_t old,
+ vm_offset_t stack;
+
+ #if __ARM_PAN_AVAILABLE__
+- if (__improbable(__builtin_arm_rsr("pan") == 0)) {
++ if (__improbable(!linux64_el0 && __builtin_arm_rsr("pan") == 0)) {
+ panic("stack handoff with PAN disabled");
+ }
+ #endif
+diff --git a/osfmk/arm64/sleh.c b/osfmk/arm64/sleh.c
+index d8f1b19..c257ecf 100644
+--- a/osfmk/arm64/sleh.c
++++ b/osfmk/arm64/sleh.c
+@@ -1,4 +1,5 @@
+ #include <kern/boot_progress.h>
++#include <linux64/linux64.h>
+ /*
+ * Copyright (c) 2012-2023 Apple Inc. All rights reserved.
+ *
+@@ -78,6 +79,7 @@
+ #if CONFIG_TELEMETRY
+ #include <kern/telemetry.h>
+ #include <kern/trap_telemetry.h>
++#include <kern/recount.h>
+ #endif
+
+ #include <prng/entropy.h>
+@@ -1225,7 +1227,14 @@ virt_compat_patch(arm_saved_state_t *state, uint32_t replacement)
+ *kva = replacement;
+ CleanPoU_DcacheRegion((vm_offset_t)kva, sizeof(uint32_t));
+ /* The instruction cache may alias by virtual address: invalidate all of it (inner shareable). */
+- InvalidatePoU_Icache();
++ {
++ extern unsigned int linux64_el0;
++ if (linux64_el0) {
++ InvalidatePoU_IcacheRegion((vm_offset_t)kva, sizeof(uint32_t));
++ } else {
++ InvalidatePoU_Icache();
++ }
++ }
+ return true;
+ }
+
+@@ -3646,3 +3655,463 @@ sleh_panic_lockdown_should_initiate_el1_sp0_sync(uint64_t esr, uint64_t elr,
+ }
+ __SECURITY_STACK_DISALLOWED_POP
+ #endif /* CONFIG_SPTM */
++
++/*
++ * LINUX64 (xnulinux): a data or instruction abort on an XNU kernel address, taken in Linux's vectors and forwarded by
++ * the host (xnu.ko through FKI). Does what handle_kernel_abort does for a kernel-map fault: the pmap fast path for
++ * permission/access-flag faults, then vm_fault. Returns KERN_SUCCESS when the access can be retried.
++ */
++kern_return_t linux64_kernel_fault(uint64_t far, uint64_t esr);
++kern_return_t
++linux64_kernel_fault(uint64_t far, uint64_t esr)
++{
++ uint32_t ec = (uint32_t)((esr >> 26) & 0x3f);
++ fault_status_t fault_code = (fault_status_t)(esr & 0x3f);
++ vm_prot_t fault_type = VM_PROT_READ;
++ kern_return_t result = KERN_FAILURE;
++
++ if (ec == 0x21) { /* instruction abort, current EL */
++ fault_type = VM_PROT_READ | VM_PROT_EXECUTE;
++ } else if (ec == 0x25) { /* data abort, current EL */
++ if (esr & (1u << 6)) { /* WnR */
++ fault_type = VM_PROT_READ | VM_PROT_WRITE;
++ }
++ } else {
++ return KERN_FAILURE;
++ }
++ if (!is_vm_fault(fault_code)) {
++ return KERN_FAILURE;
++ }
++ /* a kernel address faults on the kernel map; a user one (copyio) on the current thread's map */
++ vm_map_t map = kernel_map;
++ if (!VM_KERNEL_ADDRESS(far)) {
++ thread_t thread = current_thread();
++ if (thread == THREAD_NULL || thread->map == VM_MAP_NULL || thread->map == kernel_map) {
++ return KERN_FAILURE;
++ }
++ map = thread->map;
++ }
++ kern_return_t ffr = KERN_FAILURE;
++ if (!is_translation_fault(fault_code)) {
++ ffr = arm_fast_fault(map->pmap, far, fault_type, (fault_code == FSC_ACCESS_FLAG_FAULT_L3), FALSE);
++ }
++ kern_return_t kr = ffr == KERN_SUCCESS ? KERN_SUCCESS :
++ vm_fault(map, far, fault_type, FALSE, VM_KERN_MEMORY_NONE, THREAD_UNINT, NULL, 0);
++ if (ffr == KERN_SUCCESS) {
++ return KERN_SUCCESS;
++ }
++ return kr;
++}
++
++/*
++ * LINUX64 (xnulinux): a kernel fault vm_fault could not resolve, taken inside a copyin/copyout routine: the pc its
++ * copyio recovery entry returns through (the routine then returns an error; x0 = EFAULT), 0 when pc has none.
++ */
++uint64_t linux64_kernel_fault_recover(uint64_t pc, uint64_t far, uint64_t esr);
++uint64_t
++linux64_kernel_fault_recover(uint64_t pc, uint64_t far, uint64_t esr)
++{
++ struct copyio_recovery_entry *e = find_copyio_recovery_entry(pc);
++ thread_t thread = current_thread();
++
++ if (e == NULL) {
++ return 0;
++ }
++ if (thread != THREAD_NULL) {
++ thread->machine.recover_esr = esr;
++ thread->machine.recover_far = far;
++ }
++ return (uint64_t)copyio_recover_table + (uint64_t)e->cre_recovery;
++}
++
++/*
++ * LINUX64 (xnulinux): the first return of a new user thread (thread_bootstrap_return) while hosted. The pending ASTs
++ * run as on the way to user space (for the first BSD thread: bsdinit_task, which execs launchd), and the thread enters
++ * user space through linux64_el0_run (the host is told where user space starts the first time).
++ */
++void linux64_thread_bootstrap_return(void) __attribute__((noreturn));
++/* boot-arg linux64_trace=1 logs every EL0 exception, and system calls with their paths and results */
++static int linux64_trace_level = -1;
++static inline int
++linux64_tracing(void)
++{
++ if (__improbable(linux64_trace_level < 0)) {
++ int v = 0;
++ if (!PE_parse_boot_argn("linux64_trace", &v, sizeof(v))) {
++ v = 0;
++ }
++ linux64_trace_level = v;
++ }
++ return linux64_trace_level;
++}
++
++static thread_t linux64_svc_thread; /* linux64_trace: the thread whose system call is in flight, and its number */
++static long long linux64_svc_num;
++
++/* LINUX64: user-space exceptions by class for the host (linux64_abi.h, LINUX64_EL0_CLASSES) */
++uint64_t linux64_el0_stat[LINUX64_EL0_CPUS][2][LINUX64_EL0_CLASSES];
++
++struct linux64_el0_pcpu {
++ uint64_t fpu_tid;
++ uint8_t fpu_live;
++ uint8_t cls;
++ uint64_t t0;
++ uint64_t local_exc;
++} __attribute__((aligned(64)));
++static struct linux64_el0_pcpu linux64_el0_pcpu[LINUX64_CPU_SLOTS];
++
++_Static_assert(sizeof(arm_neon_saved_state64_t) >= 520, "arm_neon_saved_state64_t size");
++_Static_assert(__builtin_offsetof(arm_neon_saved_state64_t, v.q[0]) == 0, "ns_64 v.q[0] offset");
++_Static_assert(__builtin_offsetof(arm_neon_saved_state64_t, fpsr) == 512, "ns_64 fpsr offset");
++_Static_assert(__builtin_offsetof(arm_neon_saved_state64_t, fpcr) == 516, "ns_64 fpcr offset");
++
++void
++linux64_el0_fpu_switch_out(thread_t old)
++{
++ if (!linux64_el0 || old == NULL) {
++ return;
++ }
++ struct linux64_el0_pcpu *pcpu = &linux64_el0_pcpu[linux64_cpu_slot()];
++ if (pcpu->fpu_tid != old->thread_id) {
++ return;
++ }
++ struct linux64_fpu_sync_req req;
++ req.thread_id = old->thread_id;
++ req.result = 0;
++ if (pcpu->fpu_live && old->machine.uNeon != NULL) {
++ req.neon_ptr = (uint64_t)(uintptr_t)&old->machine.uNeon->ns_64;
++ req.flags = LINUX64_FPU_FLUSH | LINUX64_FPU_INVALIDATE;
++ } else {
++ req.neon_ptr = 0;
++ req.flags = LINUX64_FPU_INVALIDATE;
++ }
++ linux64_call(LINUX64_CALL_UTCB_FPU_SYNC, &req);
++ if (req.result != 0) {
++ panic("linux64_el0: FPU flush failed (%d)", req.result);
++ }
++ pcpu->fpu_live = 0;
++ pcpu->fpu_tid = 0;
++}
++
++void
++linux64_el0_fpu_flush(thread_t thread)
++{
++ if (!linux64_el0 || thread != current_thread()) {
++ return;
++ }
++ boolean_t istate = ml_set_interrupts_enabled(FALSE);
++ struct linux64_el0_pcpu *pcpu = &linux64_el0_pcpu[linux64_cpu_slot()];
++ if (pcpu->fpu_tid == thread->thread_id && pcpu->fpu_live && thread->machine.uNeon != NULL) {
++ struct linux64_fpu_sync_req req;
++ req.thread_id = thread->thread_id;
++ req.neon_ptr = (uint64_t)(uintptr_t)&thread->machine.uNeon->ns_64;
++ req.flags = LINUX64_FPU_FLUSH;
++ req.result = 0;
++ linux64_call(LINUX64_CALL_UTCB_FPU_SYNC, &req);
++ if (req.result != 0) {
++ panic("linux64_el0: FPU flush failed (%d)", req.result);
++ }
++ pcpu->fpu_live = 0;
++ }
++ (void)ml_set_interrupts_enabled(istate);
++}
++
++void
++linux64_el0_fpu_invalidate(thread_t thread)
++{
++ if (!linux64_el0 || thread != current_thread()) {
++ return;
++ }
++ boolean_t istate = ml_set_interrupts_enabled(FALSE);
++ struct linux64_el0_pcpu *pcpu = &linux64_el0_pcpu[linux64_cpu_slot()];
++ if (pcpu->fpu_tid == thread->thread_id) {
++ struct linux64_fpu_sync_req req;
++ req.thread_id = thread->thread_id;
++ req.neon_ptr = 0;
++ req.flags = LINUX64_FPU_INVALIDATE;
++ req.result = 0;
++ linux64_call(LINUX64_CALL_UTCB_FPU_SYNC, &req);
++ pcpu->fpu_live = 0;
++ pcpu->fpu_tid = 0;
++ }
++ (void)ml_set_interrupts_enabled(istate);
++}
++
++void
++linux64_thread_bootstrap_return(void)
++{
++ thread_t thread = current_thread();
++
++ static int reported;
++
++ (void)ml_set_interrupts_enabled(FALSE);
++ ast_taken_user();
++ if (linux64_svc_thread == thread && linux64_tracing()) { /* what the system call returned (C set: x0 is errno) */
++ linux64_svc_thread = NULL;
++ extern int proc_selfpid(void);
++ kprintf("linux64: [%d] svc %lld -> x0 0x%llx x1 0x%llx%s\n", proc_selfpid(), linux64_svc_num, get_saved_state_reg(thread->machine.upcb, 0),
++ get_saved_state_reg(thread->machine.upcb, 1), (get_saved_state_cpsr(thread->machine.upcb) & PSR64_C) ? " (error)" : "");
++ }
++ if (reported++ == 0) {
++ linux64_call2(LINUX64_CALL_USER_ENTER, get_saved_state_pc(thread->machine.upcb), 0);
++ }
++ /*
++ * An arm64 (not arm64e) process runs the arm64e system libraries with JOP off: Apple hardware disables the user
++ * IA/DA keys for it; hosted, user code runs with SCTLR_EL1.EnIA/EnDA cleared (linux64_el0_run puts them back on
++ * the next exception), or a blraaz on one of its unsigned function pointers fails (EXC_ARM_PAC_FAIL).
++ */
++#if PRECISE_USER_KERNEL_TIME
++ recount_enter_user(); /* user time vs system time, as locore's return to user space does */
++#endif
++ { /* the host's per-class accounting (linux64_abi.h): the exception this CPU took last is now done */
++ struct linux64_el0_pcpu *pcpu = &linux64_el0_pcpu[linux64_cpu_slot()];
++ if (pcpu->t0 != 0) {
++ unsigned int stat_slot = (unsigned int)cpu_number() & (LINUX64_EL0_CPUS - 1);
++ linux64_el0_stat[stat_slot][1][pcpu->cls] += __builtin_arm_rsr64("CNTVCT_EL0") - pcpu->t0;
++ pcpu->t0 = 0;
++ }
++ }
++ linux64_el0_run(thread->machine.upcb, (thread->machine.arm_machine_flags & ARM_MACHINE_THREAD_DISABLE_USER_JOP) != 0);
++}
++
++/* LINUX64: the registers linux64_el0_vectors saved for an exception taken at EL0 (cswitch.s) */
++struct linux64_el0_frame {
++ uint64_t x[31];
++ uint64_t sp, pc, cpsr, esr, far;
++ uint64_t neon[64]; /* q0..q31 */
++ uint32_t fpsr, fpcr;
++ uint64_t pad;
++};
++_Static_assert(__builtin_offsetof(struct linux64_el0_frame, neon) == 288, "linux64_el0_frame layout");
++_Static_assert(sizeof(struct linux64_el0_frame) == 36 * 8 + 528, "linux64_el0_frame size");
++
++static void __attribute__((noreturn))
++linux64_el0_dispatch(const uint64_t x[31], uint64_t sp, uint64_t pc, uint64_t cpsr_raw, uint64_t esr, uint64_t far)
++{
++ thread_t thread = current_thread();
++ arm_saved_state_t *ss = thread->machine.upcb;
++
++#if PRECISE_USER_KERNEL_TIME
++ recount_leave_user(); /* interrupts are still off here, as on locore's exception entry */
++#endif
++ {
++ struct linux64_el0_pcpu *pcpu = &linux64_el0_pcpu[linux64_cpu_slot()];
++ unsigned int stat_slot = (unsigned int)cpu_number() & (LINUX64_EL0_CPUS - 1);
++ unsigned int ec = (unsigned int)ESR_EC(esr);
++ unsigned int cls = esr == ~0ULL ? 3 : ec == ESR_EC_SVC_64 ? 0 : ec == ESR_EC_DABORT_EL0 ? 1 : ec == ESR_EC_IABORT_EL0 ? 2 : 4;
++ linux64_el0_stat[stat_slot][0][cls]++;
++ pcpu->cls = (uint8_t)cls;
++ pcpu->t0 = __builtin_arm_rsr64("CNTVCT_EL0");
++ pcpu->local_exc++;
++ if (cls != 0 || pcpu->local_exc >= 64) {
++ os_atomic_add(&linux64_dbg[LINUX64_CTR_EL0_EXC], pcpu->local_exc, relaxed);
++ pcpu->local_exc = 0;
++ linux64_dbg[LINUX64_CTR_EL0_ESR] = esr;
++ linux64_dbg[LINUX64_CTR_EL0_FAR] = far;
++ linux64_dbg[LINUX64_CTR_EL0_PC] = pc;
++ }
++ }
++ if (linux64_tracing()) kprintf("linux64: EL0 exception esr 0x%llx far 0x%llx pc 0x%llx x16 %lld ttbr0 0x%llx ttep 0x%llx\n", esr, far, pc, x[16],
++ linux64_el0 ? 0ULL : __builtin_arm_rsr64("TTBR0_EL1"), (uint64_t)thread->map->pmap->ttep);
++ /*
++ * The whole user state at once, signed once as locore's exception entry does (HAS_APPLE_PAC): the per-field setters
++ * each check the old signature and sign again, five times per exception. EL0 runs with IRQ/FIQ masked while hosted
++ * (no XNU interrupts at EL0 yet); XNU must see the user's own PSTATE, or its abort path takes the user fault for
++ * one from a non-interruptible context.
++ */
++ {
++ arm_saved_state64_t *s64 = saved_state64(ss);
++ uint32_t cpsr = (uint32_t)cpsr_raw & ~(uint32_t)0x3c0;
++ for (unsigned i = 0; i < 29; i++) {
++ if (i != 16 && i != 17) {
++ s64->x[i] = x[i];
++ }
++ }
++ s64->fp = x[29];
++ s64->sp = sp;
++#if HAS_APPLE_PAC
++ uint64_t intr = ml_pac_safe_interrupts_disable();
++ if (linux64_el0) {
++ asm volatile (
++ "mov x9, lr" "\n"
++ "mov x0, %[ss]" "\n"
++ "mov x1, %[pc]" "\n"
++ "mov w2, %w[cpsr]" "\n"
++ "mov x3, %[lr]" "\n"
++ "mov x4, %[x16]" "\n"
++ "mov x5, %[x17]" "\n"
++ "str x1, [x0, %[SS64_PC]]" "\n"
++ "str w2, [x0, %[SS64_CPSR]]" "\n"
++ "str x3, [x0, %[SS64_LR]]" "\n"
++ "stp x4, x5, [x0, %[SS64_X16]]" "\n"
++ "bl _ml_sign_thread_state" "\n"
++ "mov lr, x9" "\n"
++ :
++ : [ss] "r"(ss), [pc] "r"(pc), [cpsr] "r"(cpsr), [lr] "r"(x[30]), [x16] "r"(x[16]), [x17] "r"(x[17]),
++ [SS64_X16] "i"(ss64_offsetof(x[16])), [SS64_PC] "i"(ss64_offsetof(pc)),
++ [SS64_CPSR] "i"(ss64_offsetof(cpsr)), [SS64_LR] "i"(ss64_offsetof(lr))
++ : "x0", "x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9", "x16", "x17", "memory"
++ );
++ } else {
++ asm volatile (
++ "mov x9, lr" "\n"
++ "mov x0, %[ss]" "\n"
++ "mrs x10, SPSel" "\n"
++ "msr SPSel, #1" "\n"
++ "mov x1, %[pc]" "\n"
++ "mov w2, %w[cpsr]" "\n"
++ "mov x3, %[lr]" "\n"
++ "mov x4, %[x16]" "\n"
++ "mov x5, %[x17]" "\n"
++ "str x1, [x0, %[SS64_PC]]" "\n"
++ "str w2, [x0, %[SS64_CPSR]]" "\n"
++ "str x3, [x0, %[SS64_LR]]" "\n"
++ "stp x4, x5, [x0, %[SS64_X16]]" "\n"
++ "bl _ml_sign_thread_state" "\n"
++ "msr SPSel, x10" "\n"
++ "mov lr, x9" "\n"
++ :
++ : [ss] "r"(ss), [pc] "r"(pc), [cpsr] "r"(cpsr), [lr] "r"(x[30]), [x16] "r"(x[16]), [x17] "r"(x[17]),
++ [SS64_X16] "i"(ss64_offsetof(x[16])), [SS64_PC] "i"(ss64_offsetof(pc)),
++ [SS64_CPSR] "i"(ss64_offsetof(cpsr)), [SS64_LR] "i"(ss64_offsetof(lr))
++ : "x0", "x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9", "x10", "x16", "x17", "memory"
++ );
++ }
++ ml_pac_safe_interrupts_restore(intr);
++#else
++ s64->x[16] = x[16];
++ s64->x[17] = x[17];
++ s64->lr = x[30];
++ s64->pc = pc;
++ s64->cpsr = cpsr;
++#endif
++ }
++ if (esr == ~0ULL) {
++ /*
++ * A host IRQ arrived while user code ran (EL0 runs with IRQs unmasked). Let Linux take it and run what it
++ * must (its tick, RCU, other tasks), then deliver XNU's timer "interrupt" if it is due, as sleh_irq
++ * would: the quantum expiry it may raise preempts this thread on the way back to user space.
++ */
++ cpu_data_t *cdp = getCpuDatap();
++ (void)ml_set_interrupts_enabled(FALSE); /* XNU's (virtual) interrupt state: off, as in sleh_irq */
++ linux64_call2(LINUX64_CALL_PREEMPTED, 0, 0);
++ if (cdp->rtcPop != EndOfAllTime && cdp->rtcPop != 0 && mach_absolute_time() >= cdp->rtcPop) {
++ cdp->cpu_int_state = ss;
++ cdp->cpu_stat.irq_ex_cnt++;
++ cdp->cpu_decrementer = -1;
++ rtclock_intr(TRUE);
++ cdp->cpu_int_state = NULL;
++ }
++ 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(esr) == ESR_EC_SVC_64 && linux64_tracing()) {
++ long long num = (long long)x[16];
++ linux64_svc_thread = thread;
++ linux64_svc_num = num;
++ if (num == 202 && x[1] > 0 && x[1] <= 8) { /* sysctl: the MIB and this thread's kernel stack */
++ int mib[8] = {0};
++ if (copyin((user_addr_t)x[0], mib, x[1] * sizeof(int)) == 0) {
++ kprintf("linux64: svc 202 mib %d.%d.%d.%d (len %llu) kstack 0x%llx\n", mib[0], mib[1], mib[2], mib[3], x[1],
++ (uint64_t)thread->kernel_stack);
++ }
++ }
++ if (num == 59 || num == 244 || num == 5 || num == 398 || num == 463 || num == 33 || num == 338 || num == 340 || num == 466 || num == 469) {
++ char path[128];
++ size_t len = 0;
++ uint64_t ua = (num == 463 || num == 466 || num == 469 || num == 244) ? x[1] : x[0];
++ if (copyinstr((user_addr_t)ua, path, sizeof(path), &len) == 0) {
++ extern int proc_selfpid(void);
++ kprintf("linux64: [%d] svc %lld path \"%s\"\n", proc_selfpid(), num, path);
++ }
++ }
++ }
++ sleh_synchronous(thread->machine.contextData, esr, (vm_offset_t)far, false);
++ thread_exception_return();
++}
++
++void linux64_el0_exception(struct linux64_el0_frame *f) __attribute__((noreturn));
++void
++linux64_el0_exception(struct linux64_el0_frame *f)
++{
++ arm_neon_saved_state_t *ns = current_thread()->machine.uNeon;
++ memcpy(&ns->ns_64.v.q[0], f->neon, sizeof(f->neon));
++ ns->ns_64.fpsr = f->fpsr;
++ ns->ns_64.fpcr = f->fpcr;
++ linux64_el0_dispatch(f->x, f->sp, f->pc, f->cpsr, f->esr, f->far);
++}
++
++void linux64_el0_utcb_entry(arm_saved_state_t *ss, unsigned long disable_jop) __attribute__((noreturn));
++void
++linux64_el0_utcb_entry(arm_saved_state_t *ss, unsigned long disable_jop)
++{
++ thread_t thread = current_thread();
++ pmap_t pmap = thread->map->pmap;
++ arm_saved_state64_t *s64 = saved_state64(ss);
++ arm_neon_saved_state_t *ns = thread->machine.uNeon;
++ struct linux64_utcb_req req;
++ uint64_t cpu_tpidr;
++
++ req.as_handle = linux64_el0_ensure_as(pmap);
++ if (!req.as_handle) {
++ panic("linux64_el0_utcb_entry: failed to allocate user AS for pmap %p", pmap);
++ }
++ req.thread_id = thread->thread_id;
++ req.disable_jop = disable_jop;
++#if defined(HAS_APPLE_PAC)
++ req.rop_pid = thread->machine.rop_pid;
++ req.jop_pid = thread->machine.jop_pid;
++#else
++ req.rop_pid = 0;
++ req.jop_pid = 0;
++#endif
++ for (unsigned i = 0; i < 29; i++) {
++ req.x[i] = s64->x[i];
++ }
++ req.x[29] = s64->fp;
++ req.x[30] = s64->lr;
++ req.sp = s64->sp;
++ req.pc = s64->pc;
++ req.pstate = s64->cpsr;
++ cpu_tpidr = thread->machine.CpuDatap->cpu_tpidr_el0 & MACHDEP_TPIDR_CPU_DATA_MASK;
++ req.tpidr = (thread->machine.linux64_user_tpidr & ~MACHDEP_TPIDR_CPU_DATA_MASK) | cpu_tpidr;
++ req.tpidrro = (uint64_t)thread->machine.cthread_self;
++ req.neon_ptr = (uint64_t)(uintptr_t)&ns->ns_64;
++ req.fpu_dirty = 0;
++
++ unsigned long run_call = LINUX64_CALL_UTCB_RUN;
++ for (;;) {
++ req.result = 0;
++ linux64_call(run_call, &req);
++ if (req.result != 0) {
++ panic("linux64_el0_utcb_entry: UTCB_%s failed (%lld)",
++ run_call == LINUX64_CALL_UTCB_RESUME ? "RESUME" : "RUN",
++ (long long)req.result);
++ }
++ if (req.stop_kind == LINUX64_STOP_PAGEFAULT) {
++ if (linux64_el0_sync_user_pte(pmap, (vm_offset_t)req.fault_addr, req.esr)) {
++ run_call = LINUX64_CALL_UTCB_RESUME;
++ continue;
++ }
++ req.result = 0;
++ linux64_call(LINUX64_CALL_UTCB_SYNC_REGS, &req);
++ if (req.result != 0) {
++ panic("linux64_el0_utcb_entry: UTCB_SYNC_REGS failed (%lld)",
++ (long long)req.result);
++ }
++ }
++ break;
++ }
++
++ thread->machine.linux64_user_tpidr = req.tpidr;
++ {
++ struct linux64_el0_pcpu *pcpu = &linux64_el0_pcpu[linux64_cpu_slot()];
++ pcpu->fpu_tid = thread->thread_id;
++ pcpu->fpu_live = 1;
++ }
++ linux64_el0_dispatch(req.x, req.sp, req.pc, req.pstate, req.esr, req.fault_addr);
++}
+diff --git a/osfmk/arm64/static_if.c b/osfmk/arm64/static_if.c
+index 22be6f2..dc98132 100644
+--- a/osfmk/arm64/static_if.c
++++ b/osfmk/arm64/static_if.c
+@@ -75,9 +75,17 @@ ml_static_if_entry_patch(static_if_entry_t sie, int branch)
+ }
+ }
+
++extern unsigned int linux64_el0;
++extern void linux64_el0_icache_flush(unsigned long va, unsigned long size);
++
+ MARK_AS_FIXUP_TEXT void
+ ml_static_if_flush_icache(void)
+ {
++ if (linux64_el0) {
++ linux64_el0_icache_flush((unsigned long)__text_exec_start,
++ (unsigned long)((uintptr_t)__text_exec_end - (uintptr_t)__text_exec_start));
++ return;
++ }
+ asm volatile (""
+ "ic ialluis" "\n\t"
+ "dsb sy" "\n\t"
+diff --git a/osfmk/arm64/status.c b/osfmk/arm64/status.c
+index c615764..4ca62d2 100644
+--- a/osfmk/arm64/status.c
++++ b/osfmk/arm64/status.c
+@@ -33,6 +33,7 @@
+ #include <kern/kalloc.h>
+ #include <arm/vmparam.h>
+ #include <arm/cpu_data_internal.h>
++#include <linux64/linux64.h>
+ #include <arm/misc_protos.h>
+ #include <arm64/machine_machdep.h>
+ #include <arm64/proc_reg.h>
+@@ -1426,6 +1427,7 @@ machine_thread_get_state(thread_t thread,
+ }
+
+ state = (struct arm_vfp_state *) tstate;
++ linux64_el0_fpu_flush(thread);
+ thread_state = neon_state32(thread->machine.uNeon);
+ /* ARM64 TODO: set fpsr and fpcr from state->fpscr */
+
+@@ -1446,6 +1448,7 @@ machine_thread_get_state(thread_t thread,
+ }
+
+ state = (arm_neon_state_t *)tstate;
++ linux64_el0_fpu_flush(thread);
+ thread_state = neon_state32(thread->machine.uNeon);
+
+ assert(sizeof(*thread_state) == sizeof(*state));
+@@ -1468,6 +1471,7 @@ machine_thread_get_state(thread_t thread,
+ }
+
+ state = (arm_neon_state64_t *)tstate;
++ linux64_el0_fpu_flush(thread);
+ thread_state = neon_state64(thread->machine.uNeon);
+
+ #if HAS_ARM_FEAT_SME
+@@ -1620,6 +1624,7 @@ machine_thread_switch_addrmode(thread_t thread)
+ bzero(&thread->machine.uNeon->uns, sizeof(thread->machine.uNeon->uns));
+ thread->machine.uNeon->ns_32.fpcr = FPCR_DEFAULT_32;
+ }
++ linux64_el0_fpu_invalidate(thread);
+ }
+
+ extern long long arm_debug_get(void);
+@@ -1943,6 +1948,7 @@ machine_thread_set_state(thread_t thread,
+
+ thread->machine.uNeon->nsh.flavor = ARM_NEON_SAVED_STATE32;
+ thread->machine.uNeon->nsh.count = ARM_NEON_SAVED_STATE32_COUNT;
++ linux64_el0_fpu_invalidate(thread);
+ break;
+ }
+
+@@ -1966,6 +1972,7 @@ machine_thread_set_state(thread_t thread,
+
+ thread->machine.uNeon->nsh.flavor = ARM_NEON_SAVED_STATE32;
+ thread->machine.uNeon->nsh.count = ARM_NEON_SAVED_STATE32_COUNT;
++ linux64_el0_fpu_invalidate(thread);
+ break;
+ }
+
+@@ -2014,6 +2021,7 @@ machine_thread_set_state(thread_t thread,
+
+ thread->machine.uNeon->nsh.flavor = ARM_NEON_SAVED_STATE64;
+ thread->machine.uNeon->nsh.count = ARM_NEON_SAVED_STATE64_COUNT;
++ linux64_el0_fpu_invalidate(thread);
+ break;
+ }
+
+@@ -2088,6 +2096,7 @@ machine_thread_state_initialize(thread_t thread)
+ context->ns.ns_32.fpcr = FPCR_DEFAULT_32;
+ }
+ context->ss.ss_64.cpsr = PSR64_USER64_DEFAULT;
++ linux64_el0_fpu_invalidate(thread);
+ }
+
+ thread->machine.DebugData = NULL;
+@@ -2096,24 +2105,44 @@ machine_thread_state_initialize(thread_t thread)
+ /* Sign the initial user-space thread state */
+ if (thread->machine.upcb != NULL) {
+ uint64_t intr = ml_pac_safe_interrupts_disable();
+- asm volatile (
+- "mov x0, %[iss]" "\n"
+- "mov x1, #0" "\n"
+- "mov w2, %w[usr]" "\n"
+- "mov x3, #0" "\n"
+- "mov x4, #0" "\n"
+- "mov x5, #0" "\n"
+- "msr SPSel, #1" "\n"
+- VERIFY_USER_THREAD_STATE_INSTR "\n"
+- "mov x6, lr" "\n"
+- "bl _ml_sign_thread_state" "\n"
+- "msr SPSel, #0" "\n"
+- "mov lr, x6" "\n"
+- :
+- : [iss] "r"(thread->machine.upcb), [usr] "r"(thread->machine.upcb->ss_64.cpsr),
+- VERIFY_USER_THREAD_STATE_INPUTS
+- : "x0", "x1", "x2", "x3", "x4", "x5", "x6", "x17"
+- );
++ if (linux64_el0) {
++ asm volatile (
++ "mov x0, %[iss]" "\n"
++ "mov x1, #0" "\n"
++ "mov w2, %w[usr]" "\n"
++ "mov x3, #0" "\n"
++ "mov x4, #0" "\n"
++ "mov x5, #0" "\n"
++ VERIFY_USER_THREAD_STATE_INSTR "\n"
++ "mov x6, lr" "\n"
++ "bl _ml_sign_thread_state" "\n"
++ "mov lr, x6" "\n"
++ :
++ : [iss] "r"(thread->machine.upcb), [usr] "r"(thread->machine.upcb->ss_64.cpsr),
++ VERIFY_USER_THREAD_STATE_INPUTS
++ : "x0", "x1", "x2", "x3", "x4", "x5", "x6", "x17"
++ );
++ } else {
++ asm volatile (
++ "mov x0, %[iss]" "\n"
++ "mov x1, #0" "\n"
++ "mov w2, %w[usr]" "\n"
++ "mov x3, #0" "\n"
++ "mov x4, #0" "\n"
++ "mov x5, #0" "\n"
++ "mrs x10, SPSel" "\n"
++ "msr SPSel, #1" "\n"
++ VERIFY_USER_THREAD_STATE_INSTR "\n"
++ "mov x6, lr" "\n"
++ "bl _ml_sign_thread_state" "\n"
++ "msr SPSel, x10" "\n"
++ "mov lr, x6" "\n"
++ :
++ : [iss] "r"(thread->machine.upcb), [usr] "r"(thread->machine.upcb->ss_64.cpsr),
++ VERIFY_USER_THREAD_STATE_INPUTS
++ : "x0", "x1", "x2", "x3", "x4", "x5", "x6", "x10", "x17"
++ );
++ }
+ ml_pac_safe_interrupts_restore(intr);
+ }
+ #endif /* defined(HAS_APPLE_PAC) */
+@@ -2132,6 +2161,7 @@ machine_thread_dup(thread_t self,
+ struct arm_saved_state *target_saved_state;
+
+ target->machine.cthread_self = self->machine.cthread_self;
++ target->machine.linux64_user_tpidr = self->machine.linux64_user_tpidr;
+
+ self_saved_state = self->machine.upcb;
+ target_saved_state = target->machine.upcb;
+@@ -2142,6 +2172,7 @@ machine_thread_dup(thread_t self,
+ }
+ #endif /* defined(HAS_APPLE_PAC) */
+
++ linux64_el0_fpu_flush(self);
+ arm_neon_saved_state_t *self_neon_state = self->machine.uNeon;
+ arm_neon_saved_state_t *target_neon_state = target->machine.uNeon;
+ bcopy(self_neon_state, target_neon_state, sizeof(*target_neon_state));
+@@ -2179,6 +2210,7 @@ get_user_regs(thread_t thread)
+ void
+ set_user_neon_reg(thread_t thread, unsigned int regno, uint128_t val)
+ {
++ linux64_el0_fpu_flush(thread);
+ #if HAS_ARM_FEAT_SME
+ arm_sme_saved_state_t *sme_ss = machine_thread_get_sme_state(thread);
+ if (sme_ss && (sme_ss->svcr & SVCR_SM)) {
+@@ -2186,11 +2218,13 @@ set_user_neon_reg(thread_t thread, unsigned int regno, uint128_t val)
+ uint8_t *z_dst = z_0 + (regno * sme_ss->svl_b);
+ bcopy(&val, z_dst, sizeof(val));
+ bzero(z_dst + sizeof(val), sme_ss->svl_b - sizeof(val));
++ linux64_el0_fpu_invalidate(thread);
+ return;
+ }
+ #endif
+ void *q_dst = &thread->machine.uNeon->ns_64.v.q[regno];
+ bcopy(&val, q_dst, sizeof(val));
++ linux64_el0_fpu_invalidate(thread);
+ }
+
+ /*
+diff --git a/osfmk/arm64/tlb.h b/osfmk/arm64/tlb.h
+index c0154ab..dcc77df 100644
+--- a/osfmk/arm64/tlb.h
++++ b/osfmk/arm64/tlb.h
+@@ -89,9 +89,14 @@ arm64_sync_tlb(bool strong __unused)
+ }
+
+ // flush_mmu_tlb: full TLB flush on all cores
++extern unsigned int linux64_el0;
++
+ static inline void
+ flush_mmu_tlb_async(void)
+ {
++ if (linux64_el0) {
++ return;
++ }
+ asm volatile ("tlbi vmalle1is");
+ }
+
+@@ -111,6 +116,9 @@ flush_mmu_tlb(void)
+ static inline void
+ flush_core_tlb_async(void)
+ {
++ if (linux64_el0) {
++ return;
++ }
+ #if HAS_FEAT_XS
+ asm volatile ("tlbi vmalle1nxs");
+ #else
+@@ -131,6 +139,9 @@ static inline void
+ flush_mmu_tlb_allentries_async(uint64_t start, uint64_t end, uint64_t pmap_page_size,
+ bool last_level_only, bool strong __unused)
+ {
++ if (linux64_el0) {
++ return;
++ }
+ #if __ARM_16K_PG__
+ if (pmap_page_size == 16384) {
+ start = start & ~0x3ULL;
+@@ -192,6 +203,9 @@ static inline void
+ flush_mmu_tlb_entries_async(uint64_t start, uint64_t end, uint64_t pmap_page_size,
+ bool last_level_only, bool strong __unused)
+ {
++ if (linux64_el0) {
++ return;
++ }
+ #if __ARM_16K_PG__
+ if (pmap_page_size == 16384) {
+ start = start & ~0x3ULL;
+@@ -289,6 +303,9 @@ flush_mmu_tlb_entries(uint64_t start, uint64_t end, uint64_t pmap_page_size, boo
+ static inline void
+ flush_mmu_tlb_asid_async(uint64_t val, bool strong __unused)
+ {
++ if (linux64_el0) {
++ return;
++ }
+ #if __ARM_KERNEL_PROTECT__
+ /*
+ * If we are flushing ASID 0, this is a kernel operation. With this
+@@ -326,6 +343,9 @@ flush_mmu_tlb_asid(uint64_t val, bool strong)
+ static inline void
+ flush_core_tlb_asid_async(uint64_t val)
+ {
++ if (linux64_el0) {
++ return;
++ }
+ #if __ARM_KERNEL_PROTECT__
+ /*
+ * If we are flushing ASID 0, this is a kernel operation. With this
+@@ -390,6 +410,9 @@ generate_rtlbi_param(ppnum_t npages, uint32_t asid, vm_offset_t va, uint64_t pma
+ static inline void
+ flush_mmu_tlb_range_async(uint64_t val, bool last_level_only, bool strong __unused)
+ {
++ if (linux64_el0) {
++ return;
++ }
+ if (last_level_only) {
+ #if HAS_FEAT_XS
+ if (__probable(!strong)) {
+@@ -424,6 +447,9 @@ flush_mmu_tlb_range(uint64_t val, bool last_level_only, bool strong)
+ static inline void
+ flush_mmu_tlb_allrange_async(uint64_t val, bool last_level_only, bool strong __unused)
+ {
++ if (linux64_el0) {
++ return;
++ }
+ if (last_level_only) {
+ #if HAS_FEAT_XS
+ if (__probable(!strong)) {
+@@ -458,6 +484,9 @@ flush_mmu_tlb_allrange(uint64_t val, bool last_level_only, bool strong)
+ static inline void
+ flush_core_tlb_allrange_async(uint64_t val)
+ {
++ if (linux64_el0) {
++ return;
++ }
+ #if HAS_FEAT_XS
+ asm volatile ("tlbi rvaae1nxs, %0" : : "r"(val));
+ #else
+diff --git a/osfmk/console/serial_console.c b/osfmk/console/serial_console.c
+index 11d9eb4..8c59a02 100644
+--- a/osfmk/console/serial_console.c
++++ b/osfmk/console/serial_console.c
+@@ -1,4 +1,5 @@
+ #include <kern/boot_progress.h>
++#include <linux64/linux64.h>
+ /*
+ * Copyright (c) 2000-2020 Apple, Inc. All rights reserved.
+ *
+@@ -532,6 +533,13 @@ console_resume()
+ void
+ console_write(char *str, int size)
+ {
++ {
++ /* LINUX64 (xnulinux): hosted XNU's console (/dev/console, km) goes to the host (stage 996: bytes, length). */
++ if (linux64_hook && str && size > 0) {
++ linux64_call2(LINUX64_CALL_CONSOLE_WRITE, (unsigned long)str, (unsigned long)size);
++ return;
++ }
++ }
+ if (disableConsoleOutput) {
+ return;
+ }
+diff --git a/osfmk/console/serial_general.c b/osfmk/console/serial_general.c
+index b1ca47a..d878442 100644
+--- a/osfmk/console/serial_general.c
++++ b/osfmk/console/serial_general.c
+@@ -33,6 +33,7 @@
+ */
+
+ #include <kern/spl.h>
++#include <linux64/linux64.h>
+ #include <mach/std_types.h>
+ #include <types.h>
+ #include <kern/thread.h>
+@@ -48,13 +49,32 @@ SECURITY_READ_ONLY_LATE(unsigned int) serialmode;
+ * characters that have been typed.
+ */
+
++/*
++ * LINUX64 (xnulinux): a hosted XNU's console input comes from the host (LINUX64_CALL_CONSOLE_READ), polled by the serial keyboard thread like a UART.
++ */
++static int
++linux64_cons_getc(void)
++{
++ static char buf[64];
++ static int n, i;
++
++ if (i < n) {
++ return (unsigned char)buf[i++];
++ }
++ struct linux64_buf_req q = { .buf = buf, .len = sizeof(buf), .result = 0 };
++ linux64_call(LINUX64_CALL_CONSOLE_READ, &q);
++ n = q.result > 0 ? (int)q.result : 0;
++ i = 0;
++ return n ? (unsigned char)buf[i++] : -1;
++}
++
+ void
+ serial_keyboard_init(void)
+ {
+ kern_return_t result;
+ thread_t thread;
+
+- if (!(serialmode & SERIALMODE_INPUT)) { /* Leave if we do not want a serial console */
++ if (!(serialmode & SERIALMODE_INPUT) && !linux64_hook) { /* Leave if we do not want a serial console */
+ return;
+ }
+
+@@ -82,7 +102,7 @@ serial_keyboard_poll(void)
+ uint64_t next;
+
+ while (1) {
+- chr = _serial_getc(false); /* Get a character if there is one */
++ chr = linux64_hook ? linux64_cons_getc() : _serial_getc(false); /* Get a character if there is one */
+ if (chr < 0) { /* The serial buffer is empty */
+ break;
+ }
+diff --git a/osfmk/device/iokit_rpc.c b/osfmk/device/iokit_rpc.c
+index fd3e49e..2c7a2de 100644
+--- a/osfmk/device/iokit_rpc.c
++++ b/osfmk/device/iokit_rpc.c
+@@ -512,6 +512,24 @@ IOProtectCacheMode(vm_map_t __unused map, mach_vm_address_t __unused va,
+ break;
+ }
+
++ extern unsigned int linux64_el0;
++ bool el0_kmap = (linux64_el0 && pmap == kernel_pmap);
++ if (el0_kmap) {
++ if (!pmap_el0_wimg_supported(flags)) {
++ return KERN_NOT_SUPPORTED;
++ }
++ uint64_t end_va = 0;
++ if (os_add_overflow(va, length, &end_va)) {
++ return KERN_INVALID_ADDRESS;
++ }
++ for (off = 0; off < length; off += page_size) {
++ ppnum_t ppnum = pmap_find_phys(pmap, va + off);
++ if (ppnum && !pmap_el0_kmap_range_supported(va + off, ptoa_64(ppnum), page_size)) {
++ return KERN_NOT_SUPPORTED;
++ }
++ }
++ }
++
+ pmap_flush_context_init(&pmap_flush_context_storage);
+ delayed_pmap_flush = FALSE;
+
+@@ -529,8 +547,18 @@ IOProtectCacheMode(vm_map_t __unused map, mach_vm_address_t __unused va,
+ panic("Illegal cache attribute overwrite on tagged mapping at 0x%016llx in pmap 0x%016llx", va + off, (uint64_t)pmap);
+ }
+ #endif
+- pmap_enter_options(pmap, va + off, ppnum, prot, VM_PROT_NONE, flags, TRUE,
++ kern_return_t kr = pmap_enter_options(pmap, va + off, ppnum, prot, VM_PROT_NONE, flags, TRUE,
+ PMAP_OPTIONS_NOFLUSH, (void *)&pmap_flush_context_storage, PMAP_MAPPING_TYPE_INFER);
++ if (kr != KERN_SUCCESS) {
++ if (el0_kmap) {
++ panic("linux64_el0: IOProtectCacheMode KMAP failed va=0x%llx kr=%d",
++ (unsigned long long)(va + off), kr);
++ }
++ if (delayed_pmap_flush == TRUE) {
++ pmap_flush(&pmap_flush_context_storage);
++ }
++ return kr;
++ }
+ delayed_pmap_flush = TRUE;
+ }
+ }
+diff --git a/osfmk/kern/assert.h b/osfmk/kern/assert.h
+index 4224c9d..4a1fe94 100644
+--- a/osfmk/kern/assert.h
++++ b/osfmk/kern/assert.h
+@@ -193,9 +193,28 @@ STATIC_IF_KEY_DECLARE_TRUE(mach_assert);
+ #define mach_assert_enabled_expr(ex) \
+ (mach_assert_enabled() || __builtin_constant_p(!(ex)))
+
++#if defined(XNU_KERNEL_PRIVATE) && defined(__arm64__)
++/*
++ * LINUX64 (xnulinux): hosted inside Linux there is no XNU exception vector for the assert brk, so a
++ * failed assert() is reported to the host, which decides whether XNU continues or the run ends.
++ */
++#ifdef __cplusplus
++extern "C" {
++#endif
++extern unsigned long linux64_hook;
++extern void linux64_assert_report(const char *file, int line, const char *expr);
++#ifdef __cplusplus
++}
++#endif
++#define assert(ex) \
++ (mach_assert_enabled_expr(ex) && !(ex) \
++ ? (linux64_hook ? linux64_assert_report(__FILE_NAME__, __LINE__, #ex) \
++ : (void)mach_assert_abort(#ex)) : (void)0)
++#else
+ #define assert(ex) \
+ (mach_assert_enabled_expr(ex) && !(ex) \
+ ? (void)mach_assert_abort(#ex) : (void)0)
++#endif
+
+ #define assertf(ex, fmt, args...) ({ \
+ if (mach_assert_enabled_expr(ex) && __builtin_expect(!(ex), 0L)) { \
+diff --git a/osfmk/kern/backtrace.c b/osfmk/kern/backtrace.c
+index 77044be..2c195af 100644
+--- a/osfmk/kern/backtrace.c
++++ b/osfmk/kern/backtrace.c
+@@ -48,7 +48,7 @@
+ #include <arm64/mte.h>
+ #endif // HAS_MTE
+
+-#if __x86_64__
++#if __x86_64__ || __arm64__ /* LINUX64: hosted, a kernel stack also has frames in Linux's text, beyond 32 bits of stext */
+ static void
+ _backtrace_packed_out_of_reach(void)
+ {
+@@ -58,7 +58,7 @@ _backtrace_packed_out_of_reach(void)
+ //
+ // This is an Intel only issue.
+ }
+-#endif // __x86_64__
++#endif // __x86_64__ || __arm64__
+
+ // Pack an address according to a particular packing format.
+ static size_t
+@@ -74,7 +74,7 @@ _backtrace_pack_addr(backtrace_pack_t packing, uint8_t *dst, size_t dst_size,
+ case BTP_KERN_OFFSET_32:;
+ uintptr_t addr_delta = addr - vm_kernel_stext;
+ int32_t addr_packed = (int32_t)addr_delta;
+-#if __x86_64__
++#if __x86_64__ || __arm64__
+ if ((uintptr_t)(int32_t)addr_delta != addr_delta) {
+ addr = (vm_offset_t)&_backtrace_packed_out_of_reach;
+ addr_delta = addr - vm_kernel_stext;
+diff --git a/osfmk/kern/debug.c b/osfmk/kern/debug.c
+index 0eae1f6..8d31f1d 100644
+--- a/osfmk/kern/debug.c
++++ b/osfmk/kern/debug.c
+@@ -55,6 +55,7 @@
+ */
+
+ #include <mach_assert.h>
++#include <linux64/linux64.h>
+ #include <mach_kdp.h>
+ #include <kdp/kdp.h>
+ #include <kdp/kdp_core.h>
+@@ -754,7 +755,20 @@ DebuggerTrapWithState(debugger_op db_op, const char *db_message, const char *db_
+ * The rest of the cores are halted by IPI if possible; if that
+ * fails it will fall back to dbgwrap.
+ */
++ {
++ /*
++ * LINUX64 (xnulinux): the hosted kernel's exceptions are taken by Linux, which does not hand XNU this trap
++ * (an uncategorized exception), so a stackshot (spindump, tailspin, sysdiagnose) ended the whole run. The
++ * stackshot needs no trap frame (handle_debugger_trap takes it with do_stackshot(NULL)) and there is one CPU:
++ * call the handler here, as the trap would (kdp_trap -> handle_debugger_trap).
++ */
++ if (linux64_hook && db_op == DBOP_STACKSHOT) {
++ handle_debugger_trap(0, 0, 0, NULL); /* the exception number only matters for breakpoints */
++ goto trapped;
++ }
++ }
+ TRAP_DEBUGGER;
++trapped:
+
+ ret = CPUDEBUGGERRET;
+
+@@ -1253,6 +1267,26 @@ panic_trap_to_debugger(const char *panic_format_str, va_list *panic_args, unsign
+ {
+ #pragma clang diagnostic pop
+
++#if defined(__arm64__)
++ {
++ /* LINUX64 (xnulinux): report the panic to the host (see arm_init.c). */
++ if (linux64_hook) {
++ /* the formatted message when there are arguments (the format string alone otherwise) */
++ static char linux64_panic_buf[512];
++ const char *msg = panic_format_str;
++ if (panic_args != NULL && panic_format_str != NULL) {
++ extern int vsnprintf(char *, size_t, const char *, va_list);
++ va_list ap;
++ va_copy(ap, *panic_args);
++ vsnprintf(linux64_panic_buf, sizeof(linux64_panic_buf), panic_format_str, ap);
++ va_end(ap);
++ msg = linux64_panic_buf;
++ }
++ linux64_call2(LINUX64_CALL_PANIC, (unsigned long)msg, panic_caller);
++ }
++ }
++#endif
++
+ #if defined(__x86_64__) && (DEVELOPMENT || DEBUG)
+ read_lbr();
+ #endif
+diff --git a/osfmk/kern/kext_alloc.c b/osfmk/kern/kext_alloc.c
+index 119c6c7..f3e43a6 100644
+--- a/osfmk/kern/kext_alloc.c
++++ b/osfmk/kern/kext_alloc.c
+@@ -26,6 +26,7 @@
+ * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
+ */
+ #include <kern/assert.h>
++#include <linux64/linux64.h>
+ #include <kern/debug.h>
+ #include <kern/kext_alloc.h>
+ #include <kern/misc_protos.h>
+@@ -218,6 +219,18 @@ check_reachable:
+ }
+ #endif
+
++ {
++ /*
++ * LINUX64 (xnulinux): hosted XNU has no page-fault path of its own yet (Linux takes the abort), so kext
++ * memory is wired up front instead of faulted in on first touch.
++ */
++ if (linux64_hook) {
++ kern_return_t wr = vm_map_wire_kernel(g_kext_map, addr, addr + size, VM_PROT_DEFAULT, VM_KERN_MEMORY_KEXT, FALSE);
++ if (wr != KERN_SUCCESS) {
++ printf("linux64: kext_alloc wire failed %d\n", wr);
++ }
++ }
++ }
+ /* Check that the memory is reachable by kernel text */
+ if ((addr + size) > kext_alloc_max) {
+ kext_free((vm_offset_t)addr, size);
+diff --git a/osfmk/kern/link_compat.c b/osfmk/kern/link_compat.c
+index e494eab..c2e215c 100644
+--- a/osfmk/kern/link_compat.c
++++ b/osfmk/kern/link_compat.c
+@@ -65,3 +65,40 @@ native_verified_block_manifest_sha384(unsigned int device, const char *uuid, uin
+ }
+
+ #endif
++
++/*
++ * LINUX64 (xnulinux): macOS 27 kernel functions that 27.2's RTBuddy kext imports and xnu-12377 does not have.
++ * The hosted kernel has no coprocessors; both are no-ops.
++ */
++int os_log_coprocessor_with_handle(void);
++int
++os_log_coprocessor_with_handle(void)
++{
++ return 0;
++}
++
++int os_metric_coprocessor(void);
++int
++os_metric_coprocessor(void)
++{
++ return 0;
++}
++
++/*
++ * LINUX64 (xnulinux): the two functions of compiler-rt's profile runtime that OSKext's kext PGO collection calls. Without
++ * them the link takes the runtime's objects from the toolchain's libclang_rt.cc_kext archive, Apple's binary. No kext
++ * here is built with profiling; one that is gets size 0 and EIO.
++ */
++uint64_t __llvm_profile_get_size_for_buffer_internal(void);
++uint64_t
++__llvm_profile_get_size_for_buffer_internal(void)
++{
++ return 0;
++}
++
++int __llvm_profile_write_buffer_internal(void);
++int
++__llvm_profile_write_buffer_internal(void)
++{
++ return -1;
++}
+diff --git a/osfmk/kern/printf.c b/osfmk/kern/printf.c
+index 2fc6931..d581670 100644
+--- a/osfmk/kern/printf.c
++++ b/osfmk/kern/printf.c
+@@ -155,6 +155,7 @@
+ */
+
+ #include <debug.h>
++#include <linux64/linux64.h>
+ #include <mach_kdp.h>
+ #include <mach/boolean.h>
+ #include <kern/cpu_number.h>
+@@ -876,6 +877,20 @@ __printflike(1, 0)
+ static int
+ vprintf_internal(const char *fmt, va_list ap_in, void *caller)
+ {
++ {
++ /* LINUX64 (xnulinux): hosted XNU prints through the host (dmesg), like kprintf. */
++ if (linux64_hook && fmt) {
++ extern int vsnprintf(char *, size_t, const char *, va_list);
++ char buf[256];
++ va_list ap;
++ va_copy(ap, ap_in);
++ vsnprintf(buf, sizeof(buf), fmt, ap);
++ va_end(ap);
++ linux64_call(LINUX64_CALL_KPRINTF, buf);
++ (void)caller;
++ return 0;
++ }
++ }
+ if (fmt) {
+ struct console_printbuf_state info_data;
+
+diff --git a/osfmk/kern/sched_prim.c b/osfmk/kern/sched_prim.c
+index b2aae03..af01ff3 100644
+--- a/osfmk/kern/sched_prim.c
++++ b/osfmk/kern/sched_prim.c
+@@ -65,6 +65,7 @@
+ */
+
+ #include <kern/sched_prim.h>
++#include <linux64/linux64.h>
+
+ #if !SCHED_TEST_HARNESS
+
+@@ -3010,6 +3011,7 @@ thread_invoke(
+
+ thread_continue_t continuation = self->continuation;
+ void *parameter = self->parameter;
++ linux64_count(LINUX64_CTR_SWITCHES); linux64_dbg[LINUX64_CTR_THREAD] = (unsigned long)thread; /* LINUX64: for the host's monitor */
+
+ struct recount_snap snap = { 0 };
+ recount_snapshot(&snap);
+@@ -6452,6 +6454,7 @@ processor_idle(
+ recount_processor_idle(&processor->pr_recount, &snap);
+
+ while (1) {
++ linux64_count(LINUX64_CTR_IDLE_THREAD); /* LINUX64: for the host's monitor */
+ /*
+ * Ensure that updates to my processor and pset state,
+ * made by the IPI source processor before sending the IPI,
+@@ -9984,3 +9987,45 @@ sysctl_clutch_thread_group_cpu_time_for_thread(__unused thread_t thread,
+ #endif /* !SCHED_TEST_HARNESS */
+
+ #endif /* DEVELOPMENT || DEBUG */
++
++/*
++ * 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)
++{
++ thread_t t;
++ int n = 0;
++ extern int proc_pid(struct proc *);
++ queue_iterate(&threads, t, thread_t, threads) {
++ if (++n > 400) {
++ break;
++ }
++ void *bp = get_bsdthreadtask_info(t);
++ if (bp == NULL || proc_pid((struct proc *)bp) == 0) {
++ /* the kernel's own threads: only those blocked with a saved stack (not parked on a continuation) */
++ if (t->continuation != NULL || t->kernel_stack == 0) {
++ continue;
++ }
++ kprintf("linux64 proc 0 kernel_task\n");
++ } else {
++ kprintf("linux64 proc %d %s\n", proc_pid((struct proc *)bp), proc_name_address((struct proc *)bp));
++ }
++ struct arm_kernel_saved_state *ss = (struct arm_kernel_saved_state *)(void *)t->machine.kstackptr;
++ uint64_t lr = 0, fp = 0;
++ if (ss != NULL && t->kernel_stack != 0) {
++ lr = ss->lr | 0xffffff8000000000ULL;
++ fp = ss->fp;
++ }
++ kprintf("linux64 thread %p tid %llu state 0x%x pri %d wait %p cont %p lr 0x%llx\n",
++ t, t->thread_id, t->state, t->sched_pri, (void *)t->wait_event, (void *)t->continuation, lr);
++ for (int f = 0; f < 14 && fp != 0 && t->kernel_stack != 0 &&
++ fp >= t->kernel_stack && fp < t->kernel_stack + kernel_stack_size; f++) {
++ uint64_t *frame = (uint64_t *)fp;
++ kprintf("linux64 frame 0x%llx\n", frame[1] | 0xffffff8000000000ULL);
++ fp = frame[0];
++ }
++ }
++}
+diff --git a/osfmk/kern/stack.c b/osfmk/kern/stack.c
+index 1111ccf..b2a685d 100644
+--- a/osfmk/kern/stack.c
++++ b/osfmk/kern/stack.c
+@@ -30,6 +30,7 @@
+ */
-@@ -354,7 +354,7 @@ Lbegin_panic_lockdown_continue_\@:
- str x1, [x0, #24] // spsr
- mrs x1, SP_EL0
- str x1, [x0, #32] // sp
-- mrs x1, TPIDR_EL1
-+ mrs x1, TPIDRRO_EL0
- str x1, [x0, #40] // tpidr (thread pointer)
+ #include <mach/mach_host.h>
++#include <linux64/linux64.h>
+ #include <mach/mach_types.h>
+ #include <mach/processor_set.h>
- /* Get timestamp */
-@@ -396,7 +396,7 @@ Lbegin_panic_lockdown_continue_\@:
- cmp x1, x2 // If we have a data abort, we need to
- b.ne Lvalid_stack_\@ // ...validate the stack pointer
- mrs x0, SP_EL0 // Get SP_EL0
-- mrs x1, TPIDR_EL1 // Get thread pointer
-+ mrs x1, TPIDRRO_EL0 // Get thread pointer
- /*
- * Check for either a NULL TPIDR or a NULL kernel stack, both of which
- * are expected in early boot, but will cause recursive faults if not
-@@ -490,7 +490,7 @@ Lvalid_stack_\@:
- * Clobbers NZCV.
+@@ -185,6 +186,24 @@ STARTUP(TUNABLES, STARTUP_RANK_MIDDLE, stack_init);
+ * block.
*/
- .macro CHECK_EXCEPTION_STACK invalid_stack_label
-- mrs x18, TPIDR_EL1 // Get thread pointer
-+ mrs x18, TPIDRRO_EL0 // Get thread pointer
- /*
- * The thread pointer might be invalid during early boot.
- * Return zero in x18 to indicate that we failed to execute the check.
-@@ -631,7 +631,7 @@ Lel0_serror_vector_64:
- // SWITCH_TO_INT_STACK requires a clobberable tmp register, but at this
- // point in the exception vector we can't spare the extra GPR. Instead note
- // that EL1_SP0_VECTOR ends with x0 == sp and use this to unclobber x0.
-- mrs x1, TPIDR_EL1
-+ mrs x1, TPIDRRO_EL0
- LOAD_INT_STACK_THREAD dst=x1, src=x1, tmp=x0
- mov x0, sp
- mov sp, x1
-@@ -701,7 +701,7 @@ Lkernel_stack_valid:
- * Slow path: check/map redzone.
- * Skip redzone mapping if preemption is disabled (e.g. possibly in SPTM context)
- */
-- mrs x0, TPIDR_EL1
-+ mrs x0, TPIDRRO_EL0
- ldr w0, [x0, ACT_PREEMPT_CNT]
- cbnz w0, Lel1_sp0_redzone_done_\@ // Preemption disabled, skip redzone
-@@ -822,7 +822,7 @@ Lel1_sp1_synchronous_vector_continue:
- *
- * Ensure that we actually performed the check on a legitmate value now.
- */
-- mrs x0, TPIDR_EL1
-+ mrs x0, TPIDRRO_EL0
- LOAD_EXCEP_STACK_THREAD dst=x0, src=x0, tmp=x1
- cmp x0, x18
- /* If we aren't equal, something is very wrong and we should lockdown. */
-@@ -875,7 +875,7 @@ LEXT(el1_sp1_synchronous_vector_long_spill_failed)
- /* Macro returns x0=1 if it performed a simulated lockdown */
- cbz x0, 0f
- /* This was a test; return to fault handler so they can fixup the system. */
-- mrs x0, TPIDR_EL1
-+ mrs x0, TPIDRRO_EL0
- ldr x16, [x0, TH_EXPECTED_FAULT_HANDLER]
- #if __has_feature(ptrauth_calls)
- movk x17, #TH_EXPECTED_FAULT_HANDLER_DIVERSIFIER
-@@ -944,7 +944,7 @@ el1_sp1_serror_vector_long:
- #if __ARM_KERNEL_PROTECT__
- mov x18, #0 // Zero x18 to avoid leaking data to user SS
- #endif
-- mrs x0, TPIDR_EL1 // Load the thread register
-+ mrs x0, TPIDRRO_EL0 // Load the thread register
- LOAD_USER_PCB dst=x0, src=x0, tmp=x1 // Load the user context pointer
- mrs x1, SP_EL0 // Load the user stack pointer
- str x1, [x0, SS64_SP] // Store the user stack pointer in the user PCB
-@@ -953,7 +953,7 @@ el1_sp1_serror_vector_long:
- msr SPSel, #0 // Switch to SP0
- stp x0, x1, [sp, SS64_X0] // Save x0, x1 to the user PCB
- stp x2, x3, [sp, SS64_X2] // Save x2, x3 to the user PCB
-- mrs x1, TPIDR_EL1 // Load the thread register
-+ mrs x1, TPIDRRO_EL0 // Load the thread register
++/*
++ * LINUX64 (xnulinux): an exception taken on an XNU kernel stack enters Linux's vectors, whose overflow check wants
++ * bit THREAD_SHIFT (14) of sp clear, as on Linux's 2*THREAD_SIZE-aligned stacks. Hosted, each stack starts on a
++ * 32 KiB boundary. The allocation's mask aligns the address after its first guard page (kernel_memory_allocate with
++ * KMA_GUARD_FIRST: the start plus one page is 32 KiB aligned), so the stack sits one page plus 32 KiB above the start
++ * (the two guard pages, then unused wired pages, then the stack, then the upper guard page), for any page size.
++ */
++static inline vm_offset_t
++linux64_stack_lead(void)
++{
++ return linux64_hook ? ptoa(1) + 0x8000 : ptoa(2);
++}
++static inline vm_offset_t
++linux64_stack_mask(void)
++{
++ return linux64_hook ? (stack_addr_mask | 0x7fff) : stack_addr_mask;
++}
++
+ static vm_offset_t
+ stack_alloc_internal(void)
+ {
+@@ -218,7 +237,7 @@ stack_alloc_internal(void)
+ */
+ kernel_memory_allocate(kernel_map, &stack,
+- kernel_stack_size + ptoa(3), stack_addr_mask,
++ kernel_stack_size + linux64_stack_lead() + ptoa(1), linux64_stack_mask(),
+ flags, VM_KERN_MEMORY_STACK);
+ /*
+@@ -226,7 +245,10 @@ stack_alloc_internal(void)
+ * guard pages. Skip past them to get the actual stack base address.
+ */
-@@ -1321,7 +1321,7 @@ Lblocked_user_sync_exception:
- * sp - Interrupt stack for the current CPU
- */
- .macro BEGIN_INTERRUPT_HANDLER
-- mrs x22, TPIDR_EL1
-+ mrs x22, TPIDRRO_EL0
- ldr x23, [x22, ACT_CPUDATAP] // Get current cpu
- /* Update IRQ count; CPU_STAT_IRQ.* is required to be accurate for the WFE idle sequence */
- ldr w1, [x23, CPU_STAT_IRQ]
-@@ -1529,7 +1529,7 @@ LEXT(fleh_check_map_redzone)
- PUSH_FRAME
+- stack += ptoa(2);
++ stack += linux64_stack_lead();
++ if (linux64_hook && (stack & 0x7fff)) { /* Linux would take an exception on it for a stack overflow */
++ panic("linux64: kernel stack %p is not on a 32 KiB boundary", (void *)stack);
++ }
+ }
+ return stack;
+ }
+@@ -389,8 +411,8 @@ stack_collect(void)
+ stack = (vm_offset_t)vm_map_trunc_page(
+ stack,
+ VM_MAP_PAGE_MASK(kernel_map));
+- stack -= ptoa(2);
+- kmem_free(kernel_map, stack, kernel_stack_size + ptoa(3),
++ stack -= linux64_stack_lead();
++ kmem_free(kernel_map, stack, kernel_stack_size + linux64_stack_lead() + ptoa(1),
+ KMF_GUARD_FIRST | KMF_GUARD_LAST | KMF_GUARD_STACK);
+ stack = 0;
- /* Check if we have a valid thread */
-- mrs x1, TPIDR_EL1
-+ mrs x1, TPIDRRO_EL0
- cbz x1, Lfleh_check_map_redzone_skip
+diff --git a/osfmk/mach/arm/thread_status.h b/osfmk/mach/arm/thread_status.h
+index 99971b0..fc03c4e 100644
+--- a/osfmk/mach/arm/thread_status.h
++++ b/osfmk/mach/arm/thread_status.h
+@@ -483,6 +483,7 @@ extern void ml_panic_on_invalid_new_cpsr(const arm_saved_state_t *, uint32_t) __
+ __BEGIN_DECLS
+ extern uint64_t ml_pac_safe_interrupts_disable(void);
+ extern void ml_pac_safe_interrupts_restore(uint64_t);
++extern unsigned int linux64_el0;
+ __END_DECLS
- /* Get kernel stack bottom */
-@@ -1671,7 +1671,7 @@ Lfleh_synchronous_sp1_skip_panic_lockdown:
- * still on init_thread) and we try to panic(), we'll end up in an infinite
- * nested exception, so just stop here instead to preserve the call stack.
- */
-- mrs x9, TPIDR_EL1
-+ mrs x9, TPIDRRO_EL0
- cbz x9, 0f
- ldr x9, [x9, TH_KSTACKPTR]
- cbz x9, 0f
-@@ -1742,7 +1742,7 @@ LEXT(xnu_return_to_gl2)
- * If thread->txm_thread_stack is set, we need to tell SPTM dispatch to
- * resume the TXM thread in x0.
- */
-- mrs x8, TPIDR_EL1
-+ mrs x8, TPIDRRO_EL0
- ldr x8, [x8, TH_TXM_THREAD_STACK]
- cbz x8, 1f
- mov x0, x8
-@@ -1756,7 +1756,7 @@ LEXT(xnu_return_to_gl2)
- * we need to tell SPTM dispatch to resume the SK thread.
- */
- 1:
-- mrs x8, TPIDR_EL1
-+ mrs x8, TPIDRRO_EL0
- ldr x9, [x8, TH_EXCLAVES_INTSTATE]
- and x9, x9, TH_EXCLAVES_EXECUTION
- cbz x9, 1f
-@@ -1783,7 +1783,7 @@ LEXT(return_to_kernel)
- UNWIND_PROLOGUE
- RETURN_TO_KERNEL_UNWIND
- tbnz w0, #DAIF_IRQF_SHIFT, exception_return // Skip AST check if IRQ disabled
-- mrs x3, TPIDR_EL1 // Load thread pointer
-+ mrs x3, TPIDRRO_EL0 // Load thread pointer
- ldr w1, [x3, ACT_PREEMPT_CNT] // Load preemption count
- msr DAIFSet, #DAIFSC_ALL // Disable exceptions
- cbnz x1, exception_return_unint_tpidr_x3 // If preemption disabled, skip AST check
-@@ -1802,6 +1802,12 @@ LEXT(return_to_kernel)
- .globl EXT(thread_bootstrap_return)
- LEXT(thread_bootstrap_return)
- ARM64_PROLOG
-+ // LINUX64 (xnulinux): hosted, a new user thread's first return goes through C (user space is not hosted yet)
-+ adrp x9, _linux64_hook@PAGE
-+ ldr x9, [x9, _linux64_hook@PAGEOFF]
-+ cbz x9, 1f
-+ b EXT(linux64_thread_bootstrap_return)
-+1:
- #if CONFIG_DTRACE
- bl EXT(dtrace_thread_bootstrap)
- #endif
-@@ -1816,7 +1822,13 @@ LEXT(thread_bootstrap_return)
- .globl EXT(arm64_thread_exception_return)
- LEXT(arm64_thread_exception_return)
- ARM64_PROLOG
-- mrs x0, TPIDR_EL1
-+ // LINUX64 (xnulinux): hosted, a return to user space goes through C (user space is not hosted yet)
-+ adrp x9, _linux64_hook@PAGE
-+ ldr x9, [x9, _linux64_hook@PAGEOFF]
-+ cbz x9, 1f
-+ b EXT(linux64_thread_bootstrap_return)
-+1:
-+ mrs x0, TPIDRRO_EL0
- LOAD_USER_PCB dst=x21, src=x0, tmp=x28
- mov x28, xzr
+ /*
+@@ -519,33 +520,62 @@ extern void ml_check_signed_state(const arm_saved_state_t *, uint64_t, uint32_t,
+ #define MANIPULATE_SIGNED_THREAD_STATE(_iss, _instr, ...) \
+ do { \
+ uint64_t _intr = ml_pac_safe_interrupts_disable(); \
+- asm volatile ( \
+- "mov x9, lr" "\n" \
+- "mov x0, %[iss]" "\n" \
+- "msr SPSel, #1" "\n" \
+- "ldp x4, x5, [x0, %[SS64_X16]]" "\n" \
+- "ldr x7, [x0, %[SS64_PC]]" "\n" \
+- "ldr w8, [x0, %[SS64_CPSR]]" "\n" \
+- "ldr x3, [x0, %[SS64_LR]]" "\n" \
+- "mov x1, x7" "\n" \
+- "mov w2, w8" "\n" \
+- "bl _ml_check_signed_state" "\n" \
+- "mov x1, x7" "\n" \
+- "mov w2, w8" "\n" \
+- _instr "\n" \
+- "bl _ml_sign_thread_state" "\n" \
+- "0:" "\n" \
+- "msr SPSel, #0" "\n" \
+- "mov lr, x9" "\n" \
+- : \
+- : [iss] "r"(_iss), \
+- [SS64_X16] "i"(ss64_offsetof(x[16])), \
+- [SS64_PC] "i"(ss64_offsetof(pc)), \
+- [SS64_CPSR] "i"(ss64_offsetof(cpsr)), \
+- [SS64_LR] "i"(ss64_offsetof(lr)),##__VA_ARGS__ \
+- : "x0", "x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", \
+- "x9", "x16", "x17" \
+- ); \
++ if (linux64_el0) { \
++ asm volatile ( \
++ "mov x9, lr" "\n" \
++ "mov x0, %[iss]" "\n" \
++ "ldp x4, x5, [x0, %[SS64_X16]]" "\n" \
++ "ldr x7, [x0, %[SS64_PC]]" "\n" \
++ "ldr w8, [x0, %[SS64_CPSR]]" "\n" \
++ "ldr x3, [x0, %[SS64_LR]]" "\n" \
++ "mov x1, x7" "\n" \
++ "mov w2, w8" "\n" \
++ "bl _ml_check_signed_state" "\n" \
++ "mov x1, x7" "\n" \
++ "mov w2, w8" "\n" \
++ _instr "\n" \
++ "bl _ml_sign_thread_state" "\n" \
++ "0:" "\n" \
++ "mov lr, x9" "\n" \
++ : \
++ : [iss] "r"(_iss), \
++ [SS64_X16] "i"(ss64_offsetof(x[16])), \
++ [SS64_PC] "i"(ss64_offsetof(pc)), \
++ [SS64_CPSR] "i"(ss64_offsetof(cpsr)), \
++ [SS64_LR] "i"(ss64_offsetof(lr)),##__VA_ARGS__ \
++ : "x0", "x1", "x2", "x3", "x4", "x5", "x6", \
++ "x7", "x8", "x9", "x16", "x17" \
++ ); \
++ } else { \
++ asm volatile ( \
++ "mov x9, lr" "\n" \
++ "mov x0, %[iss]" "\n" \
++ "mrs x10, SPSel" "\n" \
++ "msr SPSel, #1" "\n" \
++ "ldp x4, x5, [x0, %[SS64_X16]]" "\n" \
++ "ldr x7, [x0, %[SS64_PC]]" "\n" \
++ "ldr w8, [x0, %[SS64_CPSR]]" "\n" \
++ "ldr x3, [x0, %[SS64_LR]]" "\n" \
++ "mov x1, x7" "\n" \
++ "mov w2, w8" "\n" \
++ "bl _ml_check_signed_state" "\n" \
++ "mov x1, x7" "\n" \
++ "mov w2, w8" "\n" \
++ _instr "\n" \
++ "bl _ml_sign_thread_state" "\n" \
++ "0:" "\n" \
++ "msr SPSel, x10" "\n" \
++ "mov lr, x9" "\n" \
++ : \
++ : [iss] "r"(_iss), \
++ [SS64_X16] "i"(ss64_offsetof(x[16])), \
++ [SS64_PC] "i"(ss64_offsetof(pc)), \
++ [SS64_CPSR] "i"(ss64_offsetof(cpsr)), \
++ [SS64_LR] "i"(ss64_offsetof(lr)),##__VA_ARGS__ \
++ : "x0", "x1", "x2", "x3", "x4", "x5", "x6", \
++ "x7", "x8", "x9", "x10", "x16", "x17" \
++ ); \
++ } \
+ ml_pac_safe_interrupts_restore(_intr); \
+ } while (0)
-@@ -1835,7 +1847,7 @@ check_user_asts:
- bl EXT(__asan_handle_no_return)
- POP_FRAME_WITHOUT_LR
- #endif /* KASAN_TBI */
-- mrs x3, TPIDR_EL1 // Load thread pointer
-+ mrs x3, TPIDRRO_EL0 // Load thread pointer
+diff --git a/osfmk/mach/arm/vm_param.h b/osfmk/mach/arm/vm_param.h
+index bb62cdd..9bea611 100644
+--- a/osfmk/mach/arm/vm_param.h
++++ b/osfmk/mach/arm/vm_param.h
+@@ -149,6 +149,11 @@ extern int PAGE_SHIFT_CONST;
+ #undef MACH_VM_MAX_ADDRESS_RAW
+ #define MACH_VM_MAX_ADDRESS_RAW 0x00007FFFFE000000ULL
+ #endif /* defined(XNU_PLATFORM_iPhoneOS) && EXTENDED_USER_VA_SUPPORT */
++#if !__ARM_16K_PG__ && !defined(XNU_PLATFORM_MacOSX)
++/* LINUX64 (xnulinux): 4 KiB user pmaps span 47 bits (pmap_pt_attr_4k_user), the macOS layout its userland expects */
++#undef MACH_VM_MAX_ADDRESS_RAW
++#define MACH_VM_MAX_ADDRESS_RAW 0x00007FFFFE000000ULL
++#endif
+ /* threshold for allocations to be placed in the large file range */
+ #define VM_LARGE_FILE_THRESHOLD (1ULL << 30)
+ #define MACH_VM_JUMBO_ADDRESS ((mach_vm_offset_t) 0x0000000FC0000000ULL)
+@@ -294,7 +299,7 @@ extern int PAGE_SHIFT_CONST;
- movn w2, #0
- str w2, [x3, TH_IOTIER_OVERRIDE] // Reset IO tier override to -1 before returning to user
-@@ -1927,7 +1939,7 @@ no_asts:
- PUSH_FRAME
- bl EXT(arm_debug_set) // Establish thread debug state in live regs
- POP_FRAME_WITHOUT_LR
-- mrs x3, TPIDR_EL1 // Reload thread pointer
-+ mrs x3, TPIDRRO_EL0 // Reload thread pointer
- ldr x4, [x3, ACT_CPUDATAP] // Reload CPU data pointer
- L_skip_user_set_debug_state:
+ #if XNU_KERNEL_PRIVATE
+ #define VM_KERNEL_STRIP_MASK (-1ULL << (64 - T1SZ_BOOT))
+-#define VM_USER_STRIP_MASK (-1ULL >> (T0SZ_BOOT))
++#define VM_USER_STRIP_MASK (-1ULL >> (T0SZ_HW)) /* LINUX64: user addresses span the width TTBR0 runs with */
+ #define _VM_KERNEL_STRIP_PTR(_va) ({((_va) & 1ULL << 55) ? ((_va) | VM_KERNEL_STRIP_MASK) : ((_va) & VM_USER_STRIP_MASK);})
+ #else /* XNU_KERNEL_PRIVATE */
-@@ -1937,7 +1949,7 @@ L_skip_user_set_debug_state:
- exception_return:
- msr DAIFSet, #DAIFSC_ALL // Disable exceptions
- exception_return_unint:
-- mrs x3, TPIDR_EL1 // Load thread pointer
-+ mrs x3, TPIDRRO_EL0 // Load thread pointer
- exception_return_unint_tpidr_x3:
- mov sp, x21 // Reload the pcb pointer
+diff --git a/osfmk/prng/prng_random.c b/osfmk/prng/prng_random.c
+index 44b993c..4ce279b 100644
+--- a/osfmk/prng/prng_random.c
++++ b/osfmk/prng/prng_random.c
+@@ -28,6 +28,7 @@
-@@ -2006,7 +2018,7 @@ Lexception_return_restore_registers:
- // SPSR_EL1.M != EL0: no SME state to restore
- bne Lno_sme_saved_state
+ extern volatile unsigned long long port_crumb; /* port bring-up breadcrumb (link_compat.c) */
+ #include <kern/locks.h>
++#include <linux64/linux64.h>
+ #include <kern/cpu_number.h>
+ #include <libkern/section_keywords.h>
+ #include <libkern/crypto/sha2.h>
+@@ -368,13 +369,23 @@ random_cpu_init(int cpu)
+ panic("random_cpu_init: kernel prng has not been installed");
+ }
-- mrs x3, TPIDR_EL1
-+ mrs x3, TPIDRRO_EL0
- add x3, x3, ACT_UMATRIX_HDR
- ldr x2, [x3]
- cbz x2, Lno_sme_saved_state
-@@ -2071,7 +2083,7 @@ Lno_gcr_mask_el0_reset:
- #endif /* HAS_MTE */
- // If sync_on_cswitch and ERET is not a CSE, issue an ISB now. Unconditionally clear the
- // sync_on_cswitch flag.
-- mrs x1, TPIDR_EL1
-+ mrs x1, TPIDRRO_EL0
- ldr x1, [x1, ACT_CPUDATAP]
+- prng_funcs.initgen(prng_ctx, cpu);
++ if (prng_funcs.initgen != NULL) {
++ prng_funcs.initgen(prng_ctx, cpu);
++ }
+ }
- // Redefined for backporting.
-@@ -2095,7 +2107,7 @@ Lno_gcr_mask_el0_reset:
- mrs x2, SPSR_EL1
- tst x2, #(PSR64_MODE_EL_MASK)
- b.ne 1f
-- mrs x2, TPIDR_EL1
-+ mrs x2, TPIDRRO_EL0
- ldr w2, [x2, TH_ARM_MACHINE_FLAGS]
- tbz w2, #ARM_MACHINE_THREAD_DISABLE_USER_JOP_SHIFT, 1f
- mrs x2, SCTLR_EL1
-@@ -2184,7 +2196,7 @@ user_take_ast:
- .text
- .align 2
- preempt_underflow:
-- mrs x0, TPIDR_EL1
-+ mrs x0, TPIDRRO_EL0
- str x0, [sp, #-16]! // We'll print thread pointer
- adr x0, L_underflow_str // Format string
- CALL_EXTERN panic // Game over
-@@ -2197,7 +2209,7 @@ L_underflow_str:
- .text
- .align 2
- preempt_count_notzero:
-- mrs x0, TPIDR_EL1
-+ mrs x0, TPIDRRO_EL0
- str x0, [sp, #-16]! // We'll print thread pointer
- ldr w0, [x0, ACT_PREEMPT_CNT]
- str w0, [sp, #8]
-@@ -2457,7 +2469,7 @@ ppl_exit:
- add x15, x15, x10, lsl #32
+ /* export good random numbers to the rest of the kernel */
+ __mockable void
+ read_random(void * buffer, u_int numbytes)
+ {
++ /*
++ * LINUX64 (xnulinux): without the corecrypto kext nobody calls register_and_init_prng() and prng_funcs stays
++ * zeroed; hosted, the host's generator (Linux's get_random_bytes) stands in.
++ */
++ if (prng_funcs.generate == NULL && linux64_hook) {
++ linux64_random(buffer, numbytes);
++ return;
++ }
+ prng_funcs.refresh(prng_ctx);
+ read_random_generate(buffer, numbytes);
+ }
+@@ -433,7 +444,9 @@ write_random(void * buffer, u_int numbytes)
+ memcpy(seed, buffer, numbytes);
+ }
- /* Load the preemption count. */
-- mrs x10, TPIDR_EL1
-+ mrs x10, TPIDRRO_EL0
- ldr w12, [x10, ACT_PREEMPT_CNT]
+- prng_funcs.reseed(prng_ctx, sizeof(seed), seed);
++ if (prng_funcs.reseed != NULL) {
++ prng_funcs.reseed(prng_ctx, sizeof(seed), seed);
++ }
+ cc_clear(sizeof(seed), seed);
- /* Detect underflow */
-@@ -2493,7 +2505,7 @@ Lno_preempt_underflow:
- mov w12, #0
+ return 0;
+diff --git a/osfmk/vm/pmap.h b/osfmk/vm/pmap.h
+index 67ebd6a..2671903 100644
+--- a/osfmk/vm/pmap.h
++++ b/osfmk/vm/pmap.h
+@@ -740,6 +740,17 @@ extern kern_return_t pmap_unnest_options(pmap_t,
+ unsigned int);
+ extern boolean_t pmap_adjust_unnest_parameters(pmap_t, vm_map_offset_t *, vm_map_offset_t *);
+ extern void pmap_advise_pagezero_range(pmap_t, uint64_t);
++extern bool pmap_el0_kmap_range_supported(vm_map_address_t va, pmap_paddr_t pa, vm_map_size_t size);
++extern bool pmap_el0_kmap_pte_supported(pmap_t pmap, vm_map_address_t va);
++extern bool pmap_el0_kmap_pte_ready(pmap_t pmap, vm_map_address_t va, vm_prot_t req_prot);
++extern bool pmap_el0_wimg_supported(unsigned int wimg);
++extern kern_return_t pmap_el0_update_cache_mode(pmap_t pmap, vm_map_address_t va, unsigned int wimg_flags, bool use_default);
++extern bool pmap_el0_read_pte_snapshot(pmap_t pmap, vm_map_address_t va, uint64_t *pte_out, pmap_paddr_t *pa_out, bool *pa_is_valid_out);
++extern bool pmap_el0_pte_restorable(pmap_t pmap, uint64_t saved_pte_u64);
++extern kern_return_t pmap_el0_restore_pte_snapshot(pmap_t pmap, vm_map_address_t va, uint64_t saved_pte);
++extern kern_return_t pmap_el0_kmap_txn_begin(vm_map_address_t va, vm_map_size_t size, uint64_t *handle_out);
++extern void pmap_el0_kmap_txn_begin_restore(uint64_t handle);
++extern void pmap_el0_kmap_txn_end(uint64_t handle);
+ #endif /* MACH_KERNEL_PRIVATE */
+
+ extern boolean_t pmap_is_noencrypt(ppnum_t);
+diff --git a/osfmk/vm/vm_fault.c b/osfmk/vm/vm_fault.c
+index 79f983b..caa4e94 100644
+--- a/osfmk/vm/vm_fault.c
++++ b/osfmk/vm/vm_fault.c
+@@ -4178,11 +4178,20 @@ vm_fault_enter(
+ int pmap_options = fault_info->pmap_options;
+
+ assert(need_retry != NULL);
++ *need_retry = false;
+
+ if (vm_page_is_guard(m)) {
+ return KERN_SUCCESS;
+ }
- /* Restore the thread pointer into x10. */
-- mrs x10, TPIDR_EL1
-+ mrs x10, TPIDRRO_EL0
++ extern unsigned int linux64_el0;
++ if (linux64_el0 && pmap == kernel_pmap &&
++ !pmap_el0_kmap_range_supported(vaddr,
++ ((pmap_paddr_t)VM_PAGE_GET_PHYS_PAGE(m) << PAGE_SHIFT) + fault_phys_offset,
++ fault_page_size)) {
++ return KERN_NOT_SUPPORTED;
++ }
++
+ fault_type = fault_info->fi_change_wiring ? VM_PROT_NONE : caller_prot;
- Lskip_collect_measurement:
- #endif /* SCHED_HYGIENE_DEBUG */
-@@ -2743,7 +2755,7 @@ LEXT(_sptm_pre_entry_hook)
- stp x6, x7, [sp, #0x30]
+ assertf(VM_PAGE_OBJECT(m) != VM_OBJECT_NULL, "m=%p", m);
+@@ -4191,6 +4200,18 @@ vm_fault_enter(
+ fault_info, type_of_fault, &page_needs_data_sync, page_needs_sleep);
+ object = VM_PAGE_OBJECT(m);
- /* Increase the preemption count. */
-- mrs x9, TPIDR_EL1
-+ mrs x9, TPIDRRO_EL0
- cbz x9, Lskip_preemption_check_sptmhook
- ldr w10, [x9, ACT_PREEMPT_CNT]
- add w10, w10, #1
-@@ -2803,7 +2815,7 @@ LEXT(_sptm_post_exit_hook)
++ bool did_wire = (m->vmp_q_state != VM_PAGE_USED_BY_COMPRESSOR &&
++ fault_info->fi_change_wiring && wired && kr == KERN_SUCCESS);
++
++ if (did_wire && linux64_el0 && pmap == kernel_pmap) {
++ vm_page_lockspin_queues();
++ bool wire_sat = (m->vmp_wire_count >= MAX_WIRE_COUNT);
++ vm_page_unlock_queues();
++ if (wire_sat) {
++ return KERN_RESOURCE_SHORTAGE;
++ }
++ }
++
+ vm_fault_enqueue_page(object, m, wired, fault_info->fi_change_wiring, wire_tag, fault_info->no_cache, type_of_fault, kr);
+ if (__probable((kr == KERN_SUCCESS) && !(*page_needs_sleep))) {
+@@ -4208,6 +4229,18 @@ vm_fault_enter(
+ &prot, caller_prot, fault_type, wired, pmap_options, need_retry, object_lock_type);
+ }
- /* Load the preemption count. */
-- mrs x0, TPIDR_EL1
-+ mrs x0, TPIDRRO_EL0
- cbz x0, Lsptm_skip_ast_taken_sptmhook
- ldr w12, [x0, ACT_PREEMPT_CNT]
++ if (__improbable((kr != KERN_SUCCESS || *need_retry || *page_needs_sleep) && did_wire)) {
++ if (*object_lock_type == OBJECT_LOCK_SHARED) {
++ if (!vm_object_lock_upgrade(object)) {
++ vm_object_lock(object);
++ }
++ *object_lock_type = OBJECT_LOCK_EXCLUSIVE;
++ }
++ vm_page_lockspin_queues();
++ vm_page_unwire(m, TRUE);
++ vm_page_unlock_queues();
++ }
++
+ return kr;
+ }
-@@ -2834,7 +2846,7 @@ Lno_preempt_underflow_sptmhook:
- mov w12, #0
+@@ -6738,7 +6771,8 @@ handle_copy_delay:
+ * while it holds the entry lock, so doing so in the reverse order here
+ * could cause a deadlock.
+ */
+- kr = vm_map_lookup_object_and_lock_entry(&map, vaddr, fault_type,
++ kr = vm_map_lookup_object_and_lock_entry(&map, vaddr,
++ wired ? original_fault_type : fault_type,
+ &retry_object, &entry, &retry_offset, &retry_prot, &wired,
+ fault_info, &real_map, ctx, vml_ctx_for_vaddr,
+ true /* try_lock_entry */);
+@@ -7112,13 +7146,20 @@ handle_copy_delay:
+ */
+ assert(!vm_should_override_mte_cacheattr(block_map_pmap, object, block_map_va, block_map_pa));
+ #endif /* HAS_MTE */
+- kr = pmap_map_block_addr(block_map_pmap,
+- block_map_va,
+- block_map_pa,
+- (uint32_t)((ldelta + hdelta) >> fault_page_shift),
+- prot,
+- block_map_wimg | superpage,
+- 0);
++ extern unsigned int linux64_el0;
++ if (linux64_el0 && block_map_pmap == kernel_pmap &&
++ !pmap_el0_kmap_range_supported((vm_map_address_t)block_map_va,
++ block_map_pa, (vm_map_size_t)(ldelta + hdelta))) {
++ kr = KERN_NOT_SUPPORTED;
++ } else {
++ kr = pmap_map_block_addr(block_map_pmap,
++ block_map_va,
++ block_map_pa,
++ (uint32_t)((ldelta + hdelta) >> fault_page_shift),
++ prot,
++ block_map_wimg | superpage,
++ 0);
++ }
+
+ if (kr != KERN_SUCCESS) {
+ goto cleanup;
+@@ -7291,6 +7332,57 @@ vm_fault_wire_resident_pages(
+ }
+
+ if (VME_OBJECT(entry)->phys_contiguous) {
++ extern unsigned int linux64_el0;
++ vm_map_offset_t pa_base;
++ if (!(linux64_el0 && pmap == kernel_pmap && (prot & (VM_PROT_READ | VM_PROT_WRITE)))) {
++ return KERN_SUCCESS;
++ }
++ /*
++ * IOKit maps device_pager phys_contiguous objects before
++ * calling device_pager_populate_object() and vm_fault().
++ * Skip prefaulting while vo_shadow_offset is still 0 so we
++ * never install a bogus PA=0 PTE; the subsequent vm_fault()
++ * validates pmap_el0_kmap_range_supported() once populated.
++ */
++ if (VME_OBJECT(entry)->private && VME_OBJECT(entry)->pager_created &&
++ !VME_OBJECT(entry)->vo_el0_populated) {
++ return KERN_SUCCESS;
++ }
++ if (os_add_overflow((vm_map_offset_t)VME_OBJECT(entry)->vo_shadow_offset,
++ VME_OFFSET(entry), &pa_base) ||
++ !pmap_el0_kmap_range_supported(pmap_addr, (pmap_paddr_t)pa_base,
++ end_addr - entry->vme_start)) {
++ return KERN_NOT_SUPPORTED;
++ }
++ effective_page_size = MIN(VM_MAP_PAGE_SIZE(map), PAGE_SIZE);
++ for (va = entry->vme_start;
++ va < end_addr;
++ va += effective_page_size) {
++ vm_map_offset_t cur_pmap_addr = pmap_addr + (va - entry->vme_start);
++ if (!pmap_el0_kmap_pte_ready(pmap, cur_pmap_addr, prot)) {
++ struct vm_object_fault_info fault_info = {
++ .interruptible = THREAD_UNINT,
++ .behavior = VM_BEHAVIOR_SEQUENTIAL,
++ .fi_change_wiring = false,
++ };
++ if (os_sub_overflow(end_addr, va, &fault_info.cluster_size)) {
++ fault_info.cluster_size = UPL_SIZE_MAX;
++ }
++ rc = vm_fault_internal(map, va, prot, wire_tag,
++ pmap,
++ cur_pmap_addr,
++ physpage_p,
++ &fault_info,
++ vml_ctx);
++ if (rc != KERN_SUCCESS) {
++ return rc;
++ }
++ if (linux64_el0 && pmap == kernel_pmap &&
++ !pmap_el0_kmap_pte_ready(pmap, cur_pmap_addr, prot)) {
++ return KERN_NOT_SUPPORTED;
++ }
++ }
++ }
+ return KERN_SUCCESS;
+ }
+
+@@ -7312,8 +7404,10 @@ vm_fault_wire_resident_pages(
+ for (va = entry->vme_start;
+ va < end_addr;
+ va += effective_page_size) {
++ extern unsigned int linux64_el0;
++ vm_map_offset_t cur_pmap_addr = pmap_addr + (va - entry->vme_start);
+ rc = vm_fault_wire_fast(map, va, prot, wire_tag, entry, pmap,
+- pmap_addr + (va - entry->vme_start),
++ cur_pmap_addr,
+ physpage_p);
+
+ if (rc != KERN_SUCCESS) {
+@@ -7327,8 +7421,7 @@ vm_fault_wire_resident_pages(
+ }
+ rc = vm_fault_internal(map, va, prot, wire_tag,
+ pmap,
+- (pmap_addr +
+- (va - entry->vme_start)),
++ cur_pmap_addr,
+ physpage_p,
+ &fault_info,
+ vml_ctx);
+@@ -7343,6 +7436,12 @@ vm_fault_wire_resident_pages(
+ DTRACE_VM2(softlock, int, 1, (uint64_t *), NULL);
+ }
+
++ if (rc == KERN_SUCCESS && linux64_el0 && pmap == kernel_pmap &&
++ !pmap_el0_kmap_pte_ready(pmap, cur_pmap_addr, prot) &&
++ !vm_fault_el0_entry_va_skip_pte(map, entry, va)) {
++ rc = KERN_NOT_SUPPORTED;
++ }
++
+ if (rc != KERN_SUCCESS) {
+ vm_object_offset_t current_offset = va - entry->vme_start;
+ /*
+@@ -7361,6 +7460,260 @@ vm_fault_wire_resident_pages(
+ return KERN_SUCCESS;
+ }
+
++bool
++vm_fault_el0_entry_va_skip_pte(
++ vm_map_t map,
++ vm_map_entry_t entry,
++ vm_map_offset_t va)
++{
++ if (entry->is_sub_map) {
++ return false;
++ }
++ vm_object_t obj = VME_OBJECT(entry);
++ if (obj == VM_OBJECT_NULL) {
++ return false;
++ }
++ vm_object_offset_t off;
++ if (os_add_overflow(VME_OFFSET(entry), va - entry->vme_start, &off)) {
++ return false;
++ }
++ vm_object_lock_shared(obj);
++ if (obj->phys_contiguous) {
++ vm_object_unlock(obj);
++ return false;
++ }
++ for (;;) {
++ vm_page_t m = vm_page_lookup(obj, vm_object_trunc_page(off));
++ if (m != VM_PAGE_NULL) {
++ bool is_guard = vm_page_is_guard(m);
++ vm_object_unlock(obj);
++ return is_guard;
++ }
++ vm_object_t next = obj->shadow;
++ if (next == VM_OBJECT_NULL || os_add_overflow(off, obj->vo_shadow_offset, &off)) {
++ vm_object_unlock(obj);
++ return map->never_faults && entry->wired_count > 0;
++ }
++ vm_object_lock_shared(next);
++ vm_object_unlock(obj);
++ obj = next;
++ }
++}
++
++static inline bool
++vm_fault_el0_vo_copy_covers_page_locked(
++ vm_object_t object,
++ vm_object_offset_t page_off)
++{
++ vm_object_t copy_obj = object->vo_copy;
++ if (copy_obj == VM_OBJECT_NULL) {
++ return false;
++ }
++ if (page_off < copy_obj->vo_shadow_offset) {
++ return false;
++ }
++ return (page_off - copy_obj->vo_shadow_offset) < copy_obj->vo_size;
++}
++
++bool
++vm_fault_el0_never_faults_entry_supported(
++ vm_map_entry_t entry,
++ vm_prot_t req_prot)
++{
++ if (entry->is_sub_map || entry->wired_count == 0 || entry->needs_copy) {
++ return false;
++ }
++ vm_object_t obj = VME_OBJECT(entry);
++ if (obj == VM_OBJECT_NULL) {
++ return false;
++ }
++ vm_object_lock_shared(obj);
++ if (obj->phys_contiguous ||
++ obj->shadow != VM_OBJECT_NULL ||
++ obj->copy_strategy == MEMORY_OBJECT_COPY_SYMMETRIC) {
++ vm_object_unlock(obj);
++ return false;
++ }
++ vm_map_size_t entry_size = entry->vme_end - entry->vme_start;
++ for (vm_map_size_t off = 0; off < entry_size; off += PAGE_SIZE) {
++ vm_object_offset_t page_off;
++ if (os_add_overflow(VME_OFFSET(entry), off, &page_off)) {
++ vm_object_unlock(obj);
++ return false;
++ }
++ vm_page_t m = vm_page_lookup(obj, page_off);
++ if (m != VM_PAGE_NULL && !vm_page_is_guard(m)) {
++ if (vm_page_is_fictitious(m) ||
++ m->vmp_wire_count == 0 ||
++ (m->vmp_unusual && (m->vmp_error || m->vmp_restart || m->vmp_absent)) ||
++ ((req_prot & VM_PROT_WRITE) &&
++ vm_fault_el0_vo_copy_covers_page_locked(obj, page_off)) ||
++ !pmap_el0_kmap_range_supported(entry->vme_start + off,
++ (pmap_paddr_t)ptoa_64(VM_PAGE_GET_PHYS_PAGE(m)), PAGE_SIZE)) {
++ vm_object_unlock(obj);
++ return false;
++ }
++ }
++ }
++ vm_object_unlock(obj);
++ return true;
++}
++
++static kern_return_t
++vm_fault_el0_populate_never_faults_page(
++ vm_map_t map,
++ vm_map_entry_t entry,
++ vm_map_offset_t va,
++ vm_prot_t prot,
++ vm_tag_t wire_tag)
++{
++ vm_object_t object = VME_OBJECT(entry);
++ vm_object_offset_t offset = (va - entry->vme_start) + VME_OFFSET(entry);
++ pmap_t pmap = map->pmap;
++ vm_map_size_t fault_page_size = MIN(VM_MAP_PAGE_SIZE(map), PAGE_SIZE);
++ vm_map_offset_t fault_phys_offset = offset - vm_object_trunc_page(offset);
++
++ for (;;) {
++ struct vm_object_fault_info fault_info = {
++ .user_tag = VME_ALIAS(entry),
++ .pmap_options = 0,
++ .fi_change_wiring = false,
++ };
++ if (entry->iokit_acct || (!entry->is_sub_map && !entry->use_pmap)) {
++ fault_info.pmap_options |= PMAP_OPTIONS_ALT_ACCT;
++ }
++ if (entry->vme_xnu_user_debug) {
++ fault_info.pmap_options |= PMAP_OPTIONS_XNU_USER_DEBUG;
++ }
++ if (entry->translated_allow_execute) {
++ fault_info.pmap_options |= PMAP_OPTIONS_TRANSLATED_ALLOW_EXECUTE;
++ }
++
++ vm_object_lock(object);
++ if (entry->needs_copy ||
++ object->shadow != VM_OBJECT_NULL || object->phys_contiguous) {
++ vm_object_unlock(object);
++ return KERN_NOT_SUPPORTED;
++ }
++ vm_object_offset_t page_off = vm_object_trunc_page(offset);
++ vm_page_t m = vm_page_lookup(object, page_off);
++ if (m == VM_PAGE_NULL || vm_page_is_guard(m)) {
++ vm_object_unlock(object);
++ return KERN_SUCCESS;
++ }
++ if (m->vmp_busy) {
++ vm_page_sleep(object, m, THREAD_UNINT, LCK_SLEEP_UNLOCK);
++ continue;
++ }
++ if (vm_page_is_fictitious(m) ||
++ m->vmp_wire_count == 0 ||
++ (m->vmp_unusual && (m->vmp_error || m->vmp_restart || m->vmp_absent)) ||
++ ((prot & VM_PROT_WRITE) &&
++ vm_fault_el0_vo_copy_covers_page_locked(object, page_off))) {
++ vm_object_unlock(object);
++ return KERN_NOT_SUPPORTED;
++ }
++
++ vm_object_reference_locked(object);
++ vm_object_paging_begin(object);
++ m->vmp_busy = TRUE;
++
++ uint8_t object_lock_type = OBJECT_LOCK_EXCLUSIVE;
++ int type_of_fault = DBG_CACHE_HIT_FAULT;
++ bool page_sleep_needed = false;
++ bool need_retry = false;
++ kern_return_t kr = vm_fault_enter(m, pmap, va, fault_page_size,
++ fault_phys_offset, prot, prot, TRUE, wire_tag, &fault_info,
++ &need_retry, &type_of_fault, &object_lock_type, &page_sleep_needed);
++
++ if (need_retry) {
++ /*
++ * NOWAIT pmap enter hit page-table or PV resource shortage.
++ * Keep m->vmp_busy and paging_in_progress held, drop object
++ * lock, and perform blocking pmap enter without NOWAIT.
++ */
++ vm_prot_t enter_prot = prot;
++ vm_object_unlock(object);
++ kr = vm_fault_attempt_pmap_enter(pmap, va, fault_page_size,
++ fault_phys_offset, m, &enter_prot, prot, prot, TRUE,
++ fault_info.pmap_options);
++ vm_object_lock(object);
++ }
++
++ vm_page_wakeup_done(object, m);
++ vm_object_paging_end(object);
++ vm_object_unlock(object);
++ vm_object_deallocate(object);
++
++ if (!need_retry && page_sleep_needed) {
++ mutex_pause(0);
++ continue;
++ }
++ return kr;
++ }
++}
++
++kern_return_t
++vm_fault_el0_populate_wired_entry(
++ vm_map_t map,
++ vm_map_entry_t entry,
++ vm_prot_t prot,
++ vm_tag_t wire_tag,
++ vm_map_lock_ctx_t vml_ctx)
++{
++ vm_map_offset_t va;
++ vm_map_offset_t end_addr = entry->vme_end;
++ kern_return_t rc;
++ vm_map_size_t effective_page_size;
++ pmap_t pmap = map->pmap;
++
++ if (entry->is_sub_map || VME_OBJECT(entry) == VM_OBJECT_NULL ||
++ !(prot & (VM_PROT_READ | VM_PROT_WRITE))) {
++ return KERN_SUCCESS;
++ }
++ if (VME_OBJECT(entry)->phys_contiguous) {
++ return vm_fault_wire_resident_pages(map, entry, prot, wire_tag, NULL, vml_ctx);
++ }
++
++ effective_page_size = MIN(VM_MAP_PAGE_SIZE(map), PAGE_SIZE);
++ for (va = entry->vme_start;
++ va < end_addr;
++ va += effective_page_size) {
++ if (pmap_el0_kmap_pte_ready(pmap, va, prot) ||
++ vm_fault_el0_entry_va_skip_pte(map, entry, va)) {
++ continue;
++ }
++ if (map->never_faults) {
++ rc = vm_fault_el0_populate_never_faults_page(map, entry, va, prot, wire_tag);
++ if (rc != KERN_SUCCESS) {
++ return rc;
++ }
++ } else {
++ rc = vm_fault_wire_fast(map, va, prot, wire_tag, entry, pmap, va, NULL);
++ if (rc != KERN_SUCCESS) {
++ struct vm_object_fault_info fault_info = {
++ .interruptible = THREAD_UNINT,
++ .behavior = VM_BEHAVIOR_SEQUENTIAL,
++ .fi_change_wiring = false,
++ };
++ if (os_sub_overflow(end_addr, va, &fault_info.cluster_size)) {
++ fault_info.cluster_size = UPL_SIZE_MAX;
++ }
++ rc = vm_fault_internal(map, va, prot, wire_tag,
++ pmap, va, NULL, &fault_info, vml_ctx);
++ if (rc != KERN_SUCCESS) {
++ return rc;
++ }
++ }
++ }
++ if (pmap == kernel_pmap && !pmap_el0_kmap_pte_ready(pmap, va, prot) &&
++ !vm_fault_el0_entry_va_skip_pte(map, entry, va)) {
++ return KERN_NOT_SUPPORTED;
++ }
++ }
++ return KERN_SUCCESS;
++}
++
+ /*
+ * For this to happen, the object likely was shrunk during the call to vm_wire
+ */
+@@ -7425,6 +7778,7 @@ vm_fault_wire_object_pages(
- /* Restore x0 as the thread pointer */
-- mrs x0, TPIDR_EL1
-+ mrs x0, TPIDRRO_EL0
- Lskip_collect_measurement_sptmhook:
- #endif /* SCHED_HYGIENE_DEBUG */
-@@ -2916,7 +2928,7 @@ LEXT(panic_lockdown_record_debug_data)
- mov x1, sp
- str x1, [x0, #PANIC_LOCKDOWN_INITIATOR_STATE_INITIATOR_SP]
+ do { /* while (amount_left > 0) */
++ error = 0;
+ prot = VM_PROT_WRITE | VM_PROT_READ;
+
+ /* cap cluster size at maximum UPL size */
+@@ -7526,6 +7880,21 @@ vm_fault_wire_object_pages(
+ assert(object == VM_PAGE_OBJECT(page));
+
+ vm_page_lockspin_queues();
++ extern unsigned int linux64_el0;
++ if (linux64_el0 && map->pmap == kernel_pmap &&
++ page->vmp_wire_count >= MAX_WIRE_COUNT) {
++ vm_page_unlock_queues();
++ vm_page_wakeup_done(object, page);
++ if (top_page != VM_PAGE_NULL) {
++ VM_PAGE_FREE(top_page);
++ }
++ vm_object_paging_end(object);
++ vm_object_unlock(object);
++ if (wire_size > amount_left) {
++ vm_fault_unwire_object_pages(map, object, start_offset, wire_size - amount_left);
++ }
++ return KERN_RESOURCE_SHORTAGE;
++ }
+ vm_page_wire(page, tag, TRUE);
+ vm_page_unlock_queues();
+ vm_page_wakeup_done(object, page);
+@@ -7544,10 +7913,8 @@ vm_fault_wire_object_pages(
+ return KERN_SUCCESS;
+ }
-- mrs x1, TPIDR_EL1
-+ mrs x1, TPIDRRO_EL0
- str x1, [x0, #PANIC_LOCKDOWN_INITIATOR_STATE_INITIATOR_TPIDR]
+-
+-/*!
+- * @abstract
+- * Find a page to later be unwired
++/*
++ * Helper for vm_fault_unwire. Finds the page to unwire at fault_offset.
+ * a vm_page_wakeup_done(object, page) and a vm_fault_cleanup(object, top_page)
+ * should be done by the caller after unwiring the page.
+ *
+diff --git a/osfmk/vm/vm_fault_internal.h b/osfmk/vm/vm_fault_internal.h
+index 8a3d744..d891745 100644
+--- a/osfmk/vm/vm_fault_internal.h
++++ b/osfmk/vm/vm_fault_internal.h
+@@ -75,6 +75,13 @@ extern kern_return_t vm_fault_wire_resident_pages(
+ ppnum_t *physpage_p,
+ vm_map_lock_ctx_t ctx);
+
++extern kern_return_t vm_fault_el0_populate_wired_entry(
++ vm_map_t map,
++ vm_map_entry_t entry,
++ vm_prot_t prot,
++ vm_tag_t wire_tag,
++ vm_map_lock_ctx_t ctx);
++
+ kern_return_t
+ vm_fault_wire_object_pages(
+ vm_map_t map,
+@@ -146,6 +153,15 @@ extern kern_return_t vm_map_lookup_object_and_lock_entry(
+ vm_map_lock_ctx_t vml_ctx_for_vaddr,
+ bool try_lock_entry);
+
++extern bool vm_fault_el0_entry_va_skip_pte(
++ vm_map_t map,
++ vm_map_entry_t entry,
++ vm_map_offset_t va);
++
++extern bool vm_fault_el0_never_faults_entry_supported(
++ vm_map_entry_t entry,
++ vm_prot_t req_prot);
++
+ #endif /* MACH_KERNEL_PRIVATE */
- mrs x1, MPIDR_EL1
-diff --git a/osfmk/arm64/machine_routines.c b/osfmk/arm64/machine_routines.c
-index f456377..3fdc51c 100644
---- a/osfmk/arm64/machine_routines.c
-+++ b/osfmk/arm64/machine_routines.c
-@@ -27,6 +27,7 @@
- */
+ __END_DECLS
+diff --git a/osfmk/vm/vm_kern.c b/osfmk/vm/vm_kern.c
+index 4f2045c..0fb9bc3 100644
+--- a/osfmk/vm/vm_kern.c
++++ b/osfmk/vm/vm_kern.c
+@@ -65,6 +65,7 @@
- #include <arm64/machine_machdep.h>
+ #include <mach/kern_return.h>
+ #include <mach/vm_param.h>
+#include <linux64/linux64.h>
- #include <arm64/proc_reg.h>
- #include <arm/machine_cpu.h>
- #include <arm/cpu_internal.h>
-@@ -385,6 +386,7 @@ wfe_process_recommendation(void)
- void
- machine_idle(void)
- {
-+ linux64_count(LINUX64_CTR_MACHINE_IDLE); /* LINUX64: for the host's monitor */
- /* Interrupts are expected to be masked on entry or re-entry via
- * Idle_load_context()
+ #include <kern/assert.h>
+ #include <kern/thread.h>
+ #include <vm/vm_entry_lock_internal.h>
+@@ -869,6 +870,12 @@ kmem_alloc_guard_internal(
*/
-@@ -400,6 +402,13 @@ machine_idle(void)
- */
- Idle_context();
- }
-+ {
-+ /* LINUX64 (xnulinux): hosted, hardware IRQs stay masked; only the virtual flag changes. */
-+ if (linux64_hook) {
-+ LINUX64_VINT = 1;
-+ return;
+ assert((flags & (KMA_PAGEABLE | KMA_DATA)) != (KMA_PAGEABLE | KMA_DATA));
+ #endif /* defined(__arm64__) */
++ if (linux64_el0 && (flags & KMA_PAGEABLE) && !(flags & KMA_VAONLY)) {
++ flags &= ~KMA_PAGEABLE;
++ if (guard.kmg_tag == VM_KERN_MEMORY_NONE) {
++ guard.kmg_tag = VM_KERN_MEMORY_OSFMK;
+ }
+ }
- __builtin_arm_wsr("DAIFClr", DAIFSC_STANDARD_DISABLE);
- }
-@@ -441,6 +450,12 @@ ml_get_interrupts_enabled(void)
- {
- uint64_t value;
+ #if DEBUG || DEVELOPMENT
+ VM_DEBUG_CONSTANT_EVENT(vm_kern_request, DBG_VM_KERN_REQUEST, DBG_FUNC_START,
+@@ -1406,6 +1413,12 @@ mach_vm_allocate_kernel_sanitize(
+ return KERN_SUCCESS;
+ }
-+ {
-+ /* LINUX64: interrupts are virtual while hosted (see ml_set_interrupts_enabled_with_debug). */
-+ if (linux64_hook) {
-+ return LINUX64_VINT ? TRUE : FALSE;
++kern_return_t linux64_el0_prefault_kernel_map(
++ vm_map_t map,
++ mach_vm_offset_t addr,
++ mach_vm_size_t size,
++ vm_prot_t prot);
++
+ kern_return_t
+ mach_vm_allocate_kernel(
+ vm_map_t map,
+@@ -1467,6 +1480,13 @@ mach_vm_allocate_kernel(
+ VM_INHERIT_DEFAULT);
+
+ if (result == KERN_SUCCESS) {
++ if (linux64_el0 && map->pmap == kernel_pmap) {
++ result = linux64_el0_prefault_kernel_map(map, map_addr, map_size, VM_PROT_DEFAULT);
++ if (result != KERN_SUCCESS) {
++ (void)vm_map_remove(map, map_addr, map_addr + map_size);
++ return result;
++ }
+ }
+ #if KASAN
+ if (map->pmap == kernel_pmap) {
+ kasan_notify_address(map_addr, map_size);
+@@ -2478,6 +2498,42 @@ alloc_fail:
+
+ #pragma mark map/remap/wire
+
++extern kern_return_t vm_map_wire_el0_autowire(
++ vm_map_t map,
++ vm_map_offset_t start,
++ vm_map_offset_t end);
++
++bool
++linux64_el0_is_kernel_pmap(vm_map_t map)
++{
++ return map != VM_MAP_NULL && map->pmap == kernel_pmap;
++}
++
++kern_return_t
++linux64_el0_prefault_kernel_map(
++ vm_map_t map,
++ mach_vm_offset_t addr,
++ mach_vm_size_t size,
++ vm_prot_t prot)
++{
++ if (!linux64_el0 || map == VM_MAP_NULL || map->pmap != kernel_pmap) {
++ return KERN_SUCCESS;
+ }
- MRS(value, "DAIF");
- if ((value & DAIF_STANDARD_DISABLE) == DAIF_STANDARD_DISABLE) {
- return FALSE;
-@@ -934,6 +949,13 @@ halt_all_cpus(boolean_t reboot)
- printf("CPU halted\n");
- PEHaltRestart(kPEHaltCPU);
- }
-+ if (linux64_hook) {
-+ /*
-+ * LINUX64 (xnulinux): hosted, spinning here keeps this Linux CPU with its interrupts masked for good (Linux
-+ * soft-locks). The host ends the run instead and says whether the system asked for a restart.
-+ */
-+ linux64_call2(LINUX64_CALL_HALT, reboot ? 1 : 0, 0);
++ if (!(prot & (VM_PROT_READ | VM_PROT_WRITE | VM_PROT_ALLEXEC)) || size == 0) {
++ return KERN_SUCCESS;
+ }
- while (1) {
- ;
- }
-@@ -1367,7 +1389,9 @@ ml_parse_cpu_topology(void)
- assert(((tpidr_el0 & MACHDEP_TPIDR_CLUSTERID_MASK) >> MACHDEP_TPIDR_CLUSTERID_SHIFT) == boot_cpu->cluster_id);
- __builtin_arm_wsr64("TPIDR_EL0", tpidr_el0);
-
-- __builtin_arm_wsr64("TPIDRRO_EL0", 0);
-+ if (!linux64_hook) { /* LINUX64: hosted, TPIDRRO_EL0 already holds the kernel's thread pointer */
-+ __builtin_arm_wsr64("TPIDRRO_EL0", 0);
++ mach_vm_offset_t raw_end;
++ if (os_add_overflow(addr, size, &raw_end)) {
++ return KERN_INVALID_ARGUMENT;
++ }
++ vm_map_offset_t start = vm_map_trunc_page(addr, VM_MAP_PAGE_MASK(map));
++ vm_map_offset_t end = vm_map_round_page(raw_end, VM_MAP_PAGE_MASK(map));
++ if (end <= start) {
++ return KERN_INVALID_ARGUMENT;
++ }
++ return vm_map_wire_el0_autowire(map, start, end);
++}
++
+ kern_return_t
+ mach_vm_map_kernel(
+ vm_map_t target_map,
+@@ -2493,7 +2549,7 @@ mach_vm_map_kernel(
+ vm_inherit_ut inheritance)
+ {
+ /* range_id is set by vm_map_enter_mem_object */
+- return vm_map_enter_mem_object(target_map,
++ kern_return_t kr = vm_map_enter_mem_object(target_map,
+ address,
+ initial_size,
+ mask,
+@@ -2506,6 +2562,19 @@ mach_vm_map_kernel(
+ inheritance,
+ NULL,
+ 0);
++ if (kr == KERN_SUCCESS && linux64_el0 && target_map->pmap == kernel_pmap &&
++ !vmk_flags.vmf_overwrite) {
++ mach_vm_offset_t map_addr = VM_SANITIZE_UNSAFE_UNWRAP(*address);
++ mach_vm_size_t map_size = VM_SANITIZE_UNSAFE_UNWRAP(initial_size);
++ kr = linux64_el0_prefault_kernel_map(target_map, map_addr, map_size,
++ VM_SANITIZE_UNSAFE_UNWRAP(cur_protection));
++ if (kr != KERN_SUCCESS) {
++ (void)vm_map_remove(target_map,
++ vm_map_trunc_page(map_addr, VM_MAP_PAGE_MASK(target_map)),
++ vm_map_round_page(map_addr + map_size, VM_MAP_PAGE_MASK(target_map)));
++ }
+ }
++ return kr;
}
- const ml_topology_info_t *
-@@ -2529,6 +2553,12 @@ ml_set_decrementer(uint32_t dec_value)
- }
- }
-
-+ {
-+ /* LINUX64 (xnulinux): the generic timer is Linux's; cpu_idle hands the deadline to the host. */
-+ if (linux64_hook) {
-+ return;
+ kern_return_t
+@@ -2531,7 +2600,7 @@ mach_vm_remap_new_kernel(
+ vmk_flags.vmf_return_data_addr = true;
+
+ /* range_id is set by vm_map_remap */
+- return vm_map_remap(target_map,
++ kern_return_t kr = vm_map_remap(target_map,
+ address,
+ size,
+ mask,
+@@ -2542,6 +2611,19 @@ mach_vm_remap_new_kernel(
+ cur_protection,
+ max_protection,
+ inheritance);
++ if (kr == KERN_SUCCESS && cur_protection != NULL &&
++ linux64_el0 && target_map->pmap == kernel_pmap) {
++ mach_vm_offset_t map_addr = VM_SANITIZE_UNSAFE_UNWRAP(*address);
++ mach_vm_size_t map_size = VM_SANITIZE_UNSAFE_UNWRAP(size);
++ kr = linux64_el0_prefault_kernel_map(target_map, map_addr, map_size,
++ VM_SANITIZE_UNSAFE_UNWRAP(*cur_protection));
++ if (kr != KERN_SUCCESS) {
++ (void)vm_map_remove(target_map,
++ vm_map_trunc_page(map_addr, VM_MAP_PAGE_MASK(target_map)),
++ vm_map_round_page(map_addr + map_size, VM_MAP_PAGE_MASK(target_map)));
+ }
+ }
- if (cdp->cpu_set_decrementer_func) {
- cdp->cpu_set_decrementer_func((uint32_t)counter_value);
- } else {
-diff --git a/osfmk/arm64/machine_routines_asm.s b/osfmk/arm64/machine_routines_asm.s
-index 96650a0..445ce31 100644
---- a/osfmk/arm64/machine_routines_asm.s
-+++ b/osfmk/arm64/machine_routines_asm.s
-@@ -95,7 +95,7 @@ Lcre_start_\@:
-
-
- .macro LOAD_CPU_JOP_KEY dst, tmp
-- mrs \tmp, TPIDR_EL1
-+ mrs \tmp, TPIDRRO_EL0
- ldr \tmp, [\tmp, ACT_CPUDATAP]
- ldr \dst, [\tmp, CPU_JOP_KEY]
- .endmacro
-@@ -1748,6 +1748,11 @@ LEXT(arm64_force_wfi_clock_gate)
- LEXT(arm64_replace_bootstack)
- ARM64_STACK_PROLOG
- PUSH_FRAME
-+ // LINUX64 (xnulinux): hosted, SP_EL1 is Linux's kernel stack and SP_EL0 is Linux's `current`;
-+ // XNU must not touch either. Its exception stacks are unused while hosted.
-+ adrp x9, _linux64_hook@PAGE
-+ ldr x9, [x9, _linux64_hook@PAGEOFF]
-+ cbnz x9, Lreplace_bootstack_hosted
- // Set the exception stack pointer
- ldr x0, [x0, CPU_EXCEPSTACK_TOP]
- mrs x4, DAIF // Load current DAIF; use x4 as pinst may trash x1-x3
-@@ -1763,6 +1768,7 @@ LEXT(arm64_replace_bootstack)
- mov sp, x0
- msr SPSel, #0
- msr DAIF, x4 // Restore interrupt state
-+Lreplace_bootstack_hosted:
- POP_FRAME
- ARM64_STACK_EPILOG EXT(arm64_replace_bootstack)
++ return kr;
+ }
-diff --git a/osfmk/arm64/pac_asm.h b/osfmk/arm64/pac_asm.h
-index d211433..cb48971 100644
---- a/osfmk/arm64/pac_asm.h
-+++ b/osfmk/arm64/pac_asm.h
-@@ -216,7 +216,7 @@
- * Expects interrupts to be disabled.
- */
- .macro PACGA_IRG_RESEED x, y, z
-- mrs \x, TPIDR_EL1
-+ mrs \x, TPIDRRO_EL0
- ldr \x, [\x, ACT_CPUDATAP]
+ #pragma mark free
+@@ -3093,7 +3175,12 @@ kmem_add_extra_claims(struct mach_vm_range km_range)
+ * This is a useful assert as it should catch us if we were to end up
+ * with a "negative" (or extremely large) data_range_size.
+ */
+- assert(ptr_total_allocation_size < free_size);
++ if (ptr_total_allocation_size >= free_size) {
++ panic("kmem_add_extra_claims: insufficient kernel VA space "
++ "(ptr_total=%#llx >= free=%#llx)",
++ (unsigned long long)ptr_total_allocation_size,
++ (unsigned long long)free_size);
++ }
- // 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..3fac7b4 100644
---- a/osfmk/arm64/sleh.c
-+++ b/osfmk/arm64/sleh.c
-@@ -1,4 +1,5 @@
- #include <kern/boot_progress.h>
+ /*
+ * Finally, give any remaining allocable space to the data region.
+diff --git a/osfmk/vm/vm_map.c b/osfmk/vm/vm_map.c
+index fd9e108..8edd104 100644
+--- a/osfmk/vm/vm_map.c
++++ b/osfmk/vm/vm_map.c
+@@ -74,6 +74,7 @@
+ #include <mach/port.h>
+ #include <mach/vm_attributes.h>
+ #include <mach/vm_param.h>
+#include <linux64/linux64.h>
- /*
- * Copyright (c) 2012-2023 Apple Inc. All rights reserved.
- *
-@@ -78,6 +79,7 @@
- #if CONFIG_TELEMETRY
- #include <kern/telemetry.h>
- #include <kern/trap_telemetry.h>
-+#include <kern/recount.h>
- #endif
+ #include <mach/vm_behavior.h>
+ #include <mach/vm_statistics.h>
+ #include <mach/memory_object.h>
+@@ -103,6 +104,11 @@
+ #include <vm/vm_pageout.h>
+ #include <vm/pmap.h>
+ #include <vm/vm_kern_internal.h>
++extern kern_return_t linux64_el0_prefault_kernel_map(
++ vm_map_t map,
++ mach_vm_offset_t addr,
++ mach_vm_size_t size,
++ vm_prot_t prot);
+ #include <ipc/ipc_port.h>
+ #include <kern/sched_prim.h>
+ #include <kern/misc_protos.h>
+@@ -923,6 +929,7 @@ vm_map_entry_reinit_after_copy(vm_map_t map, vm_map_entry_t entry)
+ entry->is_shared = false;
+ entry->wired_count = 0;
+ entry->user_wired_count = 0;
++ entry->vme_el0_autowire = 0;
+ entry->vme_permanent = false;
+ vm_map_entry_reinit_code_signing_after_copy(map, entry);
+ vm_map_entry_reinit_csm_assoc_after_copy(map, entry);
+@@ -946,13 +953,368 @@ vm_map_entry_reinit_after_copy(vm_map_t map, vm_map_entry_t entry)
+ * something goes wrong. In that case, the zap list is iterated and the entries
+ * reinserted into the map (see vm_map_enter).
+ */
++struct el0_zap_saved {
++ struct el0_zap_saved *next;
++ vm_map_entry_t entry;
++ vm_map_t map;
++ bool had_autowire;
++ bool had_iokit_acct;
++ bool had_use_pmap;
++ bool deferred_page_unwire;
++ bool restored;
++ bool has_saved_ptes;
++ uint64_t npages;
++ uint64_t *saved_ptes;
++ size_t ptes_bytes;
++ vm_page_t *pinned_pages;
++ vm_object_t *pinned_objs;
++ size_t pinned_count;
++};
++
+ typedef struct vm_map_zap {
+ vm_map_entry_t vmz_head;
+ vm_map_entry_t *vmz_tail;
++ struct el0_zap_saved *el0_saved_head;
++ struct el0_zap_saved **el0_saved_tail;
++ uint64_t el0_kmap_txn;
+ } *vm_map_zap_t;
+
+ #define VM_MAP_ZAP_DECLARE(zap) \
+- struct vm_map_zap zap = { .vmz_tail = &zap.vmz_head }
++ struct vm_map_zap zap = { .vmz_tail = &zap.vmz_head, .el0_saved_tail = &zap.el0_saved_head }
++
++static void vm_map_entry_unlink_and_extend_sentinel(
++ vm_map_t map, vm_map_entry_t entry, vm_map_entry_t sentinel_or_null);
++static bool el0_entry_unpopulated_device_pager(vm_map_entry_t entry);
++static bool el0_entry_missing_pte(vm_map_t map, vm_map_entry_t entry, vm_prot_t req_prot);
++static kern_return_t vm_map_preflight_wire_space(
++ vm_map_t map, vm_map_entry_t entry, bool user_wire,
++ vm_map_size_t *const size_that_would_be_wired);
++static kern_return_t vm_map_wire_count_add(
++ vm_map_t map, vm_map_entry_t entry, bool user_wire);
++static bool vm_map_wire_count_sub(
++ vm_map_t map, vm_map_entry_t entry, bool user_wire);
++
++static void
++el0_zap_unpin_page(vm_page_t m, vm_object_t orig_obj)
++{
++ for (;;) {
++ vm_page_lock_queues();
++ vm_object_t cur_obj = VM_PAGE_OBJECT(m);
++ if (cur_obj == VM_OBJECT_NULL) {
++ vm_page_unlock_queues();
++ mutex_pause(0);
++ continue;
++ }
++ if (!vm_object_lock_try_scan(cur_obj)) {
++ vm_page_unlock_queues();
++ mutex_pause(0);
++ continue;
++ }
++ if (VM_PAGE_OBJECT(m) != cur_obj) {
++ vm_object_unlock(cur_obj);
++ vm_page_unlock_queues();
++ continue;
++ }
++ vm_page_unwire(m, TRUE);
++ vm_page_unlock_queues();
++ vm_object_unlock(cur_obj);
++ break;
++ }
++ vm_object_deallocate(orig_obj);
++}
++
++static void
++el0_zap_unpin_saved(struct el0_zap_saved *s)
++{
++ if (s->pinned_pages == NULL || s->pinned_objs == NULL || s->pinned_count == 0) {
++ return;
++ }
++ for (size_t i = 0; i < s->pinned_count; i++) {
++ vm_page_t m = s->pinned_pages[i];
++ vm_object_t po = s->pinned_objs[i];
++ if (m != VM_PAGE_NULL && po != VM_OBJECT_NULL) {
++ s->pinned_pages[i] = VM_PAGE_NULL;
++ s->pinned_objs[i] = VM_OBJECT_NULL;
++ el0_zap_unpin_page(m, po);
++ }
++ }
++}
++
++static kern_return_t
++el0_zap_save_entry(vm_map_zap_t zap, vm_map_t map, vm_map_entry_t entry)
++{
++ struct el0_zap_saved *s = kalloc_type(struct el0_zap_saved, Z_WAITOK | Z_ZERO);
++ if (s == NULL) {
++ return KERN_RESOURCE_SHORTAGE;
++ }
++ s->entry = entry;
++ s->map = map;
++ s->had_autowire = (entry->vme_el0_autowire != 0);
++ s->had_iokit_acct = (entry->iokit_acct != 0);
++ s->had_use_pmap = (entry->use_pmap != 0);
++
++ vm_object_t entry_obj = entry->is_sub_map ? VM_OBJECT_NULL : VME_OBJECT(entry);
++ if (!entry->is_sub_map && !entry->vme_kernel_object && entry_obj != compressor_object) {
++ vm_map_size_t eff_pgsz = MIN(VM_MAP_PAGE_SIZE(map), PAGE_SIZE);
++ uint64_t npages = (entry->vme_end - entry->vme_start) / eff_pgsz;
++ if (npages > 0) {
++ size_t ptes_bytes = 0;
++ if (npages > SIZE_MAX || os_mul_overflow(npages, sizeof(uint64_t), &ptes_bytes)) {
++ kfree_type(struct el0_zap_saved, s);
++ return KERN_RESOURCE_SHORTAGE;
++ }
++ uint64_t *ptes = kalloc_data(ptes_bytes, Z_WAITOK | Z_ZERO);
++ if (ptes == NULL) {
++ kfree_type(struct el0_zap_saved, s);
++ return KERN_RESOURCE_SHORTAGE;
++ }
++ bool need_pin = (!s->had_autowire &&
++ entry_obj != VM_OBJECT_NULL && !entry_obj->phys_contiguous);
++ vm_page_t *pinned_pages = NULL;
++ vm_object_t *pinned_objs = NULL;
++ size_t pinned_count = 0;
++ if (need_pin) {
++ pinned_count = (size_t)npages;
++ pinned_pages = kalloc_type(vm_page_t, pinned_count, Z_WAITOK | Z_ZERO);
++ pinned_objs = kalloc_type(vm_object_t, pinned_count, Z_WAITOK | Z_ZERO);
++ if (pinned_pages == NULL || pinned_objs == NULL) {
++ if (pinned_pages != NULL) {
++ kfree_type(vm_page_t, pinned_count, pinned_pages);
++ }
++ if (pinned_objs != NULL) {
++ kfree_type(vm_object_t, pinned_count, pinned_objs);
++ }
++ kfree_data(ptes, ptes_bytes);
++ kfree_type(struct el0_zap_saved, s);
++ return KERN_RESOURCE_SHORTAGE;
++ }
++ }
++ s->npages = npages;
++ s->saved_ptes = ptes;
++ s->ptes_bytes = ptes_bytes;
++ s->pinned_pages = pinned_pages;
++ s->pinned_objs = pinned_objs;
++ s->pinned_count = pinned_count;
++
++ kern_return_t fail_kr = KERN_SUCCESS;
++ for (uint64_t i = 0; i < npages && fail_kr == KERN_SUCCESS; i++) {
++ vm_map_offset_t va = entry->vme_start + ((vm_map_offset_t)i * eff_pgsz);
++ bool page_done = false;
++
++ for (int attempt = 0; attempt < 3 && !page_done && fail_kr == KERN_SUCCESS; attempt++) {
++ uint64_t pte = 0;
++ pmap_paddr_t pa = 0;
++ bool pa_ok = false;
++
++ if (!pmap_el0_read_pte_snapshot(map->pmap, va, &pte, &pa, &pa_ok)) {
++ ptes[i] = 0;
++ page_done = true;
++ break;
++ }
++ if (!pmap_el0_pte_restorable(map->pmap, pte)) {
++ fail_kr = KERN_PROTECTION_FAILURE;
++ break;
++ }
++ if (!pa_ok || s->had_autowire ||
++ (entry_obj != VM_OBJECT_NULL && entry_obj->phys_contiguous)) {
++ ptes[i] = pte;
++ s->has_saved_ptes = true;
++ page_done = true;
++ break;
++ }
++ if (entry_obj == VM_OBJECT_NULL) {
++ fail_kr = KERN_NOT_SUPPORTED;
++ break;
++ }
++
++ ppnum_t target_pn = atop(pa);
++ vm_object_offset_t cur_off = VME_OFFSET(entry) + ((vm_object_offset_t)i * eff_pgsz);
++ vm_object_t cur_obj = entry_obj;
++ vm_page_t pinned_m = VM_PAGE_NULL;
++ vm_object_t pinned_o = VM_OBJECT_NULL;
++ bool page_pinned_or_private = false;
++
++ vm_object_lock(cur_obj);
++ while (cur_obj != VM_OBJECT_NULL) {
++ vm_page_t m = vm_page_lookup(cur_obj, cur_off);
++ if (m != VM_PAGE_NULL) {
++ if (VM_PAGE_GET_PHYS_PAGE(m) == target_pn) {
++ if (vm_page_is_private(m)) {
++ page_pinned_or_private = true;
++ } else if (!vm_page_is_fictitious(m) &&
++ !m->vmp_gobbled &&
++ !m->vmp_absent &&
++ !m->vmp_error) {
++ if (m->vmp_wire_count >= MAX_WIRE_COUNT) {
++ fail_kr = KERN_RESOURCE_SHORTAGE;
++ } else {
++ vm_page_lock_queues();
++ vm_page_wire(m, VM_KERN_MEMORY_OSFMK, FALSE);
++ vm_page_unlock_queues();
++ vm_object_reference_locked(cur_obj);
++ pinned_m = m;
++ pinned_o = cur_obj;
++ page_pinned_or_private = true;
++ }
++ }
++ }
++ vm_object_unlock(cur_obj);
++ break;
++ }
++ vm_object_t next_shadow = cur_obj->shadow;
++ if (next_shadow == VM_OBJECT_NULL ||
++ os_add_overflow(cur_off, cur_obj->vo_shadow_offset, &cur_off)) {
++ vm_object_unlock(cur_obj);
++ break;
++ }
++ vm_object_lock(next_shadow);
++ vm_object_unlock(cur_obj);
++ cur_obj = next_shadow;
++ }
++ if (fail_kr != KERN_SUCCESS) {
++ break;
++ }
++
++ uint64_t re_pte = 0;
++ pmap_paddr_t re_pa = 0;
++ bool re_ok = false;
++ bool re_valid = pmap_el0_read_pte_snapshot(map->pmap, va, &re_pte, &re_pa, &re_ok);
++ if (!re_valid) {
++ if (pinned_m != VM_PAGE_NULL) {
++ el0_zap_unpin_page(pinned_m, pinned_o);
++ }
++ ptes[i] = 0;
++ page_done = true;
++ break;
++ }
++ if (page_pinned_or_private && re_ok && re_pa == pa &&
++ pmap_el0_pte_restorable(map->pmap, re_pte)) {
++ if (pinned_m != VM_PAGE_NULL) {
++ pinned_pages[i] = pinned_m;
++ pinned_objs[i] = pinned_o;
++ }
++ ptes[i] = re_pte;
++ s->has_saved_ptes = true;
++ page_done = true;
++ break;
++ }
++ if (pinned_m != VM_PAGE_NULL) {
++ el0_zap_unpin_page(pinned_m, pinned_o);
++ }
++ }
++ if (fail_kr == KERN_SUCCESS && !page_done) {
++ fail_kr = KERN_ABORTED;
++ }
++ }
++ if (fail_kr != KERN_SUCCESS) {
++ el0_zap_unpin_saved(s);
++ if (s->pinned_pages != NULL) {
++ kfree_type(vm_page_t, s->pinned_count, s->pinned_pages);
++ }
++ if (s->pinned_objs != NULL) {
++ kfree_type(vm_object_t, s->pinned_count, s->pinned_objs);
++ }
++ kfree_data(s->saved_ptes, s->ptes_bytes);
++ kfree_type(struct el0_zap_saved, s);
++ return fail_kr;
++ }
++ if (!s->has_saved_ptes) {
++ el0_zap_unpin_saved(s);
++ if (s->pinned_pages != NULL) {
++ kfree_type(vm_page_t, s->pinned_count, s->pinned_pages);
++ s->pinned_pages = NULL;
++ }
++ if (s->pinned_objs != NULL) {
++ kfree_type(vm_object_t, s->pinned_count, s->pinned_objs);
++ s->pinned_objs = NULL;
++ }
++ s->pinned_count = 0;
++ kfree_data(s->saved_ptes, s->ptes_bytes);
++ s->saved_ptes = NULL;
++ s->ptes_bytes = 0;
++ s->npages = 0;
++ }
++ }
++ }
++ s->next = NULL;
++ *zap->el0_saved_tail = s;
++ zap->el0_saved_tail = &s->next;
++ return KERN_SUCCESS;
++}
++
++static void
++el0_zap_free_saved(vm_map_zap_t zap)
++{
++ while (zap->el0_saved_head != NULL) {
++ struct el0_zap_saved *s = zap->el0_saved_head;
++ zap->el0_saved_head = s->next;
++ el0_zap_unpin_saved(s);
++ if (s->pinned_pages != NULL) {
++ kfree_type(vm_page_t, s->pinned_count, s->pinned_pages);
++ }
++ if (s->pinned_objs != NULL) {
++ kfree_type(vm_object_t, s->pinned_count, s->pinned_objs);
++ }
++ if (s->saved_ptes != NULL) {
++ kfree_data(s->saved_ptes, s->ptes_bytes);
++ }
++ kfree_type(struct el0_zap_saved, s);
++ }
++ zap->el0_saved_tail = &zap->el0_saved_head;
++}
++
++static bool
++el0_object_range_supported(
++ vm_object_t object,
++ vm_object_offset_t offset,
++ vm_map_size_t size,
++ vm_map_offset_t va,
++ bool allow_obj_wimg_override,
++ bool allow_device_pager_wimg)
++{
++ if (object == VM_OBJECT_NULL || size == 0 ||
++ is_kernel_object(object) || object == compressor_object) {
++ return true;
++ }
++ vm_object_lock_shared(object);
++ bool is_device_pager = (object->pager != MEMORY_OBJECT_NULL &&
++ is_device_pager_ops(object->pager->mo_pager_ops));
++ bool wimg_ok = allow_obj_wimg_override || pmap_el0_wimg_supported(object->wimg_bits) ||
++ (allow_device_pager_wimg && is_device_pager);
++ if (!wimg_ok) {
++ vm_object_unlock(object);
++ return false;
++ }
++ bool ok = true;
++ if (object->phys_contiguous) {
++ if (!(object->private && object->pager_created && !object->vo_el0_populated)) {
++ vm_map_offset_t pa_base;
++ if (os_add_overflow((vm_map_offset_t)object->vo_shadow_offset,
++ offset, &pa_base) ||
++ !pmap_el0_kmap_range_supported(va, (pmap_paddr_t)pa_base, size)) {
++ ok = false;
++ }
++ }
++ } else if (object->private) {
++ for (vm_map_size_t off = 0; off < size; off += PAGE_SIZE) {
++ vm_object_offset_t page_off;
++ if (os_add_overflow(offset, object->paging_offset, &page_off) ||
++ os_add_overflow(page_off, off, &page_off)) {
++ ok = false;
++ break;
++ }
++ vm_page_t m = vm_page_lookup(object, page_off);
++ if (m != VM_PAGE_NULL &&
++ !pmap_el0_kmap_range_supported(va + off,
++ (pmap_paddr_t)ptoa_64(VM_PAGE_GET_PHYS_PAGE(m)), PAGE_SIZE)) {
++ ok = false;
++ break;
++ }
++ }
++ }
++ vm_object_unlock(object);
++ return ok;
++}
- #include <prng/entropy.h>
-@@ -3646,3 +3648,274 @@ sleh_panic_lockdown_should_initiate_el1_sp0_sync(uint64_t esr, uint64_t elr,
- }
- __SECURITY_STACK_DISALLOWED_POP
- #endif /* CONFIG_SPTM */
+ static vm_map_entry_t
+ vm_map_zap_first_entry(vm_map_zap_t list)
+@@ -996,6 +1358,23 @@ vm_map_zap_dispose(vm_map_t map __unused, vm_map_zap_t list)
+ {
+ vm_map_entry_t entry;
+
++ for (struct el0_zap_saved *s = list->el0_saved_head; s != NULL; s = s->next) {
++ if (s->deferred_page_unwire && !s->restored) {
++ vm_map_entry_t se = s->entry;
++ if (!se->is_sub_map && VME_OBJECT(se) != VM_OBJECT_NULL &&
++ !VME_OBJECT(se)->phys_contiguous) {
++ vm_fault_unwire_object_pages(s->map, VME_OBJECT(se),
++ VME_OFFSET(se), se->vme_end - se->vme_start);
++ }
++ s->deferred_page_unwire = false;
++ }
++ }
++ el0_zap_free_saved(list);
++ if (list->el0_kmap_txn != 0) {
++ pmap_el0_kmap_txn_end(list->el0_kmap_txn);
++ list->el0_kmap_txn = 0;
++ }
++
+ while ((entry = vm_map_zap_pop(list))) {
+ /*
+ * RANGELOCKINGTODO:
+@@ -3026,6 +3405,89 @@ uint64_t vm_map_enter_RLIMIT_DATA_count = 0;
+ */
+ __static_testable unsigned int vm_map_enter_restore_successes = 0;
+ __static_testable unsigned int vm_map_enter_restore_failures = 0;
+
-+/*
-+ * LINUX64 (xnulinux): a data or instruction abort on an XNU kernel address, taken in Linux's vectors and forwarded by
-+ * the host (xnu.ko through FKI). Does what handle_kernel_abort does for a kernel-map fault: the pmap fast path for
-+ * permission/access-flag faults, then vm_fault. Returns KERN_SUCCESS when the access can be retried.
-+ */
-+kern_return_t linux64_kernel_fault(uint64_t far, uint64_t esr);
-+kern_return_t
-+linux64_kernel_fault(uint64_t far, uint64_t esr)
++static void
++vm_map_el0_restore_zapped_entries(
++ vm_map_t map,
++ vm_map_zap_t zap_old_list,
++ bool *map_ilocked_p)
+{
-+ uint32_t ec = (uint32_t)((esr >> 26) & 0x3f);
-+ fault_status_t fault_code = (fault_status_t)(esr & 0x3f);
-+ vm_prot_t fault_type = VM_PROT_READ;
-+ kern_return_t result = KERN_FAILURE;
++ vm_map_entry_t entry;
++ struct el0_zap_saved *cur = zap_old_list->el0_saved_head;
+
-+ if (ec == 0x21) { /* instruction abort, current EL */
-+ fault_type = VM_PROT_READ | VM_PROT_EXECUTE;
-+ } else if (ec == 0x25) { /* data abort, current EL */
-+ if (esr & (1u << 6)) { /* WnR */
-+ fault_type = VM_PROT_READ | VM_PROT_WRITE;
++ assert(*map_ilocked_p);
++ while ((entry = vm_map_zap_pop(zap_old_list))) {
++ assert(!VME_IS_SENTINEL(entry));
++ vm_map_store_insert(map, entry);
++ if (cur != NULL && cur->entry == entry) {
++ if (cur->had_iokit_acct) {
++ entry->iokit_acct = TRUE;
++ entry->use_pmap = FALSE;
++ DTRACE_VM4(vm_map_iokit_mapped_region,
++ vm_map_t, map,
++ vm_map_offset_t, entry->vme_start,
++ vm_map_offset_t, entry->vme_end,
++ int, VME_ALIAS(entry));
++ vm_map_iokit_mapped_region(map,
++ entry->vme_end - entry->vme_start);
++ } else {
++ entry->use_pmap = cur->had_use_pmap;
++ }
++ cur->restored = true;
++ cur = cur->next;
++ } else {
++ vm_entry_unlock_exclusive(map, entry);
+ }
-+ } else {
-+ return KERN_FAILURE;
+ }
-+ if (!is_vm_fault(fault_code)) {
-+ return KERN_FAILURE;
++ vm_map_ilk_unlock(map);
++ *map_ilocked_p = false;
++
++ if (zap_old_list->el0_kmap_txn != 0) {
++ pmap_el0_kmap_txn_begin_restore(zap_old_list->el0_kmap_txn);
+ }
-+ /* a kernel address faults on the kernel map; a user one (copyio) on the current thread's map */
-+ vm_map_t map = kernel_map;
-+ if (!VM_KERNEL_ADDRESS(far)) {
-+ thread_t thread = current_thread();
-+ if (thread == THREAD_NULL || thread->map == VM_MAP_NULL || thread->map == kernel_map) {
-+ return KERN_FAILURE;
++
++ vm_map_size_t eff_pgsz = MIN(VM_MAP_PAGE_SIZE(map), PAGE_SIZE);
++ for (struct el0_zap_saved *s = zap_old_list->el0_saved_head; s != NULL; s = s->next) {
++ if (!s->restored) {
++ continue;
+ }
-+ map = thread->map;
++ vm_map_entry_t old_e = s->entry;
++ if (s->had_autowire) {
++ kern_return_t wkr = vm_map_wire_count_add(map, old_e, FALSE);
++ assert(wkr == KERN_SUCCESS);
++ s->deferred_page_unwire = false;
++ }
++ if (s->saved_ptes != NULL && s->npages > 0) {
++ for (uint64_t i = 0; i < s->npages; i++) {
++ if (s->saved_ptes[i] != 0) {
++ vm_map_offset_t va = old_e->vme_start + ((vm_map_offset_t)i * eff_pgsz);
++ kern_return_t rkr = pmap_el0_restore_pte_snapshot(map->pmap, va, s->saved_ptes[i]);
++ if (rkr != KERN_SUCCESS) {
++ panic("vm_map_el0_restore_zapped_entries: unrecoverable host restore failure va=0x%llx kr=%d",
++ (unsigned long long)va, rkr);
++ }
++ }
++ }
++ }
++ if (s->had_autowire) {
++ old_e->vme_el0_autowire = 1;
++ }
++ el0_zap_unpin_saved(s);
+ }
-+ kern_return_t ffr = KERN_FAILURE;
-+ if (!is_translation_fault(fault_code)) {
-+ ffr = arm_fast_fault(map->pmap, far, fault_type, (fault_code == FSC_ACCESS_FLAG_FAULT_L3), FALSE);
++ vm_map_enter_restore_successes++;
++ if (zap_old_list->el0_kmap_txn != 0) {
++ pmap_el0_kmap_txn_end(zap_old_list->el0_kmap_txn);
++ zap_old_list->el0_kmap_txn = 0;
+ }
-+ kern_return_t kr = ffr == KERN_SUCCESS ? KERN_SUCCESS :
-+ vm_fault(map, far, fault_type, FALSE, VM_KERN_MEMORY_NONE, THREAD_UNINT, NULL, 0);
-+ if (ffr == KERN_SUCCESS) {
-+ return KERN_SUCCESS;
++ for (struct el0_zap_saved *s = zap_old_list->el0_saved_head; s != NULL; s = s->next) {
++ if (s->restored) {
++ vm_entry_unlock_exclusive(map, s->entry);
++ }
+ }
-+ return kr;
+}
++static kern_return_t el0_object_prewire_pin(vm_object_t obj);
++static void el0_object_prewire_unpin(vm_object_t obj);
+
-+/*
-+ * LINUX64 (xnulinux): a kernel fault vm_fault could not resolve, taken inside a copyin/copyout routine: the pc its
-+ * copyio recovery entry returns through (the routine then returns an error; x0 = EFAULT), 0 when pc has none.
-+ */
-+uint64_t linux64_kernel_fault_recover(uint64_t pc, uint64_t far, uint64_t esr);
-+uint64_t
-+linux64_kernel_fault_recover(uint64_t pc, uint64_t far, uint64_t esr)
-+{
-+ struct copyio_recovery_entry *e = find_copyio_recovery_entry(pc);
-+ thread_t thread = current_thread();
+ kern_return_t
+ vm_map_enter(
+ vm_map_t map,
+@@ -3049,6 +3511,8 @@ vm_map_enter(
+ kern_return_t result = KERN_SUCCESS;
+ bool map_ilocked = false;
+ bool map_lock_dropped = false;
++ bool el0_keep_new_locked = false;
++ vm_map_entry_t el0_new_entry = VM_MAP_ENTRY_NULL;
+ bool pmap_empty = TRUE;
+ bool new_mapping_established = FALSE;
+ const bool keep_map_ilocked = vmk_flags.vmkf_keep_map_ilocked;
+@@ -3456,6 +3920,23 @@ fail_enter_mte_memory_request:
+ proceed_with_enter_mte_memory_request:
+ #endif /* HAS_MTE */
+
++ if (linux64_el0 && map->pmap == kernel_pmap && size != 0 &&
++ (cur_protection & VM_PROT_ALLEXEC)) {
++ RETURN(KERN_NOT_SUPPORTED);
++ }
+
-+ if (e == NULL) {
-+ return 0;
++ el0_keep_new_locked = linux64_el0 && map->pmap == kernel_pmap &&
++ !is_submap && !map->never_faults &&
++ !is_kernel_object(object) && object != compressor_object &&
++ vmk_flags.vmf_overwrite && !keep_entries_locked && !keep_map_ilocked &&
++ (cur_protection & (VM_PROT_READ | VM_PROT_WRITE)) &&
++ !superpage_size && size != 0;
++
++ if (el0_keep_new_locked && !anywhere && object != VM_OBJECT_NULL &&
++ !el0_object_range_supported(object, offset, size, vmsr_start(rsv), false, false)) {
++ RETURN(KERN_NOT_SUPPORTED);
+ }
-+ if (thread != THREAD_NULL) {
-+ thread->machine.recover_esr = esr;
-+ thread->machine.recover_far = far;
++
+ if (anywhere) {
+ result = vm_map_locate_space_anywhere(map, vmsr_start(rsv),
+ size, mask, vmk_flags, &rsv);
+@@ -3584,7 +4065,7 @@ proceed_with_enter_mte_memory_request:
+ }
+ } else if (VM_MAP_PAGE_SHIFT(map) < PAGE_SHIFT) {
+ /* no coalescing if address space uses sub-pages */
+- } else if (keep_entries_locked) {
++ } else if (keep_entries_locked || el0_keep_new_locked) {
+ /* no coalescing if caller wants the entries returned still locked. */
+ } else if ((is_submap == FALSE) &&
+ (object == VM_OBJECT_NULL) &&
+@@ -3683,7 +4164,8 @@ proceed_with_enter_mte_memory_request:
+ object == VM_OBJECT_NULL &&
+ size > chunk_size &&
+ max_protection != VM_PROT_NONE &&
+- superpage_size == 0) {
++ superpage_size == 0 &&
++ !el0_keep_new_locked) {
+ tmp_end = tmp_start + chunk_size;
+ } else {
+ tmp_end = tmp2_end;
+@@ -3834,6 +4316,9 @@ proceed_with_enter_mte_memory_request:
+ #endif /* NO_NESTED_PMAP */
+ }
+ entry = new_entry;
++ if (el0_keep_new_locked) {
++ el0_new_entry = new_entry;
++ }
+
+ if (superpage_size) {
+ vm_page_t pages, m;
+@@ -3880,7 +4365,7 @@ proceed_with_enter_mte_memory_request:
+ * Unlock the new entry we created locked at
+ * vm_map_entry_create_locked_and_insert.
+ */
+- if (!keep_entries_locked) {
++ if (!keep_entries_locked && !el0_keep_new_locked) {
+ vm_entry_unlock_exclusive(map, entry);
+ }
+ } while (tmp_end != tmp2_end &&
+@@ -4056,13 +4541,109 @@ BailOut:
+ kr = vm_map_wire_kernel(map, vmsr_start(rsv), end,
+ cur_protection, VM_KERN_MEMORY_MLOCK, TRUE);
+ result = kr;
++ } else if (el0_keep_new_locked && el0_new_entry != VM_MAP_ENTRY_NULL &&
++ new_mapping_established) {
++ vm_map_ilk_unlock(map);
++ map_ilocked = false;
++ map_lock_dropped = true;
++ pmap_empty = FALSE;
++
++ if (!el0_entry_unpopulated_device_pager(el0_new_entry)) {
++ vm_map_size_t el0_wire_sz = 0;
++ bool obj_wired = false;
++ vm_prot_t res_prot = cur_protection & (VM_PROT_READ | VM_PROT_WRITE);
++ vm_tag_t wire_tag = (alias != VM_KERN_MEMORY_NONE) ?
++ alias : VM_KERN_MEMORY_OSFMK;
++ if (el0_new_entry->needs_copy) {
++ vm_map_entry_lock_resolve_symmetric_cow(map, el0_new_entry);
++ }
++ if (VME_OBJECT(el0_new_entry) == VM_OBJECT_NULL) {
++ vm_map_entry_lock_allocate_object(el0_new_entry, vm_map_maybe_serial_id(map));
++ }
++ struct vm_map_lock_ctx el0_ctx_val = {
++ .vmlc_req_start = el0_new_entry->vme_start,
++ .vmlc_req_end = el0_new_entry->vme_end,
++ .vmlc_map = map,
++ .vmlc_vme = el0_new_entry,
++ .__vmlc_flags = VMRL_EX_STREAM_NO_HOLES | VMRL_RESOLVE_COW_AND_OBJ | _VMRL_SINGLE_ENTRY,
++ .__vmlc_locked = true,
++ };
++ vm_object_t el0_obj = VME_OBJECT(el0_new_entry);
++ bool prewire_pinned = false;
++ if (!el0_obj->phys_contiguous) {
++ result = vm_map_preflight_wire_space(map, el0_new_entry, FALSE, &el0_wire_sz);
++ if (result == KERN_SUCCESS) {
++ result = el0_object_prewire_pin(el0_obj);
++ if (result == KERN_SUCCESS) {
++ prewire_pinned = true;
++ result = vm_fault_wire_object_pages(map, el0_obj,
++ VME_OFFSET(el0_new_entry),
++ el0_new_entry->vme_end - el0_new_entry->vme_start,
++ wire_tag, THREAD_UNINT);
++ if (result == KERN_SUCCESS) {
++ obj_wired = true;
++ }
++ }
++ }
++ }
++ if (result == KERN_SUCCESS) {
++ result = vm_map_wire_count_add(map, el0_new_entry, FALSE);
++ if (result == KERN_SUCCESS) {
++ result = vm_fault_wire_resident_pages(map, el0_new_entry,
++ res_prot, wire_tag, NULL, &el0_ctx_val);
++ if (result == KERN_SUCCESS) {
++ el0_new_entry->vme_el0_autowire = 1;
++ } else {
++ vm_map_wire_count_sub(map, el0_new_entry, FALSE);
++ obj_wired = false;
++ }
++ } else if (obj_wired) {
++ vm_fault_unwire_object_pages(map, el0_obj,
++ VME_OFFSET(el0_new_entry),
++ el0_new_entry->vme_end - el0_new_entry->vme_start);
++ obj_wired = false;
++ }
++ }
++ if (prewire_pinned) {
++ el0_object_prewire_unpin(el0_obj);
++ }
++ }
++ if (result == KERN_SUCCESS) {
++ if (zap_old_list.el0_kmap_txn != 0) {
++ pmap_el0_kmap_txn_end(zap_old_list.el0_kmap_txn);
++ zap_old_list.el0_kmap_txn = 0;
++ }
++ vm_entry_unlock_exclusive(map, el0_new_entry);
++ el0_new_entry = VM_MAP_ENTRY_NULL;
++ }
+ }
+ }
+
+ if (result != KERN_SUCCESS) {
+ if (new_mapping_established) {
++ if (el0_new_entry != VM_MAP_ENTRY_NULL) {
++ if (!map_ilocked) {
++ vm_map_ilk_lock(map);
++ map_ilocked = true;
++ }
++ pmap_remove(map->pmap, el0_new_entry->vme_start, el0_new_entry->vme_end);
++ if (el0_new_entry->iokit_acct) {
++ DTRACE_VM4(vm_map_iokit_unmapped_region,
++ vm_map_t, map,
++ vm_map_offset_t, el0_new_entry->vme_start,
++ vm_map_offset_t, el0_new_entry->vme_end,
++ int, VME_ALIAS(el0_new_entry));
++ vm_map_iokit_unmapped_region(map,
++ el0_new_entry->vme_end - el0_new_entry->vme_start);
++ el0_new_entry->iokit_acct = FALSE;
++ el0_new_entry->use_pmap = FALSE;
++ }
++ vm_map_entry_unlink_and_extend_sentinel(map, el0_new_entry, VM_MAP_ENTRY_NULL);
++ vm_map_zap_append(&zap_new_list, el0_new_entry);
++ el0_new_entry = VM_MAP_ENTRY_NULL;
++ } else {
+ kern_return_t remove_kr = KERN_SUCCESS;
+- vmr_flags_t remove_flags = VM_MAP_REMOVE_TO_OVERWRITE;
++ vmr_flags_t remove_flags = VM_MAP_REMOVE_TO_OVERWRITE | VM_MAP_REMOVE_EL0_DISCARD_NEW;
+ vm_map_entry_t sentinel = VM_MAP_ENTRY_NULL;
+
+ /*
+@@ -4108,10 +4689,12 @@ BailOut:
+ * the mapping above and now, so our delete should
+ * always succeed.
+ */
+- if (remove_kr != KERN_SUCCESS) {
++ if (map_lock_dropped == false && remove_kr != KERN_SUCCESS) {
+ panic("couldn't remove what we just made in %p", map);
+ }
+- assert(VM_MAP_ENTRY_NULL != sentinel);
++ if (map_lock_dropped == false) {
++ assert(VM_MAP_ENTRY_NULL != sentinel);
++ }
+ #else /* __x86_64__ || __BUILDING_XNU_LIB_UNITTEST__*/
+ /*
+ * on x86, we may drop the ilk for superpages so we can't
+@@ -4128,6 +4711,7 @@ BailOut:
+ vm_map_store_remove(map, sentinel,
+ VMS_REMOVE_FREE_ENTRY);
+ }
++ }
+ }
+
+ /*
+@@ -4159,12 +4743,16 @@ BailOut:
+ * Transfer the saved map entries from
+ * "zap_old_map" to the original "map".
+ */
+- while ((entry = vm_map_zap_pop(&zap_old_list))) {
+- assert(!VME_IS_SENTINEL(entry));
+- vm_map_store_insert(map, entry);
+- vm_entry_unlock_exclusive(map, entry);
++ if (linux64_el0 && map->pmap == kernel_pmap && zap_old_list.el0_saved_head != NULL) {
++ vm_map_el0_restore_zapped_entries(map, &zap_old_list, &map_ilocked);
++ } else {
++ while ((entry = vm_map_zap_pop(&zap_old_list))) {
++ assert(!VME_IS_SENTINEL(entry));
++ vm_map_store_insert(map, entry);
++ vm_entry_unlock_exclusive(map, entry);
++ }
++ vm_map_enter_restore_successes++;
+ }
+- vm_map_enter_restore_successes++;
+ } else {
+ /*
+ * Part of that range has already been
+@@ -4182,6 +4770,11 @@ BailOut:
+ * keep the interlocked held, unless we failed to enter its mapping, in
+ * which case we should consistently release the interlock before we return.
+ */
++ if (zap_old_list.el0_kmap_txn != 0) {
++ pmap_el0_kmap_txn_end(zap_old_list.el0_kmap_txn);
++ zap_old_list.el0_kmap_txn = 0;
+ }
-+ return (uint64_t)copyio_recover_table + (uint64_t)e->cre_recovery;
-+}
+
-+/*
-+ * LINUX64 (xnulinux): the first return of a new user thread (thread_bootstrap_return) while hosted. The pending ASTs
-+ * run as on the way to user space (for the first BSD thread: bsdinit_task, which execs launchd), and the thread enters
-+ * user space through linux64_el0_run (the host is told where user space starts the first time).
-+ */
-+void linux64_thread_bootstrap_return(void) __attribute__((noreturn));
-+/* boot-arg linux64_trace=1 logs every EL0 exception, and system calls with their paths and results */
-+static int linux64_trace_level = -1;
-+static inline int
-+linux64_tracing(void)
+ if (map_ilocked && (!keep_map_ilocked || result != KERN_SUCCESS)) {
+ vm_map_ilk_unlock(map);
+ }
+@@ -4249,69 +4842,513 @@ vm_map_enter_adjust_offset(
+ return KERN_SUCCESS;
+ }
+
+-static __attribute__((always_inline, warn_unused_result))
+-kern_return_t
+-vm_map_enter_mem_object_sanitize(
+- vm_map_t target_map,
+- vm_map_offset_ut address_u,
+- vm_map_size_ut initial_size_u,
+- vm_map_offset_ut mask_u,
+- vm_object_offset_ut offset_u,
+- vm_prot_ut cur_protection_u,
+- vm_prot_ut max_protection_u,
+- vm_inherit_ut inheritance_u,
+- vm_map_kernel_flags_t vmk_flags,
+- ipc_port_t port,
+- vm_map_address_t *map_addr,
+- vm_map_size_t *map_size,
+- vm_map_offset_t *mask,
+- vm_object_offset_t *obj_offs,
+- vm_object_offset_t *obj_end,
+- vm_object_size_t *obj_size,
+- vm_prot_t *cur_protection,
+- vm_prot_t *max_protection,
+- vm_inherit_t *inheritance)
++static kern_return_t
++el0_object_prewire_pin(vm_object_t obj)
+ {
+- kern_return_t result;
+-
+- result = vm_sanitize_cur_and_max_prots(cur_protection_u, max_protection_u,
+- VM_SANITIZE_CALLER_ENTER_MEM_OBJ, target_map,
+- VM_PROT_IS_MASK, cur_protection,
+- max_protection);
+- if (__improbable(result != KERN_SUCCESS)) {
+- return result;
++ if (obj == VM_OBJECT_NULL) {
++ return KERN_SUCCESS;
+ }
+-
+- result = vm_sanitize_inherit(inheritance_u, VM_SANITIZE_CALLER_ENTER_MEM_OBJ,
+- inheritance);
+- if (__improbable(result != KERN_SUCCESS)) {
+- return result;
++ vm_object_lock(obj);
++ if (obj->vo_el0_prewire_count == UINT32_MAX) {
++ vm_object_unlock(obj);
++ return KERN_RESOURCE_SHORTAGE;
+ }
++ obj->vo_el0_prewire_count++;
++ vm_object_unlock(obj);
++ return KERN_SUCCESS;
++}
+
+- result = vm_sanitize_mask(mask_u, VM_SANITIZE_CALLER_ENTER_MEM_OBJ, mask);
+- if (__improbable(result != KERN_SUCCESS)) {
+- return result;
++static void
++el0_object_prewire_unpin(vm_object_t obj)
+{
-+ if (__improbable(linux64_trace_level < 0)) {
-+ int v = 0;
-+ if (!PE_parse_boot_argn("linux64_trace", &v, sizeof(v))) {
-+ v = 0;
++ if (obj == VM_OBJECT_NULL) {
++ return;
+ }
++ vm_object_lock(obj);
++ assert(obj->vo_el0_prewire_count > 0);
++ obj->vo_el0_prewire_count--;
++ vm_object_unlock(obj);
++}
+
+- if (vmk_flags.vmf_fixed) {
+- vm_map_address_t map_end;
++struct el0_atomic_seg {
++ vm_map_address_t va;
++ vm_map_size_t size;
++ vm_object_t object;
++ vm_object_offset_t offset;
++ vm_prot_t cur_protection;
++ vm_prot_t max_protection;
++ vm_inherit_t inheritance;
++ vm_map_kernel_flags_t vmk_flags;
++ bool is_submap;
++ bool needs_copy;
++ bool iokit_acct;
++ bool wimg_will_override;
++ bool prewired;
++ bool prewire_pinned;
++ bool populated;
++ vm_map_entry_t new_entry;
++};
+
+- result = vm_sanitize_addr_size(address_u, initial_size_u,
+- VM_SANITIZE_CALLER_ENTER_MEM_OBJ,
+- target_map,
+- VM_SANITIZE_FLAGS_SIZE_ZERO_FAILS | VM_SANITIZE_FLAGS_REALIGN_START,
+- map_addr, &map_end, map_size);
+- if (__improbable(result != KERN_SUCCESS)) {
+- return result;
+- }
+- } else {
+- *map_addr = vm_sanitize_addr(target_map, address_u);
+- result = vm_sanitize_size(0, initial_size_u,
+- VM_SANITIZE_CALLER_ENTER_MEM_OBJ, target_map,
+- VM_SANITIZE_FLAGS_SIZE_ZERO_FAILS, map_size);
+- if (__improbable(result != KERN_SUCCESS)) {
+- return result;
+- }
++static kern_return_t
++vm_map_el0_enter_entries_overwrite_atomic(
++ vm_map_t map,
++ vm_map_address_t base_addr,
++ vm_map_size_t total_size,
++ vm_map_offset_t mask,
++ vm_map_kernel_flags_t rsv_vmk_flags,
++ struct el0_atomic_seg *segs,
++ size_t nsegs)
++{
++ kern_return_t kr = KERN_SUCCESS;
++ vm_map_offset_t map_mask = VM_MAP_PAGE_MASK(map);
++
++ if (nsegs == 0 || total_size == 0 ||
++ !VM_MAP_PAGE_ALIGNED(base_addr, map_mask) ||
++ !VM_MAP_PAGE_ALIGNED(total_size, map_mask)) {
++ return KERN_INVALID_ARGUMENT;
++ }
++ vm_map_address_t total_end = 0;
++ if (os_add_overflow(base_addr, total_size, &total_end)) {
++ return KERN_INVALID_ARGUMENT;
++ }
++ vm_map_address_t check_va = base_addr;
++ for (size_t i = 0; i < nsegs; i++) {
++ if (segs[i].va != check_va || segs[i].size == 0 ||
++ !VM_MAP_PAGE_ALIGNED(segs[i].size, map_mask) ||
++ os_add_overflow(check_va, segs[i].size, &check_va)) {
++ return KERN_INVALID_ARGUMENT;
+ }
-+ linux64_trace_level = v;
++ if (segs[i].cur_protection & VM_PROT_ALLEXEC) {
++ return KERN_NOT_SUPPORTED;
++ }
++ segs[i].prewired = false;
++ segs[i].prewire_pinned = false;
++ segs[i].populated = false;
++ segs[i].new_entry = VM_MAP_ENTRY_NULL;
++ }
++ if (check_va != total_end) {
++ return KERN_INVALID_ARGUMENT;
+ }
-+ return linux64_trace_level;
-+}
+
-+static thread_t linux64_svc_thread; /* linux64_trace: the thread whose system call is in flight, and its number */
-+static long long linux64_svc_num;
++ /*
++ * Phase 1: Validate PA support and pre-wire object pages BEFORE touching
++ * any existing mappings in [base_addr, total_end).
++ */
++ for (size_t i = 0; i < nsegs; i++) {
++ if (segs[i].is_submap || segs[i].object == VM_OBJECT_NULL ||
++ is_kernel_object(segs[i].object) || segs[i].object == compressor_object ||
++ !(segs[i].cur_protection & (VM_PROT_READ | VM_PROT_WRITE))) {
++ continue;
++ }
++ if (!el0_object_range_supported(segs[i].object, segs[i].offset,
++ segs[i].size, segs[i].va, segs[i].wimg_will_override, false)) {
++ kr = KERN_NOT_SUPPORTED;
++ goto fail_phase1;
++ }
++ if (!segs[i].object->phys_contiguous && !segs[i].needs_copy &&
++ !(segs[i].object->private && segs[i].object->pager_created &&
++ !segs[i].object->vo_el0_populated)) {
++ vm_tag_t wire_tag = (segs[i].vmk_flags.vm_tag != VM_KERN_MEMORY_NONE) ?
++ segs[i].vmk_flags.vm_tag : VM_KERN_MEMORY_OSFMK;
++ kr = el0_object_prewire_pin(segs[i].object);
++ if (kr != KERN_SUCCESS) {
++ goto fail_phase1;
++ }
++ segs[i].prewire_pinned = true;
++ kr = vm_fault_wire_object_pages(map, segs[i].object,
++ segs[i].offset, segs[i].size, wire_tag, THREAD_UNINT);
++ if (kr != KERN_SUCCESS) {
++ goto fail_phase1;
++ }
++ segs[i].prewired = true;
++ vm_object_lock_shared(segs[i].object);
++ for (vm_map_size_t poff = 0; poff < segs[i].size; poff += PAGE_SIZE) {
++ vm_object_offset_t p_off;
++ if (os_add_overflow(segs[i].offset, segs[i].object->paging_offset, &p_off) ||
++ os_add_overflow(p_off, poff, &p_off)) {
++ kr = KERN_INVALID_ARGUMENT;
++ break;
++ }
++ vm_page_t m = vm_page_lookup(segs[i].object, p_off);
++ if (m != VM_PAGE_NULL &&
++ !pmap_el0_kmap_range_supported(segs[i].va + poff,
++ (pmap_paddr_t)ptoa_64(VM_PAGE_GET_PHYS_PAGE(m)), PAGE_SIZE)) {
++ kr = KERN_NOT_SUPPORTED;
++ break;
++ }
++ }
++ vm_object_unlock(segs[i].object);
++ if (kr != KERN_SUCCESS) {
++ goto fail_phase1;
++ }
++ }
++ }
+
-+/* LINUX64: user-space exceptions by class for the host (linux64_abi.h, LINUX64_EL0_CLASSES) */
-+uint64_t linux64_el0_stat[LINUX64_EL0_CPUS][2][LINUX64_EL0_CLASSES];
-+static uint64_t linux64_el0_t0[LINUX64_EL0_CPUS];
-+static uint8_t linux64_el0_cls[LINUX64_EL0_CPUS];
++ /*
++ * Phase 2: Single atomic overwrite of [base_addr, total_end), saving all
++ * old entries in zap_old_list and inserting all new entries kept exclusively
++ * locked until wiring + PTE population succeed for every segment.
++ */
++ VM_MAP_ZAP_DECLARE(zap_old_list);
++ VM_MAP_ZAP_DECLARE(zap_new_list);
++ vm_map_store_rsv_t rsv = vmsr_make(base_addr, VM_MAP_ENTRY_NULL);
++ bool map_ilocked = false;
+
-+void
-+linux64_thread_bootstrap_return(void)
-+{
-+ thread_t thread = current_thread();
++ rsv_vmk_flags.vmf_fixed = true;
++ rsv_vmk_flags.vmf_overwrite = true;
+
-+ static int reported;
++ for (size_t i = 0; i < nsegs; i++) {
++ if (!segs[i].is_submap && segs[i].needs_copy &&
++ segs[i].object != VM_OBJECT_NULL && !segs[i].object->shadowed) {
++ vm_object_lock(segs[i].object);
++ VM_OBJECT_SET_SHADOWED(segs[i].object, TRUE);
++ vm_object_unlock(segs[i].object);
++ }
++ }
+
-+ (void)ml_set_interrupts_enabled(FALSE);
-+ ast_taken_user();
-+ if (linux64_svc_thread == thread && linux64_tracing()) { /* what the system call returned (C set: x0 is errno) */
-+ linux64_svc_thread = NULL;
-+ extern int proc_selfpid(void);
-+ kprintf("linux64: [%d] svc %lld -> x0 0x%llx x1 0x%llx%s\n", proc_selfpid(), linux64_svc_num, get_saved_state_reg(thread->machine.upcb, 0),
-+ get_saved_state_reg(thread->machine.upcb, 1), (get_saved_state_cpsr(thread->machine.upcb) & PSR64_C) ? " (error)" : "");
++ vm_map_ilk_lock(map);
++ map_ilocked = true;
++
++ kr = vm_map_locate_space_fixed(map, base_addr, total_size, mask,
++ rsv_vmk_flags, &rsv, &zap_old_list);
++ if (kr != KERN_SUCCESS) {
++ vm_map_ilk_unlock(map);
++ vm_map_zap_dispose(map, &zap_old_list);
++ goto fail_phase1;
+ }
-+ if (reported++ == 0) {
-+ linux64_call2(LINUX64_CALL_USER_ENTER, get_saved_state_pc(thread->machine.upcb), 0);
++
++ for (size_t i = 0; i < nsegs; i++) {
++ vm_map_kernel_flags_t seg_flags = segs[i].vmk_flags;
++ seg_flags.vmkf_submap = segs[i].is_submap;
++ vm_map_entry_t ne = vm_map_entry_create_locked_and_insert(map,
++ segs[i].va, segs[i].va + segs[i].size,
++ segs[i].object, segs[i].offset, seg_flags,
++ segs[i].needs_copy,
++ segs[i].cur_protection, segs[i].max_protection,
++ segs[i].inheritance);
++ if (!segs[i].is_submap &&
++ segs[i].object != VM_OBJECT_NULL &&
++ segs[i].object->internal &&
++ (segs[i].object->purgable != VM_PURGABLE_DENY ||
++ segs[i].object->vo_ledger_tag)) {
++ ne->use_pmap = FALSE;
++ } else if (!segs[i].is_submap &&
++ segs[i].iokit_acct &&
++ segs[i].object != VM_OBJECT_NULL &&
++ segs[i].object->internal) {
++ ne->iokit_acct = TRUE;
++ ne->use_pmap = FALSE;
++ DTRACE_VM4(vm_map_iokit_mapped_region,
++ vm_map_t, map,
++ vm_map_offset_t, ne->vme_start,
++ vm_map_offset_t, ne->vme_end,
++ int, VME_ALIAS(ne));
++ vm_map_iokit_mapped_region(map, segs[i].size);
++ }
++ if (segs[i].object != VM_OBJECT_NULL) {
++ if (segs[i].is_submap) {
++ vm_map_reference((vm_map_t)(uintptr_t)segs[i].object);
++ } else {
++ vm_object_reference(segs[i].object);
++ }
++ }
++ segs[i].new_entry = ne;
+ }
-+ /*
-+ * An arm64 (not arm64e) process runs the arm64e system libraries with JOP off: Apple hardware disables the user
-+ * IA/DA keys for it; hosted, user code runs with SCTLR_EL1.EnIA/EnDA cleared (linux64_el0_run puts them back on
-+ * the next exception), or a blraaz on one of its unsigned function pointers fails (EXC_ARM_PAC_FAIL).
-+ */
-+#if PRECISE_USER_KERNEL_TIME
-+ recount_enter_user(); /* user time vs system time, as locore's return to user space does */
-+#endif
-+ { /* the host's per-class accounting (linux64_abi.h): the exception this CPU took last is now done */
-+ unsigned int slot = (unsigned int)cpu_number() & (LINUX64_EL0_CPUS - 1);
-+ if (linux64_el0_t0[slot] != 0) {
-+ linux64_el0_stat[slot][1][linux64_el0_cls[slot]] += __builtin_arm_rsr64("CNTVCT_EL0") - linux64_el0_t0[slot];
-+ linux64_el0_t0[slot] = 0;
++
++ if (map->size_limit != RLIM_INFINITY && map->size > map->size_limit) {
++ kr = KERN_NO_SPACE;
++ } else if (map->data_limit != RLIM_INFINITY && map->size > map->data_limit) {
++ kr = KERN_NO_SPACE;
++ }
++
++ vm_map_ilk_unlock(map);
++ map_ilocked = false;
++
++ if (kr == KERN_SUCCESS) {
++ for (size_t i = 0; i < nsegs; i++) {
++ vm_map_entry_t ne = segs[i].new_entry;
++ if (segs[i].is_submap ||
++ !(segs[i].cur_protection & (VM_PROT_READ | VM_PROT_WRITE)) ||
++ el0_entry_unpopulated_device_pager(ne)) {
++ continue;
++ }
++ if (ne->needs_copy) {
++ vm_map_entry_lock_resolve_symmetric_cow(map, ne);
++ }
++ if (VME_OBJECT(ne) == VM_OBJECT_NULL) {
++ vm_map_entry_lock_allocate_object(ne, vm_map_maybe_serial_id(map));
++ }
++ vm_object_t obj = VME_OBJECT(ne);
++ if (is_kernel_object(obj) || obj == compressor_object) {
++ continue;
++ }
++ vm_tag_t wire_tag = (VME_ALIAS(ne) != VM_KERN_MEMORY_NONE) ?
++ VME_ALIAS(ne) : VM_KERN_MEMORY_OSFMK;
++ bool obj_wired = false;
++ bool seg_pinned = false;
++ if (!obj->phys_contiguous) {
++ vm_map_size_t wire_sz = 0;
++ kr = vm_map_preflight_wire_space(map, ne, FALSE, &wire_sz);
++ if (kr == KERN_SUCCESS) {
++ kr = el0_object_prewire_pin(obj);
++ if (kr == KERN_SUCCESS) {
++ seg_pinned = true;
++ kr = vm_fault_wire_object_pages(map, obj,
++ VME_OFFSET(ne), ne->vme_end - ne->vme_start,
++ wire_tag, THREAD_UNINT);
++ if (kr == KERN_SUCCESS) {
++ obj_wired = true;
++ }
++ }
++ }
++ }
++ if (kr == KERN_SUCCESS) {
++ kr = vm_map_wire_count_add(map, ne, FALSE);
++ if (kr == KERN_SUCCESS) {
++ struct vm_map_lock_ctx seg_ctx = {
++ .vmlc_req_start = ne->vme_start,
++ .vmlc_req_end = ne->vme_end,
++ .vmlc_map = map,
++ .vmlc_vme = ne,
++ .__vmlc_flags = VMRL_EX_STREAM_NO_HOLES | VMRL_RESOLVE_COW_AND_OBJ | _VMRL_SINGLE_ENTRY,
++ .__vmlc_locked = true,
++ };
++ kr = vm_fault_wire_resident_pages(map, ne,
++ segs[i].cur_protection & (VM_PROT_READ | VM_PROT_WRITE),
++ wire_tag, NULL, &seg_ctx);
++ if (kr == KERN_SUCCESS) {
++ ne->vme_el0_autowire = 1;
++ segs[i].populated = true;
++ } else {
++ vm_map_wire_count_sub(map, ne, FALSE);
++ obj_wired = false;
++ }
++ } else if (obj_wired) {
++ vm_fault_unwire_object_pages(map, obj,
++ VME_OFFSET(ne), ne->vme_end - ne->vme_start);
++ obj_wired = false;
++ }
++ }
++ if (seg_pinned) {
++ el0_object_prewire_unpin(obj);
++ }
++ if (kr != KERN_SUCCESS) {
++ break;
++ }
+ }
+ }
-+ linux64_el0_run(thread->machine.upcb, (thread->machine.arm_machine_flags & ARM_MACHINE_THREAD_DISABLE_USER_JOP) != 0);
-+}
+
-+/* LINUX64: the registers linux64_el0_vectors saved for an exception taken at EL0 (cswitch.s) */
-+struct linux64_el0_frame {
-+ uint64_t x[31];
-+ uint64_t sp, pc, cpsr, esr, far;
-+ uint64_t neon[64]; /* q0..q31 */
-+ uint32_t fpsr, fpcr;
-+ uint64_t pad;
-+};
-+_Static_assert(__builtin_offsetof(struct linux64_el0_frame, neon) == 288, "linux64_el0_frame layout");
-+_Static_assert(sizeof(struct linux64_el0_frame) == 36 * 8 + 528, "linux64_el0_frame size");
++ if (kr == KERN_SUCCESS) {
++ if (zap_old_list.el0_kmap_txn != 0) {
++ pmap_el0_kmap_txn_end(zap_old_list.el0_kmap_txn);
++ zap_old_list.el0_kmap_txn = 0;
++ }
++ for (size_t i = 0; i < nsegs; i++) {
++ vm_entry_unlock_exclusive(map, segs[i].new_entry);
++ if (!segs[i].is_submap) {
++ vm_object_t obj = segs[i].object;
++ if (obj != VM_OBJECT_NULL &&
++ obj->named &&
++ obj->pager != MEMORY_OBJECT_NULL &&
++ obj->copy_strategy != MEMORY_OBJECT_COPY_NONE) {
++ vm_prot_t pager_prot = segs[i].max_protection;
++ if (segs[i].needs_copy) {
++ pager_prot &= ~VM_PROT_WRITE;
++ }
++ vm_object_lock(obj);
++ memory_object_t pager = obj->pager;
++ if (obj->named && pager != MEMORY_OBJECT_NULL &&
++ obj->copy_strategy != MEMORY_OBJECT_COPY_NONE) {
++ assert(obj->pager_ready);
++ vm_object_mapping_wait(obj, THREAD_UNINT);
++ pager = obj->pager;
++ if (obj->named && pager != MEMORY_OBJECT_NULL) {
++ vm_object_mapping_begin(obj);
++ vm_object_unlock(obj);
+
-+void linux64_el0_exception(struct linux64_el0_frame *f) __attribute__((noreturn));
-+void
-+linux64_el0_exception(struct linux64_el0_frame *f)
-+{
-+ thread_t thread = current_thread();
-+ arm_saved_state_t *ss = thread->machine.upcb;
++ kern_return_t mkr = memory_object_map(pager, pager_prot);
++ assert(mkr == KERN_SUCCESS);
+
-+#if PRECISE_USER_KERNEL_TIME
-+ recount_leave_user(); /* interrupts are still off here, as on locore's exception entry */
-+#endif
-+ linux64_count(LINUX64_CTR_EL0_EXC); /* for the host's monitor: EL0 exceptions, the last one's ESR, FAR, PC */
-+ {
-+ unsigned int slot = (unsigned int)cpu_number() & (LINUX64_EL0_CPUS - 1), ec = (unsigned int)ESR_EC(f->esr);
-+ unsigned int cls = f->esr == ~0ULL ? 3 : ec == ESR_EC_SVC_64 ? 0 : ec == ESR_EC_DABORT_EL0 ? 1 : ec == ESR_EC_IABORT_EL0 ? 2 : 4;
-+ linux64_el0_stat[slot][0][cls]++;
-+ linux64_el0_cls[slot] = (uint8_t)cls;
-+ linux64_el0_t0[slot] = __builtin_arm_rsr64("CNTVCT_EL0");
-+ }
-+ linux64_dbg[LINUX64_CTR_EL0_ESR] = f->esr;
-+ linux64_dbg[LINUX64_CTR_EL0_FAR] = f->far;
-+ linux64_dbg[LINUX64_CTR_EL0_PC] = f->pc;
-+ if (linux64_tracing()) kprintf("linux64: EL0 exception esr 0x%llx far 0x%llx pc 0x%llx x16 %lld ttbr0 0x%llx ttep 0x%llx\n", f->esr, f->far, f->pc, f->x[16],
-+ __builtin_arm_rsr64("TTBR0_EL1"), (uint64_t)thread->map->pmap->ttep);
-+ /*
-+ * The whole user state at once, signed once as locore's exception entry does (HAS_APPLE_PAC): the per-field setters
-+ * each check the old signature and sign again, five times per exception. EL0 runs with IRQ/FIQ masked while hosted
-+ * (no XNU interrupts at EL0 yet); XNU must see the user's own PSTATE, or its abort path takes the user fault for
-+ * one from a non-interruptible context.
-+ */
-+ {
-+ arm_saved_state64_t *s64 = saved_state64(ss);
-+ uint32_t cpsr = (uint32_t)f->cpsr & ~(uint32_t)0x3c0;
-+ for (unsigned i = 0; i < 29; i++) {
-+ if (i != 16 && i != 17) {
-+ s64->x[i] = f->x[i];
++ vm_object_lock(obj);
++ vm_object_mapping_end(obj);
++ }
++ }
++ vm_object_unlock(obj);
++ }
++ } else if (segs[i].object != VM_OBJECT_NULL) {
++ vm_map_t submap = (vm_map_t)(uintptr_t)segs[i].object;
++ if (submap->mapped_in_other_pmaps == FALSE &&
++ vm_map_pmap(submap) != PMAP_NULL &&
++ vm_map_pmap(submap) != vm_map_pmap(map)) {
++ vm_map_ilk_lock(submap);
++ submap->mapped_in_other_pmaps = TRUE;
++ vm_map_ilk_unlock(submap);
++ }
++ }
++ if (segs[i].prewired) {
++ vm_fault_unwire_object_pages(map, segs[i].object,
++ segs[i].offset, segs[i].size);
++ segs[i].prewired = false;
++ }
++ if (segs[i].prewire_pinned) {
++ el0_object_prewire_unpin(segs[i].object);
++ segs[i].prewire_pinned = false;
++ }
++ if (segs[i].object != VM_OBJECT_NULL) {
++ if (segs[i].is_submap) {
++ vm_map_deallocate((vm_map_t)(uintptr_t)segs[i].object);
++ } else {
++ vm_object_deallocate(segs[i].object);
++ }
++ }
++ }
++ vm_map_zap_dispose(map, &zap_old_list);
++ return KERN_SUCCESS;
++ }
++
++ /* Rollback: unwire any populated prefix, unlink all new entries, restore zap_old_list */
++ for (size_t i = 0; i < nsegs; i++) {
++ if (segs[i].populated) {
++ vm_map_entry_t ne = segs[i].new_entry;
++ ne->vme_el0_autowire = 0;
++ if (vm_map_wire_count_sub(map, ne, FALSE)) {
++ ne->zero_wired_pages = FALSE;
++ vm_fault_unwire(map, ne, false, map->pmap,
++ ne->vme_start, ne->vme_end);
+ }
++ segs[i].populated = false;
+ }
-+ s64->fp = f->x[29];
-+ s64->sp = f->sp;
-+#if HAS_APPLE_PAC
-+ uint64_t intr = ml_pac_safe_interrupts_disable();
-+ asm volatile (
-+ "mov x9, lr" "\n"
-+ "mov x0, %[ss]" "\n"
-+ "mrs x10, SPSel" "\n"
-+ "msr SPSel, #1" "\n"
-+ "mov x1, %[pc]" "\n"
-+ "mov w2, %w[cpsr]" "\n"
-+ "mov x3, %[lr]" "\n"
-+ "mov x4, %[x16]" "\n"
-+ "mov x5, %[x17]" "\n"
-+ "str x1, [x0, %[SS64_PC]]" "\n"
-+ "str w2, [x0, %[SS64_CPSR]]" "\n"
-+ "str x3, [x0, %[SS64_LR]]" "\n"
-+ "stp x4, x5, [x0, %[SS64_X16]]" "\n"
-+ "bl _ml_sign_thread_state" "\n"
-+ "msr SPSel, x10" "\n"
-+ "mov lr, x9" "\n"
-+ :
-+ : [ss] "r"(ss), [pc] "r"(f->pc), [cpsr] "r"(cpsr), [lr] "r"(f->x[30]), [x16] "r"(f->x[16]), [x17] "r"(f->x[17]),
-+ [SS64_X16] "i"(ss64_offsetof(x[16])), [SS64_PC] "i"(ss64_offsetof(pc)),
-+ [SS64_CPSR] "i"(ss64_offsetof(cpsr)), [SS64_LR] "i"(ss64_offsetof(lr))
-+ : "x0", "x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9", "x10", "x16", "x17", "memory"
-+ );
-+ ml_pac_safe_interrupts_restore(intr);
-+#else
-+ s64->x[16] = f->x[16];
-+ s64->x[17] = f->x[17];
-+ s64->lr = f->x[30];
-+ s64->pc = f->pc;
-+ s64->cpsr = cpsr;
-+#endif
-+ }
-+ {
-+ arm_neon_saved_state_t *ns = thread->machine.uNeon;
-+ memcpy(&ns->ns_64.v.q[0], f->neon, sizeof(f->neon));
-+ ns->ns_64.fpsr = f->fpsr;
-+ ns->ns_64.fpcr = f->fpcr;
+ }
-+ if (f->esr == ~0ULL) {
-+ /*
-+ * A host IRQ arrived while user code ran (EL0 runs with IRQs unmasked). Let Linux take it and run what it
-+ * must (its tick, RCU, other tasks), then deliver XNU's timer "interrupt" if it is due, as sleh_irq
-+ * would: the quantum expiry it may raise preempts this thread on the way back to user space.
-+ */
-+ cpu_data_t *cdp = getCpuDatap();
-+ (void)ml_set_interrupts_enabled(FALSE); /* XNU's (virtual) interrupt state: off, as in sleh_irq */
-+ linux64_call2(LINUX64_CALL_PREEMPTED, 0, 0);
-+ if (cdp->rtcPop != EndOfAllTime && cdp->rtcPop != 0 && mach_absolute_time() >= cdp->rtcPop) {
-+ cdp->cpu_int_state = ss;
-+ cdp->cpu_stat.irq_ex_cnt++;
-+ cdp->cpu_decrementer = -1;
-+ rtclock_intr(TRUE);
-+ cdp->cpu_int_state = NULL;
++
++ vm_map_ilk_lock(map);
++ map_ilocked = true;
++ for (size_t i = 0; i < nsegs; i++) {
++ vm_map_entry_t ne = segs[i].new_entry;
++ if (ne == VM_MAP_ENTRY_NULL) {
++ continue;
+ }
-+ 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;
++ pmap_remove(map->pmap, ne->vme_start, ne->vme_end);
++ if (ne->iokit_acct) {
++ DTRACE_VM4(vm_map_iokit_unmapped_region,
++ vm_map_t, map,
++ vm_map_offset_t, ne->vme_start,
++ vm_map_offset_t, ne->vme_end,
++ int, VME_ALIAS(ne));
++ vm_map_iokit_unmapped_region(map, ne->vme_end - ne->vme_start);
++ ne->iokit_acct = FALSE;
++ ne->use_pmap = FALSE;
+ }
-+ thread_exception_return();
++ vm_map_entry_unlink_and_extend_sentinel(map, ne, VM_MAP_ENTRY_NULL);
++ vm_map_zap_append(&zap_new_list, ne);
++ segs[i].new_entry = VM_MAP_ENTRY_NULL;
+ }
-+ if (ESR_EC(f->esr) == ESR_EC_SVC_64 && linux64_tracing()) {
-+ long long num = (long long)f->x[16];
-+ linux64_svc_thread = thread;
-+ linux64_svc_num = num;
-+ if (num == 202 && f->x[1] > 0 && f->x[1] <= 8) { /* sysctl: the MIB and this thread's kernel stack */
-+ int mib[8] = {0};
-+ if (copyin((user_addr_t)f->x[0], mib, f->x[1] * sizeof(int)) == 0) {
-+ kprintf("linux64: svc 202 mib %d.%d.%d.%d (len %llu) kstack 0x%llx\n", mib[0], mib[1], mib[2], mib[3], f->x[1],
-+ (uint64_t)thread->kernel_stack);
++
++ if (vm_map_zap_first_entry(&zap_old_list)) {
++ vm_map_address_t z_start = vm_map_zap_first_entry(&zap_old_list)->vme_start;
++ vm_map_address_t z_end = vm_map_zap_last_entry(&zap_old_list)->vme_end;
++ if (!vm_map_store_has_entries(map, z_start, z_end)) {
++ if (zap_old_list.el0_saved_head != NULL) {
++ vm_map_el0_restore_zapped_entries(map, &zap_old_list, &map_ilocked);
++ } else {
++ vm_map_entry_t oe;
++ while ((oe = vm_map_zap_pop(&zap_old_list))) {
++ assert(!VME_IS_SENTINEL(oe));
++ vm_map_store_insert(map, oe);
++ vm_entry_unlock_exclusive(map, oe);
++ }
++ vm_map_enter_restore_successes++;
+ }
++ } else {
++ vm_map_enter_restore_failures++;
+ }
-+ if (num == 59 || num == 244 || num == 5 || num == 398 || num == 463 || num == 33 || num == 338 || num == 340 || num == 466 || num == 469) {
-+ char path[128];
-+ size_t len = 0;
-+ uint64_t ua = (num == 463 || num == 466 || num == 469 || num == 244) ? f->x[1] : f->x[0];
-+ if (copyinstr((user_addr_t)ua, path, sizeof(path), &len) == 0) {
-+ extern int proc_selfpid(void);
-+ kprintf("linux64: [%d] svc %lld path \"%s\"\n", proc_selfpid(), num, path);
-+ }
++ }
++
++ if (map_ilocked) {
++ vm_map_ilk_unlock(map);
++ map_ilocked = false;
++ }
++
++ vm_map_zap_dispose(map, &zap_old_list);
++ vm_map_zap_dispose(map, &zap_new_list);
++
++fail_phase1:
++ for (size_t i = 0; i < nsegs; i++) {
++ if (segs[i].prewired) {
++ vm_fault_unwire_object_pages(map, segs[i].object,
++ segs[i].offset, segs[i].size);
++ segs[i].prewired = false;
++ }
++ if (segs[i].prewire_pinned) {
++ el0_object_prewire_unpin(segs[i].object);
++ segs[i].prewire_pinned = false;
+ }
+ }
-+ sleh_synchronous(thread->machine.contextData, f->esr, (vm_offset_t)f->far, false);
-+ thread_exception_return();
++ return kr;
+}
-diff --git a/osfmk/arm64/status.c b/osfmk/arm64/status.c
-index c615764..72ec4a7 100644
---- a/osfmk/arm64/status.c
-+++ b/osfmk/arm64/status.c
-@@ -2103,16 +2103,17 @@ machine_thread_state_initialize(thread_t thread)
- "mov x3, #0" "\n"
- "mov x4, #0" "\n"
- "mov x5, #0" "\n"
-+ "mrs x10, SPSel" "\n"
- "msr SPSel, #1" "\n"
- VERIFY_USER_THREAD_STATE_INSTR "\n"
- "mov x6, lr" "\n"
- "bl _ml_sign_thread_state" "\n"
-- "msr SPSel, #0" "\n"
-+ "msr SPSel, x10" "\n"
- "mov lr, x6" "\n"
- :
- : [iss] "r"(thread->machine.upcb), [usr] "r"(thread->machine.upcb->ss_64.cpsr),
- VERIFY_USER_THREAD_STATE_INPUTS
-- : "x0", "x1", "x2", "x3", "x4", "x5", "x6", "x17"
-+ : "x0", "x1", "x2", "x3", "x4", "x5", "x6", "x10", "x17"
- );
- ml_pac_safe_interrupts_restore(intr);
- }
-diff --git a/osfmk/console/serial_console.c b/osfmk/console/serial_console.c
-index 11d9eb4..8c59a02 100644
---- a/osfmk/console/serial_console.c
-+++ b/osfmk/console/serial_console.c
-@@ -1,4 +1,5 @@
- #include <kern/boot_progress.h>
-+#include <linux64/linux64.h>
- /*
- * Copyright (c) 2000-2020 Apple, Inc. All rights reserved.
- *
-@@ -532,6 +533,13 @@ console_resume()
- void
- console_write(char *str, int size)
- {
-+ {
-+ /* LINUX64 (xnulinux): hosted XNU's console (/dev/console, km) goes to the host (stage 996: bytes, length). */
-+ if (linux64_hook && str && size > 0) {
-+ linux64_call2(LINUX64_CALL_CONSOLE_WRITE, (unsigned long)str, (unsigned long)size);
-+ return;
-+ }
++
++static __attribute__((always_inline, warn_unused_result))
++kern_return_t
++vm_map_enter_mem_object_sanitize(
++ vm_map_t target_map,
++ vm_map_offset_ut address_u,
++ vm_map_size_ut initial_size_u,
++ vm_map_offset_ut mask_u,
++ vm_object_offset_ut offset_u,
++ vm_prot_ut cur_protection_u,
++ vm_prot_ut max_protection_u,
++ vm_inherit_ut inheritance_u,
++ vm_map_kernel_flags_t vmk_flags,
++ ipc_port_t port,
++ vm_map_address_t *map_addr,
++ vm_map_size_t *map_size,
++ vm_map_offset_t *mask,
++ vm_object_offset_t *obj_offs,
++ vm_object_offset_t *obj_end,
++ vm_object_size_t *obj_size,
++ vm_prot_t *cur_protection,
++ vm_prot_t *max_protection,
++ vm_inherit_t *inheritance)
++{
++ kern_return_t result;
++
++ result = vm_sanitize_cur_and_max_prots(cur_protection_u, max_protection_u,
++ VM_SANITIZE_CALLER_ENTER_MEM_OBJ, target_map,
++ VM_PROT_IS_MASK, cur_protection,
++ max_protection);
++ if (__improbable(result != KERN_SUCCESS)) {
++ return result;
+ }
- if (disableConsoleOutput) {
- return;
++
++ result = vm_sanitize_inherit(inheritance_u, VM_SANITIZE_CALLER_ENTER_MEM_OBJ,
++ inheritance);
++ if (__improbable(result != KERN_SUCCESS)) {
++ return result;
++ }
++
++ result = vm_sanitize_mask(mask_u, VM_SANITIZE_CALLER_ENTER_MEM_OBJ, mask);
++ if (__improbable(result != KERN_SUCCESS)) {
++ return result;
++ }
++
++ if (vmk_flags.vmf_fixed) {
++ vm_map_address_t map_end;
++
++ result = vm_sanitize_addr_size(address_u, initial_size_u,
++ VM_SANITIZE_CALLER_ENTER_MEM_OBJ,
++ target_map,
++ VM_SANITIZE_FLAGS_SIZE_ZERO_FAILS | VM_SANITIZE_FLAGS_REALIGN_START,
++ map_addr, &map_end, map_size);
++ if (__improbable(result != KERN_SUCCESS)) {
++ return result;
++ }
++ } else {
++ *map_addr = vm_sanitize_addr(target_map, address_u);
++ result = vm_sanitize_size(0, initial_size_u,
++ VM_SANITIZE_CALLER_ENTER_MEM_OBJ, target_map,
++ VM_SANITIZE_FLAGS_SIZE_ZERO_FAILS, map_size);
++ if (__improbable(result != KERN_SUCCESS)) {
++ return result;
++ }
}
-diff --git a/osfmk/console/serial_general.c b/osfmk/console/serial_general.c
-index b1ca47a..d878442 100644
---- a/osfmk/console/serial_general.c
-+++ b/osfmk/console/serial_general.c
-@@ -33,6 +33,7 @@
- */
- #include <kern/spl.h>
-+#include <linux64/linux64.h>
- #include <mach/std_types.h>
- #include <types.h>
- #include <kern/thread.h>
-@@ -48,13 +49,32 @@ SECURITY_READ_ONLY_LATE(unsigned int) serialmode;
- * characters that have been typed.
- */
+ *obj_size = vm_object_round_page(*map_size);
+@@ -4468,6 +5505,11 @@ vm_map_enter_mem_object(
+ vmlp_api_end(VM_MAP_ENTER_MEM_OBJECT, KERN_INVALID_RIGHT);
+ return KERN_INVALID_RIGHT;
+ }
++ if (linux64_el0 && target_map->pmap == kernel_pmap &&
++ (cur_protection & VM_PROT_ALLEXEC)) {
++ vmlp_api_end(VM_MAP_ENTER_MEM_OBJECT, KERN_NOT_SUPPORTED);
++ return KERN_NOT_SUPPORTED;
++ }
-+/*
-+ * LINUX64 (xnulinux): a hosted XNU's console input comes from the host (LINUX64_CALL_CONSOLE_READ), polled by the serial keyboard thread like a UART.
-+ */
-+static int
-+linux64_cons_getc(void)
-+{
-+ static char buf[64];
-+ static int n, i;
+ /*
+ * unwrap is safe because we know obj_size is larger and doesn't
+@@ -4673,6 +5715,177 @@ vm_map_enter_mem_object(
+ VM_FLAGS_RETURN_4K_DATA_ADDR |
+ VM_FLAGS_RETURN_DATA_ADDR));
+
++ if (linux64_el0 && target_map->pmap == kernel_pmap &&
++ vmk_flags.vmf_overwrite) {
++ size_t n_entries = 0;
++ for (copy_entry = vm_map_copy_first_entry(target_copy_map);
++ copy_entry != vm_map_copy_to_entry(target_copy_map);
++ copy_entry = copy_entry->vme_next) {
++ n_entries++;
++ }
++ if (n_entries == 0) {
++ kr = KERN_INVALID_ARGUMENT;
++ } else {
++ struct el0_atomic_seg *segs = kalloc_type(
++ struct el0_atomic_seg, n_entries, Z_WAITOK | Z_ZERO);
++ if (segs == NULL) {
++ kr = KERN_RESOURCE_SHORTAGE;
++ } else {
++ size_t n_segs = 0;
++ vm_map_offset_t seg_va = map_addr;
++ kr = KERN_SUCCESS;
++ for (copy_entry = vm_map_copy_first_entry(target_copy_map);
++ copy_entry != vm_map_copy_to_entry(target_copy_map);
++ copy_entry = copy_entry->vme_next) {
++ vm_map_t copy_submap = VM_MAP_NULL;
++ vm_object_t copy_object = VM_OBJECT_NULL;
++ vm_map_size_t copy_size = copy_entry->vme_end - copy_entry->vme_start;
++ vm_object_offset_t copy_offset = VME_OFFSET(copy_entry);
++ boolean_t do_copy = FALSE;
+
-+ if (i < n) {
-+ return (unsigned char)buf[i++];
++ if (copy_entry->is_sub_map) {
++ copy_submap = VME_SUBMAP(copy_entry);
++ copy_object = (vm_object_t)copy_submap;
++ } else {
++ copy_object = VME_OBJECT(copy_entry);
++ }
++ if (copy_object != VM_OBJECT_NULL) {
++ do_copy = copy || copy_entry->needs_copy;
++ }
++ if ((seg_va + copy_size) > (map_addr + target_size)) {
++ kr = KERN_INVALID_ARGUMENT;
++ break;
++ }
++ if (copy_entry->is_sub_map) {
++ vm_map_reference(copy_submap);
++ } else {
++ if (!copy && copy_object != VM_OBJECT_NULL) {
++ if (copy_object->copy_strategy == MEMORY_OBJECT_COPY_SYMMETRIC) {
++ bool is_writable = false;
++ if (!copy_object->shadowed) {
++ vm_object_lock(copy_object);
++ VM_OBJECT_SET_SHADOWED(copy_object, TRUE);
++ vm_object_unlock(copy_object);
++ }
++ VME_OBJECT_SHADOW(copy_entry, copy_size, TRUE);
++ assert(copy_object != VME_OBJECT(copy_entry));
++ if (copy_entry->protection & VM_PROT_WRITE) {
++ is_writable = true;
++#if __arm64e__
++ } else if (copy_entry->used_for_tpro) {
++ is_writable = true;
++#endif /* __arm64e__ */
++ }
++ if (!copy_entry->needs_copy && is_writable) {
++ vm_prot_t prot = copy_entry->protection & ~VM_PROT_WRITE;
++ vm_object_pmap_protect(copy_object,
++ copy_offset, copy_size,
++ PMAP_NULL, PAGE_SIZE, 0, prot);
++ }
++ copy_entry->needs_copy = FALSE;
++ do_copy = FALSE;
++ copy_entry->is_shared = TRUE;
++ copy_object = VME_OBJECT(copy_entry);
++ copy_offset = VME_OFFSET(copy_entry);
++ vm_object_lock(copy_object);
++ copy_object->copy_strategy = MEMORY_OBJECT_COPY_DELAY;
++ VM_OBJECT_SET_TRUE_SHARE(copy_object, TRUE);
++ } else {
++ vm_object_lock(copy_object);
++ }
++ vm_object_mark_shared(copy_object, VM_SHARE_TYPE_PERMANENT);
++ vm_object_unlock(copy_object);
++ }
++ if (copy && copy_object != VM_OBJECT_NULL) {
++ vm_object_t new_object;
++ vm_object_offset_t new_offset;
++ result = vm_object_copy_strategically(copy_object,
++ copy_offset, copy_size, false,
++ &new_object, &new_offset, &do_copy);
++ if (result == KERN_MEMORY_RESTART_COPY) {
++ boolean_t success;
++ boolean_t src_needs_copy;
++ new_object = copy_object;
++ new_offset = copy_offset;
++ success = vm_object_copy_quickly(new_object,
++ new_offset, copy_size,
++ &src_needs_copy, &do_copy);
++ assert(success);
++ result = KERN_SUCCESS;
++ }
++ if (result != KERN_SUCCESS) {
++ kr = result;
++ break;
++ }
++ copy_object = new_object;
++ copy_offset = new_offset;
++ } else {
++ copy_object = VME_OBJECT(copy_entry);
++ copy_offset = VME_OFFSET(copy_entry);
++ if (copy_object != VM_OBJECT_NULL) {
++ vm_object_reference(copy_object);
++ }
++ }
++ }
++ vm_map_kernel_flags_t vmk_remap_flags = {
++ .vmkf_submap = copy_entry->is_sub_map,
++ };
++ vm_map_kernel_flags_set_vmflags(&vmk_remap_flags,
++ vm_map_kernel_flags_vmflags(vmk_flags),
++ vmk_flags.vm_tag ?: VME_ALIAS(copy_entry));
++ vmk_remap_flags.vmf_fixed = true;
++ vmk_remap_flags.vmf_overwrite = true;
++#if XNU_TARGET_OS_OSX
++ if (copy_entry->used_for_jit) {
++ vmk_remap_flags.vmkf_map_jit = TRUE;
++ }
++#endif /* XNU_TARGET_OS_OSX */
++ segs[n_segs].va = seg_va;
++ segs[n_segs].size = copy_size;
++ segs[n_segs].object = copy_object;
++ segs[n_segs].offset = copy_offset;
++ segs[n_segs].cur_protection = cur_protection;
++ segs[n_segs].max_protection = max_protection;
++ segs[n_segs].inheritance = inheritance;
++ segs[n_segs].vmk_flags = vmk_remap_flags;
++ segs[n_segs].is_submap = copy_entry->is_sub_map;
++ segs[n_segs].needs_copy = do_copy;
++ segs[n_segs].iokit_acct = vmk_flags.vmkf_iokit_acct;
++ n_segs++;
++ seg_va += copy_size;
++ }
++ if (kr == KERN_SUCCESS) {
++ kr = vm_map_el0_enter_entries_overwrite_atomic(
++ target_map, map_addr,
++ vm_map_round_page(target_size, map_mask),
++ mask, rsv_flags, segs, n_segs);
++ }
++ if (kr != KERN_SUCCESS) {
++ for (size_t i = 0; i < n_segs; i++) {
++ if (segs[i].object != VM_OBJECT_NULL) {
++ if (segs[i].is_submap) {
++ vm_map_deallocate((vm_map_t)(uintptr_t)segs[i].object);
++ } else {
++ vm_object_deallocate(segs[i].object);
++ }
++ }
++ }
++ }
++ kfree_type(struct el0_atomic_seg, n_entries, segs);
++ }
++ }
++ named_entry_unlock(named_entry);
++ if (target_copy_map != copy_map) {
++ vm_map_copy_discard(target_copy_map);
++ target_copy_map = VM_MAP_COPY_NULL;
++ }
++ if (kr == KERN_SUCCESS) {
++ offset_in_mapping += overmap_start;
++ }
++ result = kr;
++ goto out;
++ }
++
+ /* reserve a contiguous range */
+ kr = vm_map_enter(target_map,
+ &map_addr,
+@@ -5048,6 +6261,11 @@ vm_map_enter_mem_object(
+ vmk_flags.vmf_return_4k_data_addr) {
+ panic("VM_FLAGS_RETURN_DATA_ADDR not expected for raw memory object.");
+ }
++ if (linux64_el0 && target_map->pmap == kernel_pmap &&
++ (cur_protection & VM_PROT_ALLEXEC)) {
++ vmlp_api_end(VM_MAP_ENTER_MEM_OBJECT, KERN_NOT_SUPPORTED);
++ return KERN_NOT_SUPPORTED;
++ }
+
+ object = memory_object_to_vm_object((memory_object_t)port);
+ if (object == VM_OBJECT_NULL) {
+@@ -5797,40 +7015,168 @@ vm_map_protect_preflight(
+ * specified, the maximum protection is to be set;
+ * otherwise, only the current protection is affected.
+ */
+-kern_return_t
+-vm_map_protect(
++static bool vm_map_wire_count_sub(vm_map_t map, vm_map_entry_t entry, bool user_wire);
++extern kern_return_t vm_map_wire_el0_autowire(vm_map_t map, vm_map_offset_t start, vm_map_offset_t end);
++static kern_return_t vm_map_wire_impl_internal(
+ vm_map_t original_map,
+ vm_map_offset_ut start_u,
+ vm_map_offset_ut end_u,
+- boolean_t set_max,
+- vm_prot_ut new_prot_u)
++ vm_prot_ut prot_u,
++ vm_tag_t tag,
++ boolean_t user_wire,
++ ppnum_t *physpage_p,
++ vm_sanitize_caller_t vm_sanitize_caller,
++ bool el0_autowire,
++ bool el0_protect_apply,
++ vm_prot_t el0_protect_new_prot,
++ int el0_protect_pmap_options);
++
++static void
++el0_protect_apply_entry_locked(
++ vm_map_t cur_map,
++ vm_map_entry_t entry,
++ vm_prot_t new_prot,
++ int pmap_options)
+ {
+- vm_map_entry_t entry;
+- __block vm_prot_t new_prot;
+- int pmap_options = 0;
+- kern_return_t kr;
+- vm_map_offset_t start;
+- vm_map_offset_t end;
+- VM_MAP_LOCK_CTX_DECLARE(ctx);
++ extern unsigned int linux64_el0;
++ const bool el0_is_kmap = (linux64_el0 && cur_map->pmap == kernel_pmap);
++ vm_prot_t old_prot = entry->protection;
+
+- vmlp_api_start(VM_MAP_PROTECT);
++ entry->protection = new_prot;
+
+- kr = vm_map_protect_sanitize(original_map,
+- start_u,
+- end_u,
+- new_prot_u,
+- &start,
+- &end,
+- &new_prot);
+- if (__improbable(kr != KERN_SUCCESS)) {
+- kr = vm_sanitize_get_kr(kr);
+- vmlp_api_end(VM_MAP_PROTECT, kr);
+- return kr;
++#if CODE_SIGNING_MONITOR
++ if (((!entry->csm_associated &&
++ !(old_prot & VM_PROT_EXECUTE) &&
++ (entry->protection & VM_PROT_EXECUTE)) ||
++ (entry->csm_associated &&
++ !(old_prot & VM_PROT_WRITE) &&
++ (entry->protection & VM_PROT_WRITE)))) {
++ vm_map_kernel_flags_t vmk_flags;
++ vmk_flags = VM_MAP_KERNEL_FLAGS_NONE;
++ vmk_flags.vmkf_remap_prot_copy = true;
++ (void)vm_map_entry_cs_associate(cur_map, entry, vmk_flags);
+ }
++#endif /* CODE_SIGNING_MONITOR */
+
+- if (new_prot & VM_PROT_COPY) {
+- vm_map_offset_t new_start;
+- vm_prot_t cur_prot, max_prot;
++ if (el0_is_kmap && entry->vme_el0_autowire &&
++ !(entry->protection & (VM_PROT_READ | VM_PROT_WRITE))) {
++ entry->vme_el0_autowire = 0;
++ if (vm_map_wire_count_sub(cur_map, entry, FALSE)) {
++ entry->zero_wired_pages = FALSE;
++ vm_fault_unwire(cur_map, entry, false, cur_map->pmap,
++ entry->vme_start, entry->vme_end);
++ }
++ }
++
++ if (entry->protection != old_prot) {
++ vm_prot_t prot = entry->protection;
++ int entry_pmap_options = pmap_options;
++
++ if (el0_is_kmap) {
++ if (entry->is_sub_map || entry->needs_copy ||
++ (VME_OBJECT(entry) != VM_OBJECT_NULL &&
++ (VME_OBJECT(entry)->shadow != VM_OBJECT_NULL ||
++ VME_OBJECT(entry)->vo_copy != VM_OBJECT_NULL))) {
++ prot &= ~VM_PROT_WRITE;
++ }
++ if (prot & VM_PROT_WRITE) {
++ entry_pmap_options |= PMAP_OPTIONS_PROTECT_IMMEDIATE;
++ }
++ } else if (entry->is_sub_map || (VME_OBJECT(entry) == NULL) ||
++ (VME_OBJECT(entry) != compressor_object)) {
++ prot &= ~VM_PROT_WRITE;
++ } else {
++ assert(!VME_OBJECT(entry)->code_signed);
++ assert(VME_OBJECT(entry)->copy_strategy == MEMORY_OBJECT_COPY_NONE);
++ if (prot & VM_PROT_WRITE) {
++ entry_pmap_options |= PMAP_OPTIONS_PROTECT_IMMEDIATE;
++ }
++ }
++
++ if (override_nx(cur_map, VME_ALIAS(entry)) && prot) {
++ prot |= VM_PROT_EXECUTE;
++ }
++
++#if DEVELOPMENT || DEBUG
++ if (!(old_prot & VM_PROT_EXECUTE) &&
++ (prot & VM_PROT_EXECUTE) &&
++ panic_on_unsigned_execute &&
++ (proc_selfcsflags() & CS_KILL)) {
++ panic("vm_map_protect(%p,0x%llx,0x%llx) old=0x%x new=0x%x - <rdar://23770418> code-signing bypass?",
++ cur_map, (uint64_t)entry->vme_start, (uint64_t)entry->vme_end, old_prot, prot);
++ }
++#endif /* DEVELOPMENT || DEBUG */
++
++ if (pmap_has_prot_policy(cur_map->pmap, entry->translated_allow_execute, prot)) {
++ if (entry->wired_count) {
++ panic("vm_map_protect(%p,0x%llx,0x%llx) new=0x%x wired=%x",
++ cur_map, (uint64_t)entry->vme_start, (uint64_t)entry->vme_end, prot, entry->wired_count);
++ }
++ prot = VM_PROT_NONE;
++ }
++
++ if (entry->is_sub_map && entry->use_pmap) {
++ pmap_protect(VME_SUBMAP(entry)->pmap,
++ entry->vme_start,
++ entry->vme_end,
++ prot);
++ } else {
++ pmap_protect_options(cur_map->pmap,
++ entry->vme_start,
++ entry->vme_end,
++ prot,
++ entry_pmap_options,
++ NULL);
++ }
+ }
-+ struct linux64_buf_req q = { .buf = buf, .len = sizeof(buf), .result = 0 };
-+ linux64_call(LINUX64_CALL_CONSOLE_READ, &q);
-+ n = q.result > 0 ? (int)q.result : 0;
-+ i = 0;
-+ return n ? (unsigned char)buf[i++] : -1;
+}
+
- void
- serial_keyboard_init(void)
- {
- kern_return_t result;
- thread_t thread;
++kern_return_t
++vm_map_protect(
++ vm_map_t original_map,
++ vm_map_offset_ut start_u,
++ vm_map_offset_ut end_u,
++ boolean_t set_max,
++ vm_prot_ut new_prot_u)
++{
++ vm_map_entry_t entry;
++ __block vm_prot_t new_prot;
++ int pmap_options = 0;
++ kern_return_t kr;
++ vm_map_offset_t start;
++ vm_map_offset_t end;
++ VM_MAP_LOCK_CTX_DECLARE(ctx);
++
++ vmlp_api_start(VM_MAP_PROTECT);
++
++ kr = vm_map_protect_sanitize(original_map,
++ start_u,
++ end_u,
++ new_prot_u,
++ &start,
++ &end,
++ &new_prot);
++ if (__improbable(kr != KERN_SUCCESS)) {
++ kr = vm_sanitize_get_kr(kr);
++ vmlp_api_end(VM_MAP_PROTECT, kr);
++ return kr;
++ }
++
++ extern unsigned int linux64_el0;
++ const bool el0_is_kmap = (linux64_el0 && original_map->pmap == kernel_pmap);
++
++ if (el0_is_kmap && !set_max && (new_prot & VM_PROT_ALLEXEC)) {
++ vmlp_api_end(VM_MAP_PROTECT, KERN_NOT_SUPPORTED);
++ return KERN_NOT_SUPPORTED;
++ }
++
++ if (new_prot & VM_PROT_COPY) {
++ if (el0_is_kmap) {
++ vmlp_api_end(VM_MAP_PROTECT, KERN_NOT_SUPPORTED);
++ return KERN_NOT_SUPPORTED;
++ }
++ vm_map_offset_t new_start;
++ vm_prot_t cur_prot, max_prot;
+ vm_map_kernel_flags_t kflags;
-- if (!(serialmode & SERIALMODE_INPUT)) { /* Leave if we do not want a serial console */
-+ if (!(serialmode & SERIALMODE_INPUT) && !linux64_hook) { /* Leave if we do not want a serial console */
- return;
+ /* LP64todo - see below */
+@@ -5869,17 +7215,6 @@ vm_map_protect(
+ return KERN_PROTECTION_FAILURE;
+ }
+
+- /*
+- * Let vm_map_remap_extract() know that it will need to:
+- * + make a copy of the mapping
+- * + add VM_PROT_WRITE to the max protections
+- * + remove any protections that are no longer allowed from the
+- * max protections (to avoid any WRITE/EXECUTE conflict, for
+- * example).
+- * Note that "max_prot" is an IN/OUT parameter only for this
+- * specific (VM_PROT_COPY) case. It's usually an OUT parameter
+- * only (and the resulting value is not used).
+- */
+ max_prot = new_prot & (VM_PROT_ALL | VM_PROT_ALLEXEC);
+ cur_prot = VM_PROT_NONE;
+ kflags = VM_MAP_KERNEL_FLAGS_FIXED(.vmf_overwrite = true);
+@@ -5931,15 +7266,28 @@ vm_map_protect(
+ end = SUPERPAGE_ROUND_UP(end);
}
-@@ -82,7 +102,7 @@ serial_keyboard_poll(void)
- uint64_t next;
++ if (el0_is_kmap && !set_max && (new_prot & (VM_PROT_READ | VM_PROT_WRITE))) {
++ vm_map_ilk_unlock(original_map);
++ kr = vm_map_wire_impl_internal(original_map,
++ vm_sanitize_wrap_addr(start),
++ vm_sanitize_wrap_addr(end),
++ vm_sanitize_wrap_prot(VM_PROT_NONE),
++ VM_KERN_MEMORY_OSFMK,
++ FALSE,
++ NULL,
++ VM_SANITIZE_CALLER_VM_MAP_WIRE,
++ true,
++ true,
++ new_prot,
++ pmap_options);
++ vmlp_api_end(VM_MAP_PROTECT, kr);
++ return kr;
++ }
++
+ vm_map_lock_ctx_set_preflight(ctx, ^kern_return_t (vm_map_lock_ctx_t vctx, vm_map_entry_t vme) {
+ return vm_map_protect_preflight(vctx, vme, set_max, &new_prot /*in/out*/);
+ });
+
+- /*
+- * This does VMRL_EX_NO_MIN_MAX_CHECK and the manual max_offset check (above) to maintain
+- * binary compatibility. That's because previously only the start address
+- * was checked, not the end.
+- */
+ kr = vm_map_range_ex_lock(ctx, &original_map, start, end,
+ VMRL_EX_ATOMIC | VMRL_EX_ILK_LOCKED | VMRL_EX_SIMPLIFY | VMRL_EX_NO_MIN_MAX_CHECK);
+ if (KERN_SUCCESS != kr) {
+@@ -5951,15 +7299,9 @@ vm_map_protect(
+ * Preflight passed, fix up the protections
+ */
+ while ((entry = vm_map_range_atomic_next(ctx))) {
+- /*
+- * No constant submap descent. Transparent submaps are okay.
+- * Then don't use variable `original_map` again inside this
+- * loop because we may be descended into a transparent submap.
+- */
+ vm_map_t cur_map = vm_map_lock_ctx_get_map(ctx);
+ assert(!vm_map_lock_ctx_in_constant_submap(ctx));
+
+- vm_prot_t old_prot;
+ #if DEVELOPMENT || DEBUG
+ if (entry->csm_associated && vm_log_xnu_user_debug) {
+ printf("FBDP %d[%s] %s(0x%llx,0x%llx,0x%x) on map %p entry %p [0x%llx:0x%llx 0x%x/0x%x] csm_associated\n",
+@@ -5980,142 +7322,15 @@ vm_map_protect(
+ #endif /* DEVELOPMENT || DEBUG */
- while (1) {
-- chr = _serial_getc(false); /* Get a character if there is one */
-+ chr = linux64_hook ? linux64_cons_getc() : _serial_getc(false); /* Get a character if there is one */
- if (chr < 0) { /* The serial buffer is empty */
- break;
+ if (entry->is_sub_map) {
+- /* range lock did unnest if needed */
+ assert(!entry->use_pmap);
}
-diff --git a/osfmk/kern/assert.h b/osfmk/kern/assert.h
-index 4224c9d..4a1fe94 100644
---- a/osfmk/kern/assert.h
-+++ b/osfmk/kern/assert.h
-@@ -193,9 +193,28 @@ STATIC_IF_KEY_DECLARE_TRUE(mach_assert);
- #define mach_assert_enabled_expr(ex) \
- (mach_assert_enabled() || __builtin_constant_p(!(ex)))
-+#if defined(XNU_KERNEL_PRIVATE) && defined(__arm64__)
-+/*
-+ * LINUX64 (xnulinux): hosted inside Linux there is no XNU exception vector for the assert brk, so a
-+ * failed assert() is reported to the host, which decides whether XNU continues or the run ends.
-+ */
-+#ifdef __cplusplus
-+extern "C" {
-+#endif
-+extern unsigned long linux64_hook;
-+extern void linux64_assert_report(const char *file, int line, const char *expr);
-+#ifdef __cplusplus
+- old_prot = entry->protection;
+-
++ vm_prot_t effective_new_prot = new_prot;
+ if (set_max) {
+ entry->max_protection = new_prot;
+- /* Consider either EXECUTE or UEXEC as EXECUTE for this masking */
+- entry->protection = (new_prot & old_prot);
+- } else {
+- entry->protection = new_prot;
+- }
+-
+-#if CODE_SIGNING_MONITOR
+- if (/* a !csm_associated mapping becoming executable */
+- ((!entry->csm_associated &&
+- !(old_prot & VM_PROT_EXECUTE) &&
+- (entry->protection & VM_PROT_EXECUTE))
+- ||
+- /* a csm_associated mapping becoming writable */
+- (entry->csm_associated &&
+- !(old_prot & VM_PROT_WRITE) &&
+- (entry->protection & VM_PROT_WRITE)))) {
+- /*
+- * This mapping has not already been marked as
+- * "user_debug" and it is either:
+- * 1. not code-signing-monitored and becoming executable
+- * 2. code-signing-monitored and becoming writable,
+- * so inform the CodeSigningMonitor and mark the
+- * mapping as "user_debug" if appropriate.
+- */
+- vm_map_kernel_flags_t vmk_flags;
+- vmk_flags = VM_MAP_KERNEL_FLAGS_NONE;
+- /* pretend it's a vm_protect(VM_PROT_COPY)... */
+- vmk_flags.vmkf_remap_prot_copy = true;
+- kr = vm_map_entry_cs_associate(cur_map, entry, vmk_flags);
+-#if DEVELOPMENT || DEBUG
+- if (vm_log_xnu_user_debug) {
+- printf("FBDP %d[%s] %s:%d map %p entry %p [ 0x%llx 0x%llx ] prot 0x%x -> 0x%x cs_associate -> %d user_debug=%d\n",
+- proc_selfpid(),
+- (get_bsdtask_info(current_task()) ? proc_name_address(get_bsdtask_info(current_task())) : "?"),
+- __FUNCTION__, __LINE__,
+- cur_map, entry,
+- entry->vme_start, entry->vme_end,
+- old_prot, entry->protection,
+- kr, entry->vme_xnu_user_debug);
+- }
+-#endif /* DEVELOPMENT || DEBUG */
+- }
+-#endif /* CODE_SIGNING_MONITOR */
+-
+- /*
+- * Update physical map if necessary.
+- * If the request is to turn off write protection,
+- * we won't do it for real (in pmap). This is because
+- * it would cause copy-on-write to fail. We've already
+- * set, the new protection in the map, so if a
+- * write-protect fault occurred, it will be fixed up
+- * properly, COW or not.
+- */
+- if (entry->protection != old_prot) {
+- /* Look one level in we support nested pmaps */
+- /* from mapped submaps which are direct entries */
+- /* in our map */
+-
+- vm_prot_t prot;
+-
+- prot = entry->protection;
+- if (entry->is_sub_map || (VME_OBJECT(entry) == NULL) || (VME_OBJECT(entry) != compressor_object)) {
+- prot &= ~VM_PROT_WRITE;
+- } else {
+- assert(!VME_OBJECT(entry)->code_signed);
+- assert(VME_OBJECT(entry)->copy_strategy == MEMORY_OBJECT_COPY_NONE);
+- if (prot & VM_PROT_WRITE) {
+- /*
+- * For write requests on the
+- * compressor, we wil ask the
+- * pmap layer to prevent us from
+- * taking a write fault when we
+- * attempt to access the mapping
+- * next.
+- */
+- pmap_options |= PMAP_OPTIONS_PROTECT_IMMEDIATE;
+- }
+- }
+-
+- if (override_nx(cur_map, VME_ALIAS(entry)) && prot) {
+- prot |= VM_PROT_EXECUTE;
+- }
+-
+-#if DEVELOPMENT || DEBUG
+- if (!(old_prot & VM_PROT_EXECUTE) &&
+- (prot & VM_PROT_EXECUTE) &&
+- panic_on_unsigned_execute &&
+- (proc_selfcsflags() & CS_KILL)) {
+- panic("vm_map_protect(%p,0x%llx,0x%llx) old=0x%x new=0x%x - <rdar://23770418> code-signing bypass?", cur_map, (uint64_t)entry->vme_start, (uint64_t)entry->vme_end, old_prot, prot);
+- }
+-#endif /* DEVELOPMENT || DEBUG */
+-
+- if (pmap_has_prot_policy(cur_map->pmap, entry->translated_allow_execute, prot)) {
+- if (entry->wired_count) {
+- panic("vm_map_protect(%p,0x%llx,0x%llx) new=0x%x wired=%x",
+- cur_map, (uint64_t)entry->vme_start, (uint64_t)entry->vme_end, prot, entry->wired_count);
+- }
+-
+- /* If the pmap layer cares about this
+- * protection type, force a fault for
+- * each page so that vm_fault will
+- * repopulate the page with the full
+- * set of protections.
+- */
+- /*
+- * TODO: We don't seem to need this,
+- * but this is due to an internal
+- * implementation detail of
+- * pmap_protect. Do we want to rely
+- * on this?
+- */
+- prot = VM_PROT_NONE;
+- }
+-
+- if (entry->is_sub_map && entry->use_pmap) {
+- pmap_protect(VME_SUBMAP(entry)->pmap,
+- entry->vme_start,
+- entry->vme_end,
+- prot);
+- } else {
+- pmap_protect_options(cur_map->pmap,
+- entry->vme_start,
+- entry->vme_end,
+- prot,
+- pmap_options,
+- NULL);
+- }
++ effective_new_prot = (new_prot & entry->protection);
+ }
++ el0_protect_apply_entry_locked(cur_map, entry, effective_new_prot, pmap_options);
+ }
+
+ vm_map_range_ex_unlock(ctx, &original_map);
+@@ -6457,11 +7672,11 @@ vm_map_wire_count_sub(vm_map_t map, vm_map_entry_t entry, bool user_wire)
+
+ entry->wired_count--;
+ vme_btref_consider_and_put(entry);
+- if (entry->wired_count <= 1) {
++ if (entry->wired_count <= (1 + ((linux64_el0 && entry->vme_el0_autowire) ? 1 : 0))) {
+ /*
+ * Wake up waiters even if the wire count is 1 because of the
+ * VM_MAP_REMOVE_KUNWIRE flag of vm_map_delete that allows a wire
+- * count to be removed there.
++ * count to be removed there (plus 1 for vme_el0_autowire).
+ *
+ * Also wakeup if the wire count is less than one.
+ */
+@@ -6753,9 +7968,12 @@ vm_map_wire_stabilize_entry_object(vm_map_t map, vm_map_entry_t entry)
+ * NOT_WIRED: nothing about the entry is wired.
+ */
+ __enum_decl(vm_wire_state_t, unsigned char, {
+- ENTRY_WIRED = 0,
+- OBJ_WIRED = 1,
+- NOT_WIRED = 2,
++ ENTRY_WIRED = 0,
++ OBJ_WIRED = 1,
++ NOT_WIRED = 2,
++ ALREADY_AUTOWIRED = 3,
++ EXT_WIRED = 4,
++ REPOPULATE_AUTOWIRED = 5,
+ });
+
+ /*
+@@ -6772,7 +7990,9 @@ typedef struct wire_copy_node {
+ vm_object_offset_t offset;
+ vm_wire_state_t wire_state;
+ bool is_sub_map;
++ bool prewire_pinned;
+ vm_object_t object;
++ vm_map_entry_t stage3_entry;
+ } *wire_copy_list_t;
+
+
+@@ -6803,6 +8023,10 @@ vm_map_wire_cleanup_wire_copy_list(struct wire_copy_list_head * head)
+ TAILQ_REMOVE(head, cur, chain);
+
+ if (!cur->is_sub_map) {
++ if (cur->prewire_pinned && cur->object != VM_OBJECT_NULL) {
++ el0_object_prewire_unpin(cur->object);
++ cur->prewire_pinned = false;
++ }
+ vm_object_deallocate(cur->object);
+ }
+ kfree_type(struct wire_copy_node, cur);
+@@ -6851,6 +8075,7 @@ clip_wire_copy_end(
+ */
+ wire_copy_list_t new_copy = kalloc_type(struct wire_copy_node, Z_WAITOK);
+ *new_copy = *cur_copy;
++ new_copy->prewire_pinned = false;
+ /* null the linkages */
+ new_copy->chain.tqe_next = NULL;
+ new_copy->chain.tqe_prev = NULL;
+@@ -6970,16 +8195,112 @@ vm_map_wire_sanitize(
+ * return KERN_SUCCESS if the preflight was successful
+ * otherwise, the preflight of space failed and we cannot wire the entry.
+ */
++static bool
++el0_entry_unpopulated_device_pager(vm_map_entry_t entry)
++{
++ if (entry->is_sub_map) {
++ return false;
++ }
++ vm_object_t obj = VME_OBJECT(entry);
++ if (obj == VM_OBJECT_NULL || !obj->private || !obj->pager_created) {
++ return false;
++ }
++ if (obj->phys_contiguous) {
++ return !obj->vo_el0_populated;
++ }
++ vm_object_offset_t start_off = VME_OFFSET(entry) + obj->paging_offset;
++ vm_object_offset_t end_off = start_off + (entry->vme_end - entry->vme_start);
++ bool missing = false;
++ vm_object_lock_shared(obj);
++ for (vm_object_offset_t off = start_off; off < end_off; off += PAGE_SIZE) {
++ if (vm_page_lookup(obj, off) == VM_PAGE_NULL) {
++ missing = true;
++ break;
++ }
++ }
++ vm_object_unlock(obj);
++ return missing;
+}
-+#endif
-+#define assert(ex) \
-+ (mach_assert_enabled_expr(ex) && !(ex) \
-+ ? (linux64_hook ? linux64_assert_report(__FILE_NAME__, __LINE__, #ex) \
-+ : (void)mach_assert_abort(#ex)) : (void)0)
-+#else
- #define assert(ex) \
- (mach_assert_enabled_expr(ex) && !(ex) \
- ? (void)mach_assert_abort(#ex) : (void)0)
-+#endif
++
++static inline bool
++el0_entry_skip_autowire(vm_map_entry_t entry, vm_prot_t effective_prot)
++{
++ if (entry->is_sub_map ||
++ !(effective_prot & (VM_PROT_READ | VM_PROT_WRITE)) ||
++ el0_entry_unpopulated_device_pager(entry)) {
++ return true;
++ }
++ vm_object_t obj = VME_OBJECT(entry);
++ return obj == VM_OBJECT_NULL || is_kernel_object(obj) || obj == compressor_object;
++}
++
++static inline bool
++el0_can_stabilize_symmetric_in_place_locked(
++ vm_map_t map,
++ vm_map_entry_t entry,
++ vm_object_t vobj)
++{
++ vm_map_size_t entry_size = entry->vme_end - entry->vme_start;
++ return !vm_map_always_shadow(map) &&
++ !entry->needs_copy &&
++ VME_OFFSET(entry) == 0 &&
++ vobj->vo_size == entry_size &&
++ os_ref_get_count_raw(&vobj->ref_count) == 1 &&
++ vobj->vo_copy == VM_OBJECT_NULL &&
++ (vobj->shadow == VM_OBJECT_NULL ||
++ vobj->shadow->vo_copy == VM_OBJECT_NULL);
++}
++
++static bool
++el0_entry_requires_in_place_symmetric_stabilize(vm_map_t map, vm_map_entry_t entry)
++{
++ if (entry->wired_count != 0) {
++ return true;
++ }
++ if (!(entry->protection & VM_PROT_WRITE)) {
++ return false;
++ }
++ vm_prot_t check_prot = (entry->protection & VM_PROT_READ) ?
++ VM_PROT_WRITE : VM_PROT_READ;
++ vm_map_size_t eff_pgsz = MIN(VM_MAP_PAGE_SIZE(map), PAGE_SIZE);
++ for (vm_map_offset_t va = entry->vme_start; va < entry->vme_end; va += eff_pgsz) {
++ if (pmap_el0_kmap_pte_ready(map->pmap, va, check_prot)) {
++ return true;
++ }
++ }
++ return false;
++}
++
++static bool
++el0_entry_missing_pte(vm_map_t map, vm_map_entry_t entry, vm_prot_t req_prot)
++{
++ if (el0_entry_skip_autowire(entry, req_prot)) {
++ return false;
++ }
++ vm_prot_t check_prot = req_prot & (VM_PROT_READ | VM_PROT_WRITE);
++ vm_map_size_t eff_pgsz = MIN(VM_MAP_PAGE_SIZE(map), PAGE_SIZE);
++ for (vm_map_offset_t va = entry->vme_start; va < entry->vme_end; va += eff_pgsz) {
++ if (!pmap_el0_kmap_pte_ready(map->pmap, va, check_prot) &&
++ !vm_fault_el0_entry_va_skip_pte(map, entry, va)) {
++ return true;
++ }
++ }
++ return false;
++}
++
+ static kern_return_t
+ vm_map_wire_copy_entry_and_preflight_space(
+ vm_map_t map,
+ vm_map_entry_t entry,
+ bool user_wire,
++ bool el0_autowire,
++ vm_prot_t el0_effective_prot,
+ struct wire_copy_list_head *copy_list,
+ vm_map_size_t * const size_that_would_be_wired)
+ {
+ kern_return_t kr;
+ wire_copy_list_t wire_copy = kalloc_type(struct wire_copy_node, Z_WAITOK);
++ wire_copy->prewire_pinned = false;
- #define assertf(ex, fmt, args...) ({ \
- if (mach_assert_enabled_expr(ex) && __builtin_expect(!(ex), 0L)) { \
-diff --git a/osfmk/kern/backtrace.c b/osfmk/kern/backtrace.c
-index 77044be..2c195af 100644
---- a/osfmk/kern/backtrace.c
-+++ b/osfmk/kern/backtrace.c
-@@ -48,7 +48,7 @@
- #include <arm64/mte.h>
- #endif // HAS_MTE
+ /*
+ * If we don't need to wire the pages,
+@@ -6988,7 +8309,28 @@ vm_map_wire_copy_entry_and_preflight_space(
+ * Also increment the wire count.
+ */
+ bool entry_already_wired = entry->wired_count != 0;
+- if (entry_already_wired) {
++ if (el0_autowire) {
++ if (el0_entry_skip_autowire(entry, el0_effective_prot)) {
++ wire_copy->wire_state = ALREADY_AUTOWIRED;
++ } else if (entry->vme_el0_autowire) {
++ wire_copy->wire_state = el0_entry_missing_pte(map, entry, el0_effective_prot) ?
++ REPOPULATE_AUTOWIRED : ALREADY_AUTOWIRED;
++ } else if (entry_already_wired) {
++ /*
++ * Defer wire_count_add, PTE population, and vme_el0_autowire
++ * to Stage 3 under the exclusive range lock so concurrent
++ * readers never observe vme_el0_autowire before PTEs exist.
++ */
++ wire_copy->wire_state = EXT_WIRED;
++ } else {
++ kr = vm_map_preflight_wire_space(map, entry, user_wire, size_that_would_be_wired);
++ if (kr != KERN_SUCCESS) {
++ kfree_type(struct wire_copy_node, wire_copy);
++ return kr;
++ }
++ wire_copy->wire_state = NOT_WIRED;
++ }
++ } else if (entry_already_wired) {
+ kr = vm_map_wire_count_add(map, entry, user_wire);
+ if (kr != KERN_SUCCESS) {
+ kfree_type(struct wire_copy_node, wire_copy);
+@@ -7008,16 +8350,19 @@ vm_map_wire_copy_entry_and_preflight_space(
+ wire_copy->end = entry->vme_end;
+ wire_copy->offset = VME_OFFSET(entry);
+ wire_copy->is_sub_map = entry->is_sub_map;
++ wire_copy->stage3_entry = VM_MAP_ENTRY_NULL;
+ if (entry->is_sub_map) {
+ /*
+ * We don't actually do anything to wire submaps.
+ * Just mark it as wired without doing anything.
+ */
+- wire_copy->wire_state = ENTRY_WIRED;
++ wire_copy->wire_state = el0_autowire ? ALREADY_AUTOWIRED : ENTRY_WIRED;
+ wire_copy->object = VM_OBJECT_NULL;
+ } else {
+ wire_copy->object = VME_OBJECT(entry);
+- vm_object_reference(VME_OBJECT(entry));
++ if (wire_copy->object != VM_OBJECT_NULL) {
++ vm_object_reference(wire_copy->object);
++ }
+ }
--#if __x86_64__
-+#if __x86_64__ || __arm64__ /* LINUX64: hosted, a kernel stack also has frames in Linux's text, beyond 32 bits of stext */
- static void
- _backtrace_packed_out_of_reach(void)
+ TAILQ_INSERT_TAIL(copy_list, wire_copy, chain);
+@@ -7055,8 +8400,8 @@ int wire_restarts_due_to_kernel_wiring;
+ * @param prot_u - the protections the entry must have. A mapping with all
+ * the protections of the corresponding entry will still be entered into the pmap.
+ */
+-kern_return_t
+-vm_map_wire_impl(
++static kern_return_t
++vm_map_wire_impl_internal(
+ vm_map_t original_map,
+ vm_map_offset_ut start_u,
+ vm_map_offset_ut end_u,
+@@ -7064,7 +8409,11 @@ vm_map_wire_impl(
+ vm_tag_t tag,
+ boolean_t user_wire,
+ ppnum_t *physpage_p,
+- vm_sanitize_caller_t vm_sanitize_caller)
++ vm_sanitize_caller_t vm_sanitize_caller,
++ bool el0_autowire,
++ bool el0_protect_apply,
++ vm_prot_t el0_protect_new_prot,
++ int el0_protect_pmap_options)
{
-@@ -58,7 +58,7 @@ _backtrace_packed_out_of_reach(void)
- //
- // This is an Intel only issue.
- }
--#endif // __x86_64__
-+#endif // __x86_64__ || __arm64__
+ /*
+ * original_map is the map passed in by the caller.
+@@ -7083,9 +8432,14 @@ vm_map_wire_impl(
+ wire_copy_list_t cur_copy;
+ bool need_restart = false;
+ uint32_t wire_restarts = 0;
++ __block vm_prot_t el0_new_prot = el0_protect_new_prot;
+ struct wire_copy_list_head copy_list;
+ TAILQ_INIT(&copy_list);
+ VM_MAP_LOCK_CTX_DECLARE(ctx);
++ kern_return_t (^el0_protect_preflight_blk)(vm_map_lock_ctx_t, vm_map_entry_t) =
++ ^kern_return_t (vm_map_lock_ctx_t vctx, vm_map_entry_t vme) {
++ return vm_map_protect_preflight(vctx, vme, false, &el0_new_prot);
++ };
+
+ vmlp_api_start(VM_MAP_WIRE_IMPL);
+ /*
+@@ -7110,6 +8464,7 @@ vm_map_wire_impl(
+ }
- // Pack an address according to a particular packing format.
- static size_t
-@@ -74,7 +74,7 @@ _backtrace_pack_addr(backtrace_pack_t packing, uint8_t *dst, size_t dst_size,
- case BTP_KERN_OFFSET_32:;
- uintptr_t addr_delta = addr - vm_kernel_stext;
- int32_t addr_packed = (int32_t)addr_delta;
--#if __x86_64__
-+#if __x86_64__ || __arm64__
- if ((uintptr_t)(int32_t)addr_delta != addr_delta) {
- addr = (vm_offset_t)&_backtrace_packed_out_of_reach;
- addr_delta = addr - vm_kernel_stext;
-diff --git a/osfmk/kern/debug.c b/osfmk/kern/debug.c
-index 0eae1f6..8d31f1d 100644
---- a/osfmk/kern/debug.c
-+++ b/osfmk/kern/debug.c
-@@ -55,6 +55,7 @@
- */
+ restart:
++ el0_new_prot = el0_protect_new_prot;
+ /* Include ALLEXEC so that we don't silently drop the UEXEC bit if we're on Intel */
+ access_type = (caller_prot & (VM_PROT_ALL | VM_PROT_ALLEXEC));
- #include <mach_assert.h>
-+#include <linux64/linux64.h>
- #include <mach_kdp.h>
- #include <kdp/kdp.h>
- #include <kdp/kdp_core.h>
-@@ -754,7 +755,20 @@ DebuggerTrapWithState(debugger_op db_op, const char *db_message, const char *db_
- * The rest of the cores are halted by IPI if possible; if that
- * fails it will fall back to dbgwrap.
+@@ -7128,17 +8483,21 @@ restart:
+ *physpage_p = 0;
+ }
+
+- if (wire_and_extract) {
++ if (el0_protect_apply) {
++ ctx->vmlc_preflight = el0_protect_preflight_blk;
++ } else if (wire_and_extract) {
+ ctx->vmlc_preflight = ^kern_return_t (vm_map_lock_ctx_t vctx, vm_map_entry_t vme) {
+ return vm_map_wire_and_extract_preflight(vctx, vme, access_type);
+ };
+ } else {
+ ctx->vmlc_preflight = ^kern_return_t (vm_map_lock_ctx_t vctx, vm_map_entry_t vme) {
+- return vm_map_wire_preflight(vctx, vme, access_type);
++ return vm_map_wire_preflight(vctx, vme, el0_autowire ? VM_PROT_NONE : access_type);
+ };
+ }
+
+- VM_MAP_CLAMP_TO_MAP_BOUNDS(original_map, start, end);
++ if (!el0_protect_apply) {
++ VM_MAP_CLAMP_TO_MAP_BOUNDS(original_map, start, end);
++ }
+ assert(VM_MAP_PAGE_ALIGNED(start, VM_MAP_PAGE_MASK(original_map)));
+ assert(VM_MAP_PAGE_ALIGNED(end, VM_MAP_PAGE_MASK(original_map)));
+ if (start == end) {
+@@ -7149,6 +8508,9 @@ restart:
+
+ /* We want an atomic lock that resolves CoW and unnests submaps */
+ flags = VMRL_EX_ATOMIC | VMRL_EX_RESOLVE_COW_AND_OBJ;
++ if (el0_protect_apply) {
++ flags |= VMRL_EX_NO_MIN_MAX_CHECK;
++ }
+ if (user_wire) {
+ /* And user wires should be interruptible */
+ flags |= VMRL_EX_INTERRUPTIBLE;
+@@ -7173,9 +8535,74 @@ restart:
*/
-+ {
+ cur_map = vm_map_lock_ctx_get_map(ctx);
+
++ if (el0_autowire) {
+ /*
-+ * LINUX64 (xnulinux): the hosted kernel's exceptions are taken by Linux, which does not hand XNU this trap
-+ * (an uncategorized exception), so a stackshot (spindump, tailspin, sysdiagnose) ended the whole run. The
-+ * stackshot needs no trap frame (handle_debugger_trap takes it with do_stackshot(NULL)) and there is one CPU:
-+ * call the handler here, as the trap would (kdp_trap -> handle_debugger_trap).
++ * Stage 1 Pass 1A (read-only): validate the full range before
++ * mutating any object or stabilizing any entry.
+ */
-+ if (linux64_hook && db_op == DBOP_STACKSHOT) {
-+ handle_debugger_trap(0, 0, 0, NULL); /* the exception number only matters for breakpoints */
-+ goto trapped;
++ while ((entry = vm_map_range_atomic_next(ctx))) {
++ vm_prot_t el0_eff_prot = el0_protect_apply ? el0_new_prot : entry->protection;
++ if (el0_eff_prot & VM_PROT_ALLEXEC) {
++ vm_map_range_ex_unlock(ctx, &original_map);
++ vmlp_api_end(VM_MAP_WIRE_IMPL, KERN_NOT_SUPPORTED);
++ return KERN_NOT_SUPPORTED;
++ }
++ if (!entry->is_sub_map && VME_OBJECT(entry) != VM_OBJECT_NULL) {
++ vm_object_t vobj = VME_OBJECT(entry);
++ if (el0_protect_apply &&
++ !el0_object_range_supported(vobj, VME_OFFSET(entry),
++ entry->vme_end - entry->vme_start, entry->vme_start, false, true)) {
++ vm_map_range_ex_unlock(ctx, &original_map);
++ vmlp_api_end(VM_MAP_WIRE_IMPL, KERN_NOT_SUPPORTED);
++ return KERN_NOT_SUPPORTED;
++ }
++ if (!el0_entry_skip_autowire(entry, el0_eff_prot)) {
++ if (cur_map->never_faults &&
++ !vm_fault_el0_never_faults_entry_supported(entry, el0_eff_prot)) {
++ vm_map_range_ex_unlock(ctx, &original_map);
++ vmlp_api_end(VM_MAP_WIRE_IMPL, KERN_NOT_SUPPORTED);
++ return KERN_NOT_SUPPORTED;
++ }
++ if (el0_entry_requires_in_place_symmetric_stabilize(cur_map, entry)) {
++ vm_object_lock_shared(vobj);
++ bool reject_sym =
++ (vobj->copy_strategy == MEMORY_OBJECT_COPY_SYMMETRIC &&
++ !el0_can_stabilize_symmetric_in_place_locked(cur_map, entry, vobj));
++ vm_object_unlock(vobj);
++ if (reject_sym) {
++ vm_map_range_ex_unlock(ctx, &original_map);
++ vmlp_api_end(VM_MAP_WIRE_IMPL, KERN_NOT_SUPPORTED);
++ return KERN_NOT_SUPPORTED;
++ }
++ }
++ }
++ }
+ }
++ vm_map_range_atomic_reset(ctx);
+ }
- TRAP_DEBUGGER;
-+trapped:
-
- ret = CPUDEBUGGERRET;
++
+ size_that_would_be_wired = 0;
+ while ((entry = vm_map_range_atomic_next(ctx))) {
+- if (!entry->is_sub_map) {
++ vm_prot_t el0_eff_prot = el0_protect_apply ? el0_new_prot : entry->protection;
++ if (!entry->is_sub_map &&
++ !(el0_autowire && el0_entry_skip_autowire(entry, el0_eff_prot))) {
++ if (el0_autowire && el0_entry_requires_in_place_symmetric_stabilize(cur_map, entry) &&
++ VME_OBJECT(entry) != VM_OBJECT_NULL) {
++ vm_object_t vobj = VME_OBJECT(entry);
++ vm_object_lock(vobj);
++ if (vobj->copy_strategy == MEMORY_OBJECT_COPY_SYMMETRIC) {
++ if (!el0_can_stabilize_symmetric_in_place_locked(cur_map, entry, vobj)) {
++ vm_object_unlock(vobj);
++ vm_map_range_ex_unlock(ctx, &original_map);
++ kr = KERN_NOT_SUPPORTED;
++ goto wire_error_unlocked;
++ }
++ VM_OBJECT_SET_SHADOWED(vobj, FALSE);
++ vobj->copy_strategy = MEMORY_OBJECT_COPY_DELAY;
++ VM_OBJECT_SET_TRUE_SHARE(vobj, TRUE);
++ }
++ vm_object_unlock(vobj);
++ }
+ /*
+ * First, stabilize the entry's object so it will
+ * not change without a deletion
+@@ -7190,7 +8617,9 @@ restart:
+ * NOT_WIRED if the entry wasn't previously wired.
+ */
+ kr = vm_map_wire_copy_entry_and_preflight_space(cur_map,
+- entry, user_wire, &copy_list, &size_that_would_be_wired);
++ entry, user_wire, el0_autowire,
++ el0_protect_apply ? el0_new_prot : entry->protection,
++ &copy_list, &size_that_would_be_wired);
+ if (kr != KERN_SUCCESS) {
+ vm_map_range_ex_unlock(ctx, &original_map);
+
+@@ -7206,8 +8635,11 @@ restart:
+ * To do this, wire all the pages in our copies.
+ */
+ TAILQ_FOREACH(cur_copy, &copy_list, chain) {
+- if (cur_copy->wire_state == ENTRY_WIRED) {
+- /* We already wired it. Don't do anything */
++ if (cur_copy->wire_state == ENTRY_WIRED ||
++ cur_copy->wire_state == ALREADY_AUTOWIRED ||
++ cur_copy->wire_state == EXT_WIRED ||
++ cur_copy->wire_state == REPOPULATE_AUTOWIRED) {
++ /* We already wired it or deferred to Stage 3. Don't do anything */
+ continue;
+ }
-@@ -1253,6 +1267,26 @@ panic_trap_to_debugger(const char *panic_format_str, va_list *panic_args, unsign
- {
- #pragma clang diagnostic pop
+@@ -7218,6 +8650,11 @@ restart:
+ interrupt_level = THREAD_UNINT;
+ }
+ assert(!cur_copy->is_sub_map);
++ kr = el0_object_prewire_pin(cur_copy->object);
++ if (kr != KERN_SUCCESS) {
++ goto wire_error_unlocked;
++ }
++ cur_copy->prewire_pinned = true;
+ kr = vm_fault_wire_object_pages(cur_map, cur_copy->object, cur_copy->offset,
+ cur_copy->end - cur_copy->start, tag, interrupt_level);
+ if (kr != KERN_SUCCESS) {
+@@ -7231,6 +8668,7 @@ restart:
+ * Transition our copies from OBJ_WIRED -> ENTRY_WIRED
+ * Update the wire count and fault the wired pages
+ */
++ el0_new_prot = el0_protect_new_prot;
+ kr = vm_map_range_ex_lock(ctx, &original_map, start, end, flags | VMRL_EX_SIMPLIFY);
+ if (kr != KERN_SUCCESS) {
+ goto wire_error_unlocked;
+@@ -7241,243 +8679,1125 @@ restart:
+ panic("transparent submap configuration unexpectedly changed during vm_map_wire");
+ }
-+#if defined(__arm64__)
-+ {
-+ /* LINUX64 (xnulinux): report the panic to the host (see arm_init.c). */
-+ if (linux64_hook) {
-+ /* the formatted message when there are arguments (the format string alone otherwise) */
-+ static char linux64_panic_buf[512];
-+ const char *msg = panic_format_str;
-+ if (panic_args != NULL && panic_format_str != NULL) {
-+ extern int vsnprintf(char *, size_t, const char *, va_list);
-+ va_list ap;
-+ va_copy(ap, *panic_args);
-+ vsnprintf(linux64_panic_buf, sizeof(linux64_panic_buf), panic_format_str, ap);
-+ va_end(ap);
-+ msg = linux64_panic_buf;
+- cur_copy = TAILQ_FIRST(&copy_list);
+- while ((entry = vm_map_range_atomic_next(ctx))) {
+- bool faulted_pages = false;
++ if (el0_protect_apply) {
+ /*
+- * Clip the end so we have the guarantee an entry
+- * and the copy are of the same size. This prevents
+- * an entry corresponding to two copies in different
+- * states (invalid), or a copy corresponding to two different
+- * entries (not inherently invalid, but makes the accounting trickier)
+- *
+- * Note we only need to clip the end, as that will clip the start
+- * of the next entry. The range lock guarantees the first copy
+- * and the first entry start at the same address.
++ * Read-only Verify Pass: validate all entries before publishing
++ * any entry->protection or wire_count changes.
+ */
+- assert(cur_copy->start == entry->vme_start);
+- clip_wire_copy_end(&copy_list, cur_copy, entry->vme_end);
+- vm_map_range_lock_clip_end(ctx, entry, cur_copy->end);
+-
+- assert(cur_copy->wire_state != NOT_WIRED);
+-
+- if (cur_copy->wire_state == OBJ_WIRED) {
+- if (vm_entry_obj_and_offs_match(entry, cur_copy)) {
+- bool entry_already_wired = entry->wired_count != 0;
+- if (entry_already_wired) {
+- /*
+- * Someone raced us and wired the entry.
+- * We therefore want to undo the object wiring we did before.
+- */
+- vm_fault_unwire_object_pages(cur_map, cur_copy->object,
+- cur_copy->offset, cur_copy->end - cur_copy->start);
+- cur_copy->wire_state = NOT_WIRED;
++ if (el0_new_prot & VM_PROT_ALLEXEC) {
++ kr = KERN_NOT_SUPPORTED;
++ goto el0_stage3_abort_locked;
++ }
++ cur_copy = TAILQ_FIRST(&copy_list);
++ while ((entry = vm_map_range_atomic_next(ctx))) {
++ if (cur_copy == NULL) {
++ need_restart = true;
++ goto el0_stage3_abort_locked;
+ }
-+ linux64_call2(LINUX64_CALL_PANIC, (unsigned long)msg, panic_caller);
++ if (cur_copy->start != entry->vme_start ||
++ cur_copy->is_sub_map != entry->is_sub_map ||
++ (!entry->is_sub_map && !vm_entry_obj_and_offs_match(entry, cur_copy)) ||
++ (cur_copy->end < entry->vme_end && entry->vme_atomic)) {
++ need_restart = true;
++ goto el0_stage3_abort_locked;
++ }
++ clip_wire_copy_end(&copy_list, cur_copy, entry->vme_end);
++ vm_map_range_lock_clip_end(ctx, entry, cur_copy->end);
++
++ if (!entry->is_sub_map && VME_OBJECT(entry) != VM_OBJECT_NULL &&
++ !el0_object_range_supported(VME_OBJECT(entry), VME_OFFSET(entry),
++ entry->vme_end - entry->vme_start, entry->vme_start, false, true)) {
++ kr = KERN_NOT_SUPPORTED;
++ goto el0_stage3_abort_locked;
++ }
++ bool skip = el0_entry_skip_autowire(entry, el0_new_prot);
++ if (!skip && cur_map->never_faults) {
++ if ((el0_new_prot & VM_PROT_WRITE) && !cur_copy->prewire_pinned) {
++ kr = el0_object_prewire_pin(cur_copy->object);
++ if (kr != KERN_SUCCESS) {
++ goto el0_stage3_abort_locked;
++ }
++ cur_copy->prewire_pinned = true;
+ }
+-
+- kr = vm_map_wire_count_add(cur_map, entry, user_wire);
+- if (kr != KERN_SUCCESS) {
+- vm_map_range_ex_unlock(ctx, &original_map);
+- cur_copy->wire_state = NOT_WIRED;
+-
+- goto wire_error_unlocked;
++ if (!vm_fault_el0_never_faults_entry_supported(entry, el0_new_prot)) {
++ kr = KERN_NOT_SUPPORTED;
++ goto el0_stage3_abort_locked;
++ }
++ }
++ if (cur_copy->wire_state == ALREADY_AUTOWIRED) {
++ if (!skip && (!entry->vme_el0_autowire ||
++ el0_entry_missing_pte(cur_map, entry, el0_new_prot))) {
++ need_restart = true;
++ goto el0_stage3_abort_locked;
++ }
++ } else if (cur_copy->wire_state == REPOPULATE_AUTOWIRED) {
++ if (!skip && !entry->vme_el0_autowire) {
++ need_restart = true;
++ goto el0_stage3_abort_locked;
++ }
++ } else if (cur_copy->wire_state == EXT_WIRED) {
++ if (!skip && !entry->vme_el0_autowire && entry->wired_count == 0) {
++ need_restart = true;
++ goto el0_stage3_abort_locked;
++ }
++ }
++ if (!skip && !entry->vme_el0_autowire && entry->wired_count >= MAX_WIRE_COUNT) {
++ kr = KERN_RESOURCE_SHORTAGE;
++ goto el0_stage3_abort_locked;
++ }
++ cur_copy = TAILQ_NEXT(cur_copy, chain);
++ }
++ if (cur_copy != NULL) {
++ need_restart = true;
++ goto el0_stage3_abort_locked;
++ }
++
++ /*
++ * Commit Pass: publish entry protections and finalize autowire/PTEs.
++ */
++ vm_map_range_atomic_reset(ctx);
++ cur_copy = TAILQ_FIRST(&copy_list);
++ while ((entry = vm_map_range_atomic_next(ctx))) {
++ assert(cur_copy != NULL && cur_copy->start == entry->vme_start &&
++ cur_copy->end == entry->vme_end);
++ el0_protect_apply_entry_locked(cur_map, entry, el0_new_prot,
++ el0_protect_pmap_options);
++
++ bool skip = el0_entry_skip_autowire(entry, entry->protection);
++ vm_prot_t res_prot = entry->protection & (VM_PROT_READ | VM_PROT_WRITE);
++ if (skip) {
++ if (cur_copy->wire_state == OBJ_WIRED) {
++ vm_fault_unwire_object_pages(cur_map, cur_copy->object,
++ cur_copy->offset, cur_copy->end - cur_copy->start);
++ }
++ cur_copy->wire_state = ALREADY_AUTOWIRED;
++ } else if (cur_copy->wire_state == ALREADY_AUTOWIRED) {
++ if (el0_entry_missing_pte(cur_map, entry, entry->protection)) {
++ kr = vm_fault_el0_populate_wired_entry(cur_map, entry, res_prot, tag, ctx);
++ if (kr != KERN_SUCCESS) {
++ panic("linux64_el0: vm_map_protect commit failed map=%p [0x%llx,0x%llx) prot=0x%x kr=%d",
++ cur_map, (unsigned long long)entry->vme_start,
++ (unsigned long long)entry->vme_end, (unsigned int)res_prot, kr);
++ }
++ }
++ } else if (cur_copy->wire_state == REPOPULATE_AUTOWIRED) {
++ kr = vm_fault_el0_populate_wired_entry(cur_map, entry, res_prot, tag, ctx);
++ if (kr != KERN_SUCCESS) {
++ panic("linux64_el0: vm_map_protect commit failed map=%p [0x%llx,0x%llx) prot=0x%x kr=%d",
++ cur_map, (unsigned long long)entry->vme_start,
++ (unsigned long long)entry->vme_end, (unsigned int)res_prot, kr);
++ }
++ cur_copy->wire_state = ALREADY_AUTOWIRED;
++ } else if (cur_copy->wire_state == EXT_WIRED) {
++ if (entry->vme_el0_autowire) {
++ if (el0_entry_missing_pte(cur_map, entry, entry->protection)) {
++ kr = vm_fault_el0_populate_wired_entry(cur_map, entry, res_prot, tag, ctx);
++ if (kr != KERN_SUCCESS) {
++ panic("linux64_el0: vm_map_protect commit failed map=%p [0x%llx,0x%llx) prot=0x%x kr=%d",
++ cur_map, (unsigned long long)entry->vme_start,
++ (unsigned long long)entry->vme_end, (unsigned int)res_prot, kr);
++ }
++ }
++ cur_copy->wire_state = ALREADY_AUTOWIRED;
++ } else {
++ kr = vm_fault_el0_populate_wired_entry(cur_map, entry, res_prot, tag, ctx);
++ if (kr != KERN_SUCCESS) {
++ panic("linux64_el0: vm_map_protect commit failed map=%p [0x%llx,0x%llx) prot=0x%x kr=%d",
++ cur_map, (unsigned long long)entry->vme_start,
++ (unsigned long long)entry->vme_end, (unsigned int)res_prot, kr);
++ }
++ kr = vm_map_wire_count_add(cur_map, entry, user_wire);
++ if (kr != KERN_SUCCESS) {
++ panic("linux64_el0: vm_map_protect commit failed map=%p [0x%llx,0x%llx) prot=0x%x kr=%d",
++ cur_map, (unsigned long long)entry->vme_start,
++ (unsigned long long)entry->vme_end, (unsigned int)res_prot, kr);
++ }
++ entry->vme_el0_autowire = 1;
++ cur_copy->stage3_entry = entry;
++ cur_copy->wire_state = ENTRY_WIRED;
++ }
++ } else if (cur_copy->wire_state == OBJ_WIRED) {
++ if (entry->vme_el0_autowire) {
++ vm_fault_unwire_object_pages(cur_map, cur_copy->object,
++ cur_copy->offset, cur_copy->end - cur_copy->start);
++ cur_copy->wire_state = ALREADY_AUTOWIRED;
++ if (el0_entry_missing_pte(cur_map, entry, entry->protection)) {
++ kr = vm_fault_el0_populate_wired_entry(cur_map, entry, res_prot, tag, ctx);
++ if (kr != KERN_SUCCESS) {
++ panic("linux64_el0: vm_map_protect commit failed map=%p [0x%llx,0x%llx) prot=0x%x kr=%d",
++ cur_map, (unsigned long long)entry->vme_start,
++ (unsigned long long)entry->vme_end, (unsigned int)res_prot, kr);
++ }
++ }
++ } else {
++ bool entry_already_wired = entry->wired_count != 0;
++ if (entry_already_wired) {
++ vm_fault_unwire_object_pages(cur_map, cur_copy->object,
++ cur_copy->offset, cur_copy->end - cur_copy->start);
++ cur_copy->wire_state = NOT_WIRED;
++ kr = vm_fault_el0_populate_wired_entry(cur_map, entry, res_prot, tag, ctx);
++ if (kr != KERN_SUCCESS) {
++ panic("linux64_el0: vm_map_protect commit failed map=%p [0x%llx,0x%llx) prot=0x%x kr=%d",
++ cur_map, (unsigned long long)entry->vme_start,
++ (unsigned long long)entry->vme_end, (unsigned int)res_prot, kr);
++ }
++ }
++ kr = vm_map_wire_count_add(cur_map, entry, user_wire);
++ if (kr != KERN_SUCCESS) {
++ panic("linux64_el0: vm_map_protect commit failed map=%p [0x%llx,0x%llx) prot=0x%x kr=%d",
++ cur_map, (unsigned long long)entry->vme_start,
++ (unsigned long long)entry->vme_end, (unsigned int)res_prot, kr);
++ }
++ if (!entry_already_wired) {
++ kr = vm_fault_wire_resident_pages(cur_map, entry, res_prot, tag, physpage_p, ctx);
++ if (kr != KERN_SUCCESS) {
++ panic("linux64_el0: vm_map_protect commit failed map=%p [0x%llx,0x%llx) prot=0x%x kr=%d",
++ cur_map, (unsigned long long)entry->vme_start,
++ (unsigned long long)entry->vme_end, (unsigned int)res_prot, kr);
++ }
++ }
++ entry->vme_el0_autowire = 1;
++ cur_copy->stage3_entry = entry;
++ cur_copy->wire_state = ENTRY_WIRED;
++ }
++ }
++ cur_copy = TAILQ_NEXT(cur_copy, chain);
+ }
++
++ vm_map_range_ex_unlock(ctx, &original_map);
++ vm_map_wire_cleanup_wire_copy_list(&copy_list);
++ vmlp_api_end(VM_MAP_WIRE_IMPL, KERN_SUCCESS);
++ return KERN_SUCCESS;
+ }
-+#endif
+
- #if defined(__x86_64__) && (DEVELOPMENT || DEBUG)
- read_lbr();
- #endif
-diff --git a/osfmk/kern/kext_alloc.c b/osfmk/kern/kext_alloc.c
-index 119c6c7..f3e43a6 100644
---- a/osfmk/kern/kext_alloc.c
-+++ b/osfmk/kern/kext_alloc.c
-@@ -26,6 +26,7 @@
- * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
- */
- #include <kern/assert.h>
-+#include <linux64/linux64.h>
- #include <kern/debug.h>
- #include <kern/kext_alloc.h>
- #include <kern/misc_protos.h>
-@@ -218,6 +219,18 @@ check_reachable:
- }
- #endif
-
-+ {
++ cur_copy = TAILQ_FIRST(&copy_list);
++ while ((entry = vm_map_range_atomic_next(ctx))) {
++ bool faulted_pages = false;
+ /*
-+ * LINUX64 (xnulinux): hosted XNU has no page-fault path of its own yet (Linux takes the abort), so kext
-+ * memory is wired up front instead of faulted in on first touch.
++ * Clip the end so we have the guarantee an entry
++ * and the copy are of the same size. This prevents
++ * an entry corresponding to two copies in different
++ * states (invalid), or a copy corresponding to two different
++ * entries (not inherently invalid, but makes the accounting trickier)
++ *
++ * Note we only need to clip the end, as that will clip the start
++ * of the next entry. The range lock guarantees the first copy
++ * and the first entry start at the same address.
+ */
-+ if (linux64_hook) {
-+ kern_return_t wr = vm_map_wire_kernel(g_kext_map, addr, addr + size, VM_PROT_DEFAULT, VM_KERN_MEMORY_KEXT, FALSE);
-+ if (wr != KERN_SUCCESS) {
-+ printf("linux64: kext_alloc wire failed %d\n", wr);
++ assert(cur_copy->start == entry->vme_start);
++ clip_wire_copy_end(&copy_list, cur_copy, entry->vme_end);
++ vm_map_range_lock_clip_end(ctx, entry, cur_copy->end);
++
++ if (el0_autowire && (entry->protection & VM_PROT_ALLEXEC)) {
++ kr = KERN_NOT_SUPPORTED;
++ goto el0_stage3_abort_locked;
++ }
++
++ assert(cur_copy->wire_state != NOT_WIRED);
++
++ if (cur_copy->wire_state == REPOPULATE_AUTOWIRED) {
++ assert(el0_autowire);
++ if (vm_entry_obj_and_offs_match(entry, cur_copy)) {
++ if (!entry->vme_el0_autowire) {
++ need_restart = true;
++ goto el0_stage3_abort_locked;
++ } else if (el0_entry_skip_autowire(entry, entry->protection)) {
++ cur_copy->wire_state = ALREADY_AUTOWIRED;
++ } else {
++ vm_prot_t res_prot = entry->protection & (VM_PROT_READ | VM_PROT_WRITE);
++ kr = vm_fault_el0_populate_wired_entry(cur_map, entry, res_prot, tag, ctx);
++ if (kr != KERN_SUCCESS) {
++ goto el0_stage3_abort_locked;
++ }
++ cur_copy->wire_state = ALREADY_AUTOWIRED;
++ }
++ } else {
++ if (!user_wire && vm_kernel_map_is_kernel(cur_map)) {
++ __vm_map_wire_kernel_deletion_panic(cur_map, start,
++ end, entry->vme_start, entry->vme_end);
++ } else if (!user_wire) {
++ need_restart = true;
++ goto el0_stage3_abort_locked;
++ }
++ cur_copy->wire_state = NOT_WIRED;
++ }
++ } else if (cur_copy->wire_state == EXT_WIRED) {
++ assert(el0_autowire);
++ if (vm_entry_obj_and_offs_match(entry, cur_copy)) {
++ if (el0_entry_skip_autowire(entry, entry->protection)) {
++ cur_copy->wire_state = ALREADY_AUTOWIRED;
++ } else if (entry->vme_el0_autowire) {
++ if (el0_entry_missing_pte(cur_map, entry, entry->protection)) {
++ vm_prot_t res_prot = entry->protection & (VM_PROT_READ | VM_PROT_WRITE);
++ kr = vm_fault_el0_populate_wired_entry(cur_map, entry, res_prot, tag, ctx);
++ if (kr != KERN_SUCCESS) {
++ goto el0_stage3_abort_locked;
++ }
++ }
++ cur_copy->wire_state = ALREADY_AUTOWIRED;
++ } else if (entry->wired_count == 0) {
++ /* External wire disappeared between Stage 1 and Stage 3. */
++ need_restart = true;
++ goto el0_stage3_abort_locked;
++ } else if (entry->wired_count >= MAX_WIRE_COUNT) {
++ kr = KERN_RESOURCE_SHORTAGE;
++ goto el0_stage3_abort_locked;
++ } else {
++ vm_prot_t res_prot = entry->protection & (VM_PROT_READ | VM_PROT_WRITE);
++ kr = vm_fault_el0_populate_wired_entry(cur_map, entry, res_prot, tag, ctx);
++ if (kr != KERN_SUCCESS) {
++ goto el0_stage3_abort_locked;
++ }
++ kr = vm_map_wire_count_add(cur_map, entry, user_wire);
++ if (kr != KERN_SUCCESS) {
++ goto el0_stage3_abort_locked;
++ }
++ entry->vme_el0_autowire = 1;
++ cur_copy->stage3_entry = entry;
++ cur_copy->wire_state = ENTRY_WIRED;
++ }
++ } else {
++ if (!user_wire && vm_kernel_map_is_kernel(cur_map)) {
++ __vm_map_wire_kernel_deletion_panic(cur_map, start,
++ end, entry->vme_start, entry->vme_end);
++ } else if (!user_wire) {
++ need_restart = true;
++ goto el0_stage3_abort_locked;
++ }
++ cur_copy->wire_state = NOT_WIRED;
++ }
++ } else if (cur_copy->wire_state == OBJ_WIRED) {
++ if (vm_entry_obj_and_offs_match(entry, cur_copy)) {
++ if (el0_autowire &&
++ el0_entry_skip_autowire(entry, entry->protection)) {
++ vm_fault_unwire_object_pages(cur_map, cur_copy->object,
++ cur_copy->offset, cur_copy->end - cur_copy->start);
++ cur_copy->wire_state = ALREADY_AUTOWIRED;
++ } else if (el0_autowire && entry->vme_el0_autowire) {
++ vm_fault_unwire_object_pages(cur_map, cur_copy->object,
++ cur_copy->offset, cur_copy->end - cur_copy->start);
++ cur_copy->wire_state = ALREADY_AUTOWIRED;
++ if (el0_entry_missing_pte(cur_map, entry, entry->protection)) {
++ vm_prot_t res_prot = entry->protection & (VM_PROT_READ | VM_PROT_WRITE);
++ kr = vm_fault_el0_populate_wired_entry(cur_map, entry, res_prot, tag, ctx);
++ if (kr != KERN_SUCCESS) {
++ goto el0_stage3_abort_locked;
++ }
++ }
++ } else if (el0_autowire && entry->wired_count >= MAX_WIRE_COUNT) {
++ kr = KERN_RESOURCE_SHORTAGE;
++ goto el0_stage3_abort_locked;
++ } else {
++ bool entry_already_wired = entry->wired_count != 0;
++ vm_prot_t res_prot = el0_autowire ?
++ (entry->protection & (VM_PROT_READ | VM_PROT_WRITE)) : caller_prot;
++ if (entry_already_wired) {
++ /*
++ * Someone raced us and wired the entry.
++ * We therefore want to undo the object wiring we did before.
++ */
++ vm_fault_unwire_object_pages(cur_map, cur_copy->object,
++ cur_copy->offset, cur_copy->end - cur_copy->start);
++ cur_copy->wire_state = NOT_WIRED;
++ if (el0_autowire) {
++ kr = vm_fault_el0_populate_wired_entry(cur_map,
++ entry, res_prot, tag, ctx);
++ if (kr != KERN_SUCCESS) {
++ goto el0_stage3_abort_locked;
++ }
++ }
++ }
++
++ kr = vm_map_wire_count_add(cur_map, entry, user_wire);
++ if (kr != KERN_SUCCESS) {
++ if (!entry_already_wired) {
++ /* Keep OBJ_WIRED so wire_error_unlocked unwires Stage 2 pages. */
++ goto el0_stage3_abort_locked;
++ }
++ cur_copy->wire_state = NOT_WIRED;
++ goto el0_stage3_abort_locked;
++ }
++
++ if (!entry_already_wired) {
++ kr = vm_fault_wire_resident_pages(cur_map,
++ entry, res_prot, tag, physpage_p, ctx);
++ if (kr != KERN_SUCCESS) {
++ /*
++ * on error, vm_fault_wire_resident_pages
++ * unwires everything in the range
++ */
++ vm_map_wire_count_sub(cur_map, entry, user_wire);
++ cur_copy->wire_state = NOT_WIRED;
++ goto el0_stage3_abort_locked;
++ }
++ faulted_pages = true;
++ }
++ if (el0_autowire) {
++ entry->vme_el0_autowire = 1;
++ cur_copy->stage3_entry = entry;
++ }
++ cur_copy->wire_state = ENTRY_WIRED;
++ }
++ } else {
++ /*
++ * Some intermediate deletion happened.
++ * Unless otherwise noted, pretend that
++ * deletion happened after the wiring.
++ * That means the new memory would be unwired by the
++ * deletion and thus not need to be wired by this call.
++ */
++ if (!user_wire && vm_kernel_map_is_kernel(cur_map)) {
++ /*
++ * Kernel initiated wire that raced against deletion
++ * on the kernel map
++ * This is a bug, and thus we should panic
++ */
++ __vm_map_wire_kernel_deletion_panic(cur_map, start,
++ end, entry->vme_start, entry->vme_end);
++ } else if (!user_wire) {
++ /*
++ * Kernel initiated wire that raced against deletion
++ * on a user map.
++ * We can't say the deletion happened after the wiring,
++ * because the deletion would have waited for the wire
++ * count to go to zero.
++ * That means we have to pretend the deletion happened
++ * before the wiring.
++ * That means we need to restart from the top.
++ * goto the error path to drop all our state
++ * and let it restart.
++ */
++ need_restart = true;
++ goto el0_stage3_abort_locked;
++ }
++
++ vm_fault_unwire_object_pages(cur_map, cur_copy->object,
++ cur_copy->offset, cur_copy->end - cur_copy->start);
++ cur_copy->wire_state = NOT_WIRED;
++ }
++ }
++ assert(cur_copy->wire_state == ENTRY_WIRED || cur_copy->wire_state == NOT_WIRED ||
++ cur_copy->wire_state == ALREADY_AUTOWIRED);
++
++ /*
++ * If we didn't already get the ppnum from faulting the pages,
++ * get it now.
++ */
++ if (!faulted_pages && wire_and_extract) {
++ assert(!entry->is_sub_map); // enforced by preflight
++ if (cur_copy->wire_state == NOT_WIRED) {
++ kr = KERN_INVALID_ADDRESS;
++ goto el0_stage3_abort_locked;
+ }
++ *physpage_p = get_page_for_wire_and_extract(entry);
++ }
++
++ cur_copy = TAILQ_NEXT(cur_copy, chain);
++ }
++
++ vm_map_range_ex_unlock(ctx, &original_map);
++
++ /* cleanup our copies */
++ vm_map_wire_cleanup_wire_copy_list(&copy_list);
++ vmlp_api_end(VM_MAP_WIRE_IMPL, KERN_SUCCESS);
++ return KERN_SUCCESS;
++
++el0_stage3_abort_locked:
++ if (el0_autowire) {
++ wire_copy_list_t unwind;
++ TAILQ_FOREACH(unwind, &copy_list, chain) {
++ if (unwind->wire_state == ENTRY_WIRED &&
++ unwind->stage3_entry != VM_MAP_ENTRY_NULL) {
++ vm_map_entry_t ue = unwind->stage3_entry;
++ ue->vme_el0_autowire = 0;
++ if (vm_map_wire_count_sub(cur_map, ue, FALSE)) {
++ assert(!ue->is_sub_map);
++ ue->zero_wired_pages = FALSE;
++ vm_fault_unwire(cur_map, ue, false, cur_map->pmap,
++ ue->vme_start, ue->vme_end);
++ }
++ unwind->stage3_entry = VM_MAP_ENTRY_NULL;
++ unwind->wire_state = NOT_WIRED;
++ }
++ }
++ }
++ vm_map_range_ex_unlock(ctx, &original_map);
++ goto wire_error_unlocked;
++
++wire_error_unlocked:
++ /*
++ * Note that this error path cannot be _locked, as we will wire
++ * entries in stage 1 and then drop it for stage 2. Therefore there is
++ * some path to this where the range lock is dropped
++ * and we later need to unwire entries.
++ *
++ * There are 3 states a copy can be in:
++ * 1) ENTRY_WIRED: We already wired the entry, so unwire that same range.
++ * 2) OBJ_WIRED: The obj is wired, so unwire it.
++ * 3) NOT_WIRED: nothing to do
++ */
++ assert(kr != KERN_SUCCESS || need_restart);
++
++ TAILQ_FOREACH(cur_copy, &copy_list, chain) {
++ if (cur_copy->wire_state == ENTRY_WIRED) {
++ if (!cur_copy->is_sub_map) {
++ assert(!el0_autowire);
++ vm_map_unwire(cur_map, cur_copy->start, cur_copy->end,
++ user_wire);
++ }
++ } else if (cur_copy->wire_state == OBJ_WIRED) {
++ mach_vm_size_t size = cur_copy->end - cur_copy->start;
++ assert(!cur_copy->is_sub_map);
++ vm_fault_unwire_object_pages(cur_map, cur_copy->object,
++ cur_copy->offset, size);
+ }
+ }
- /* Check that the memory is reachable by kernel text */
- if ((addr + size) > kext_alloc_max) {
- kext_free((vm_offset_t)addr, size);
-diff --git a/osfmk/kern/link_compat.c b/osfmk/kern/link_compat.c
-index e494eab..fc40514 100644
---- a/osfmk/kern/link_compat.c
-+++ b/osfmk/kern/link_compat.c
-@@ -65,3 +65,40 @@ native_verified_block_manifest_sha384(unsigned int device, const char *uuid, uin
- }
-
- #endif
+
-+/*
-+ * LINUX64 (xnulinux): macOS 27 kernel functions that 27.2's RTBuddy kext imports and xnu-12377 does not have.
-+ * The hosted kernel has no coprocessors; both are no-ops.
-+ */
-+int os_log_coprocessor_with_handle(void);
-+int
-+os_log_coprocessor_with_handle(void)
++ vm_map_wire_cleanup_wire_copy_list(&copy_list);
++
++ if (need_restart) {
++ /*
++ * We need to restart, but want to do exponential backoff from
++ * mutex_pause to prevent an attacker from causing us to busy
++ * loop in the kernel.
++ * We expect in practice hitting this is uncommon as we never
++ * hit this race in months of testing a branch that panicked here
++ * instead.
++ */
++ mutex_pause(wire_restarts);
++ /* overflow isn't a problem, this is used for backoff only */
++ wire_restarts++;
++ need_restart = false;
++#if DEBUG || DEVELOPMENT
++ os_atomic_add(&wire_restarts_due_to_kernel_wiring, 1, relaxed);
++#endif /* DEBUG || DEVELOPMENT */
++ goto restart;
++ }
++
++ vmlp_api_end(VM_MAP_WIRE_IMPL, kr);
++
++ return kr;
++}
++
++kern_return_t
++vm_map_wire_impl(
++ vm_map_t original_map,
++ vm_map_offset_ut start_u,
++ vm_map_offset_ut end_u,
++ vm_prot_ut prot_u,
++ vm_tag_t tag,
++ boolean_t user_wire,
++ ppnum_t *physpage_p,
++ vm_sanitize_caller_t vm_sanitize_caller)
+{
-+ return 0;
++ return vm_map_wire_impl_internal(original_map, start_u, end_u, prot_u,
++ tag, user_wire, physpage_p, vm_sanitize_caller,
++ false, false, VM_PROT_NONE, 0);
+}
+
-+int os_metric_coprocessor(void);
-+int
-+os_metric_coprocessor(void)
++kern_return_t
++vm_map_wire_el0_autowire(
++ vm_map_t map,
++ vm_map_offset_t start,
++ vm_map_offset_t end)
+{
-+ return 0;
++ return vm_map_wire_impl_internal(map,
++ vm_sanitize_wrap_addr(start),
++ vm_sanitize_wrap_addr(end),
++ vm_sanitize_wrap_prot(VM_PROT_NONE),
++ VM_KERN_MEMORY_OSFMK,
++ FALSE,
++ NULL,
++ VM_SANITIZE_CALLER_VM_MAP_WIRE,
++ true,
++ false,
++ VM_PROT_NONE,
++ 0);
+}
+
-+/*
-+ * LINUX64 (xnulinux): the two functions of compiler-rt's profile runtime that OSKext's kext PGO collection calls. Without
-+ * them the link takes the runtime's objects from the toolchain's libclang_rt.cc_kext archive, Apple's binary. No kext
-+ * here is built with profiling; one that is gets size 0 and EIO.
-+ */
-+uint64_t __llvm_profile_get_size_for_buffer_internal(void);
-+uint64_t
-+__llvm_profile_get_size_for_buffer_internal(void)
++kern_return_t
++vm_map_wire_external(
++ vm_map_t map,
++ vm_map_offset_ut start_u,
++ vm_map_offset_ut end_u,
++ vm_prot_ut prot_u,
++ boolean_t user_wire)
+{
-+ return 0;
++ vm_tag_t tag = vm_tag_bt();
++
++ return vm_map_wire_kernel(map, start_u, end_u, prot_u, tag, user_wire);
+}
+
-+int __llvm_profile_write_buffer_internal(void);
-+int
-+__llvm_profile_write_buffer_internal(void)
++__mockable kern_return_t
++vm_map_wire_kernel(
++ vm_map_t map,
++ vm_map_offset_ut start_u,
++ vm_map_offset_ut end_u,
++ vm_prot_ut prot_u,
++ vm_tag_t tag,
++ boolean_t user_wire)
+{
-+ return -1;
++ return vm_map_wire_impl(map, start_u, end_u, prot_u, tag,
++ user_wire, NULL, VM_SANITIZE_CALLER_VM_MAP_WIRE);
+}
-diff --git a/osfmk/kern/printf.c b/osfmk/kern/printf.c
-index 2fc6931..d581670 100644
---- a/osfmk/kern/printf.c
-+++ b/osfmk/kern/printf.c
-@@ -155,6 +155,7 @@
- */
-
- #include <debug.h>
-+#include <linux64/linux64.h>
- #include <mach_kdp.h>
- #include <mach/boolean.h>
- #include <kern/cpu_number.h>
-@@ -876,6 +877,20 @@ __printflike(1, 0)
- static int
- vprintf_internal(const char *fmt, va_list ap_in, void *caller)
- {
-+ {
-+ /* LINUX64 (xnulinux): hosted XNU prints through the host (dmesg), like kprintf. */
-+ if (linux64_hook && fmt) {
-+ extern int vsnprintf(char *, size_t, const char *, va_list);
-+ char buf[256];
-+ va_list ap;
-+ va_copy(ap, ap_in);
-+ vsnprintf(buf, sizeof(buf), fmt, ap);
-+ va_end(ap);
-+ linux64_call(LINUX64_CALL_KPRINTF, buf);
-+ (void)caller;
-+ return 0;
-+ }
++
++#if XNU_PLATFORM_MacOSX
++
++kern_return_t
++vm_map_wire_and_extract(
++ vm_map_t map,
++ vm_map_offset_ut start_u,
++ vm_prot_ut prot_u,
++ boolean_t user_wire,
++ ppnum_t *physpage_p)
++{
++ vm_tag_t tag = vm_tag_bt();
++ vm_map_size_ut size_u = vm_sanitize_wrap_size(VM_MAP_PAGE_SIZE(map));
++ vm_map_offset_ut end_u = vm_sanitize_compute_ut_end(start_u, size_u);
++
++ return vm_map_wire_impl(map, start_u, end_u, prot_u, tag,
++ user_wire, physpage_p, VM_SANITIZE_CALLER_VM_MAP_WIRE);
++}
++
++#endif /* XNU_PLATFORM_MacOSX */
++
++kern_return_t
++vm_map_unwire(
++ vm_map_t map,
++ vm_map_offset_ut start_u,
++ vm_map_offset_ut end_u,
++ boolean_t user_wire)
++{
++ return vm_map_unwire_impl(map, start_u, end_u, user_wire,
++ VM_SANITIZE_CALLER_VM_MAP_UNWIRE);
++}
++
++kern_return_t
++vm_map_el0_set_cache_mode(
++ vm_map_t map,
++ mach_vm_address_t va,
++ unsigned int wimg_flags,
++ bool use_default)
++{
++ if (!linux64_el0 || map == VM_MAP_NULL || map->pmap != kernel_pmap) {
++ return KERN_INVALID_ARGUMENT;
+ }
- if (fmt) {
- struct console_printbuf_state info_data;
-
-diff --git a/osfmk/kern/sched_prim.c b/osfmk/kern/sched_prim.c
-index b2aae03..af01ff3 100644
---- a/osfmk/kern/sched_prim.c
-+++ b/osfmk/kern/sched_prim.c
-@@ -65,6 +65,7 @@
- */
-
- #include <kern/sched_prim.h>
-+#include <linux64/linux64.h>
-
- #if !SCHED_TEST_HARNESS
-
-@@ -3010,6 +3011,7 @@ thread_invoke(
-
- thread_continue_t continuation = self->continuation;
- void *parameter = self->parameter;
-+ linux64_count(LINUX64_CTR_SWITCHES); linux64_dbg[LINUX64_CTR_THREAD] = (unsigned long)thread; /* LINUX64: for the host's monitor */
-
- struct recount_snap snap = { 0 };
- recount_snapshot(&snap);
-@@ -6452,6 +6454,7 @@ processor_idle(
- recount_processor_idle(&processor->pr_recount, &snap);
-
- while (1) {
-+ linux64_count(LINUX64_CTR_IDLE_THREAD); /* LINUX64: for the host's monitor */
- /*
- * Ensure that updates to my processor and pset state,
- * made by the IPI source processor before sending the IPI,
-@@ -9984,3 +9987,45 @@ sysctl_clutch_thread_group_cpu_time_for_thread(__unused thread_t thread,
- #endif /* !SCHED_TEST_HARNESS */
-
- #endif /* DEVELOPMENT || DEBUG */
++ vm_map_offset_t page_va = vm_map_trunc_page(va, VM_MAP_PAGE_MASK(map));
++ VM_MAP_FIND_LOCK_CTX_DECLARE(ctx);
++ vm_map_t orig_map = map;
++ kern_return_t kr = vm_map_find_entry_ex_locked(ctx, &orig_map, page_va,
++ VMRL_FIND_EX_DEFAULT);
++ if (kr != KERN_SUCCESS) {
++ return kr;
++ }
++ vm_map_t locked_map = vm_map_lock_ctx_get_map(ctx);
++ vm_map_entry_t entry = vm_map_found_entry_get_entry(ctx);
++ if (VME_IS_SENTINEL(entry) || entry->is_sub_map ||
++ VME_OBJECT(entry) == VM_OBJECT_NULL) {
++ vm_map_found_entry_ex_unlock(ctx, &orig_map);
++ return KERN_INVALID_ARGUMENT;
++ }
++ kr = pmap_el0_update_cache_mode(locked_map->pmap, page_va, wimg_flags, use_default);
++ if (kr == KERN_SUCCESS) {
++ vm_object_t obj = VME_OBJECT(entry);
++ vm_object_lock(obj);
++ obj->set_cache_attr = TRUE;
++ vm_object_unlock(obj);
++ }
++ vm_map_found_entry_ex_unlock(ctx, &orig_map);
++ return kr;
++}
+
-+/*
-+ * 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)
++linux64_el0_release_autowire_range(
++ vm_map_t map,
++ mach_vm_address_t addr,
++ mach_vm_size_t len)
+{
-+ thread_t t;
-+ int n = 0;
-+ extern int proc_pid(struct proc *);
-+ queue_iterate(&threads, t, thread_t, threads) {
-+ if (++n > 400) {
++ if (!linux64_el0 || map == VM_MAP_NULL || map->pmap != kernel_pmap || len == 0) {
++ return;
++ }
++ vm_map_offset_t map_mask = VM_MAP_PAGE_MASK(map);
++ vm_map_offset_t start = vm_map_trunc_page(addr, map_mask);
++ vm_map_offset_t end_raw = 0;
++ if (os_add_overflow(addr, len, &end_raw)) {
++ return;
++ }
++ vm_map_offset_t end = vm_map_round_page(end_raw, map_mask);
++ if (end <= start) {
++ return;
++ }
++
++ VM_MAP_LOCK_CTX_DECLARE(ctx);
++ vm_map_t cur_map = map;
++ kern_return_t kr = vm_map_range_ex_lock(ctx, &cur_map, start, end, VMRL_EX_STREAM);
++ if (kr != KERN_SUCCESS) {
++ return;
++ }
++ vm_map_entry_t entry;
++ while ((entry = vm_map_range_next_with_error(ctx, &kr))) {
++ if (!VME_IS_SENTINEL(entry) && !entry->is_sub_map &&
++ entry->vme_el0_autowire) {
++ entry->vme_el0_autowire = 0;
++ if (vm_map_wire_count_sub(ctx->vmlc_map, entry, FALSE)) {
++ entry->zero_wired_pages = FALSE;
++ vm_fault_unwire(ctx->vmlc_map, entry, false, ctx->vmlc_map->pmap,
++ entry->vme_start, entry->vme_end);
++ }
++ }
++ }
++ vm_map_range_ex_unlock(ctx, &cur_map);
++}
++
++struct linux64_el0_mem_entry_chunk {
++ ipc_port_t port;
++ vm_object_offset_t offset;
++ vm_map_size_t size;
++ vm_map_size_t map_size;
++ vm_prot_t prot;
++ vm_tag_t tag;
++ bool return_data_addr;
++ bool check_data_addr;
++ vm_map_address_t expected_data_addr;
++ vm_prot_t cache_perm;
++ vm_map_address_t data_addr_out;
++};
++
++static bool
++el0_atomic_segs_grow(
++ struct el0_atomic_seg **segs_p,
++ size_t *cap_p,
++ size_t need)
++{
++ if (need <= *cap_p) {
++ return true;
++ }
++ size_t new_cap = (*cap_p == 0) ? 16 : *cap_p;
++ while (new_cap < need) {
++ if (os_mul_overflow(new_cap, 2, &new_cap)) {
++ return false;
++ }
++ }
++ size_t new_bytes = 0;
++ if (os_mul_overflow(new_cap, sizeof(struct el0_atomic_seg), &new_bytes)) {
++ return false;
++ }
++ struct el0_atomic_seg *nb = kalloc_type(struct el0_atomic_seg, new_cap, Z_WAITOK | Z_ZERO);
++ if (nb == NULL) {
++ return false;
++ }
++ if (*segs_p != NULL) {
++ size_t old_bytes = (*cap_p) * sizeof(struct el0_atomic_seg);
++ bcopy(*segs_p, nb, old_bytes);
++ kfree_type(struct el0_atomic_seg, *cap_p, *segs_p);
++ }
++ *segs_p = nb;
++ *cap_p = new_cap;
++ return true;
++}
++
++kern_return_t
++linux64_el0_map_mem_entries_overwrite(
++ vm_map_t target_map,
++ vm_map_address_t base_addr,
++ vm_map_size_t total_map_size,
++ struct linux64_el0_mem_entry_chunk *chunks,
++ size_t nchunks,
++ vm_prot_t prot,
++ vm_tag_t tag,
++ bool iokit_acct,
++ bool mte_aware)
++{
++ if (!linux64_el0 || target_map == VM_MAP_NULL || target_map->pmap != kernel_pmap ||
++ chunks == NULL || nchunks == 0 || total_map_size == 0) {
++ return KERN_INVALID_ARGUMENT;
++ }
++#if !HAS_MTE
++ (void)mte_aware;
++#endif
++ vm_map_offset_t map_mask = VM_MAP_PAGE_MASK(target_map);
++ vm_prot_t cur_prot = prot & ~VM_PROT_IS_MASK;
++ vm_prot_t max_prot = cur_prot;
++#if __arm64__
++ if (cur_prot & VM_PROT_EXECUTE) {
++ cur_prot |= VM_PROT_READ;
++ max_prot |= VM_PROT_READ;
++ }
++#endif
++ struct el0_atomic_seg *segs = NULL;
++ size_t seg_cap = 0;
++ size_t n_segs = 0;
++ vm_map_address_t cur_va = base_addr;
++ kern_return_t kr = KERN_SUCCESS;
++
++ for (size_t c = 0; c < nchunks && kr == KERN_SUCCESS; c++) {
++ ipc_port_t port = chunks[c].port;
++ if (!IP_VALID(port) || ip_type(port) != IKOT_NAMED_ENTRY) {
++ kr = KERN_INVALID_OBJECT;
+ break;
+ }
-+ void *bp = get_bsdthreadtask_info(t);
-+ if (bp == NULL || proc_pid((struct proc *)bp) == 0) {
-+ /* the kernel's own threads: only those blocked with a saved stack (not parked on a continuation) */
-+ if (t->continuation != NULL || t->kernel_stack == 0) {
-+ continue;
++ if (chunks[c].size == 0 || chunks[c].map_size == 0 ||
++ !VM_MAP_PAGE_ALIGNED(chunks[c].map_size, map_mask)) {
++ kr = KERN_INVALID_ARGUMENT;
++ break;
++ }
++ vm_prot_t chunk_cur_prot = (chunks[c].prot != 0) ? (chunks[c].prot & ~VM_PROT_IS_MASK) : cur_prot;
++ vm_prot_t chunk_max_prot = chunk_cur_prot;
++#if __arm64__
++ if (chunk_cur_prot & VM_PROT_EXECUTE) {
++ chunk_cur_prot |= VM_PROT_READ;
++ chunk_max_prot |= VM_PROT_READ;
++ }
++#endif
++ vm_tag_t chunk_tag = (chunks[c].tag != 0) ? chunks[c].tag : tag;
++
++ vm_named_entry_t named_entry = mach_memory_entry_from_port(port);
++ named_entry_lock(named_entry);
++
++ if ((named_entry->protection & chunk_cur_prot) != chunk_cur_prot) {
++ named_entry_unlock(named_entry);
++ kr = KERN_INVALID_RIGHT;
++ break;
++ }
++ unsigned int req_access = MAP_MEM_NOOP;
++ if (chunks[c].cache_perm != 0) {
++ if ((chunks[c].cache_perm & (MAP_MEM_USE_DATA_ADDR | MAP_MEM_4K_DATA_ADDR)) ||
++ !named_entry->is_object) {
++ named_entry_unlock(named_entry);
++ kr = KERN_INVALID_ARGUMENT;
++ break;
++ }
++ req_access = GET_MAP_MEM(chunks[c].cache_perm);
++ if ((req_access != MAP_MEM_NOOP && req_access != named_entry->access) &&
++ !(named_entry->protection & VM_PROT_WRITE)) {
++ named_entry_unlock(named_entry);
++ kr = KERN_INVALID_RIGHT;
++ break;
+ }
-+ kprintf("linux64 proc 0 kernel_task\n");
-+ } else {
-+ kprintf("linux64 proc %d %s\n", proc_pid((struct proc *)bp), proc_name_address((struct proc *)bp));
+ }
-+ struct arm_kernel_saved_state *ss = (struct arm_kernel_saved_state *)(void *)t->machine.kstackptr;
-+ uint64_t lr = 0, fp = 0;
-+ if (ss != NULL && t->kernel_stack != 0) {
-+ lr = ss->lr | 0xffffff8000000000ULL;
-+ fp = ss->fp;
++ unsigned int effective_access = (req_access != MAP_MEM_NOOP) ? req_access : named_entry->access;
++
++ vm_object_offset_t obj_offs = chunks[c].offset;
++ if (named_entry->is_copy || chunks[c].return_data_addr) {
++ if (os_add_overflow(obj_offs, named_entry->data_offset, &obj_offs)) {
++ named_entry_unlock(named_entry);
++ kr = KERN_INVALID_ARGUMENT;
++ break;
++ }
+ }
-+ kprintf("linux64 thread %p tid %llu state 0x%x pri %d wait %p cont %p lr 0x%llx\n",
-+ t, t->thread_id, t->state, t->sched_pri, (void *)t->wait_event, (void *)t->continuation, lr);
-+ for (int f = 0; f < 14 && fp != 0 && t->kernel_stack != 0 &&
-+ fp >= t->kernel_stack && fp < t->kernel_stack + kernel_stack_size; f++) {
-+ uint64_t *frame = (uint64_t *)fp;
-+ kprintf("linux64 frame 0x%llx\n", frame[1] | 0xffffff8000000000ULL);
-+ fp = frame[0];
++ vm_object_offset_t obj_end = 0;
++ if (os_add_overflow(obj_offs, chunks[c].size, &obj_end) ||
++ obj_end > named_entry->size) {
++ named_entry_unlock(named_entry);
++ kr = KERN_INVALID_ARGUMENT;
++ break;
++ }
++ if (named_entry->offset) {
++ if (os_add_overflow(obj_offs, named_entry->offset, &obj_offs)) {
++ named_entry_unlock(named_entry);
++ kr = KERN_INVALID_ARGUMENT;
++ break;
++ }
++ }
++
++ vm_map_kernel_flags_t base_flags = {
++ .vmf_fixed = true,
++ .vmf_overwrite = true,
++ .vm_tag = chunk_tag,
++ .vmkf_iokit_acct = iokit_acct,
++ };
++#if HAS_MTE
++ if (mte_aware) {
++ base_flags.vmf_mte = true;
++ }
++#endif
++
++ if (named_entry->is_sub_map) {
++ if (chunks[c].return_data_addr) {
++ named_entry_unlock(named_entry);
++ kr = KERN_INVALID_ARGUMENT;
++ break;
++ }
++ vm_map_t submap = named_entry->backing.map;
++ vm_map_reference(submap);
++ named_entry_unlock(named_entry);
++
++ if (!el0_atomic_segs_grow(&segs, &seg_cap, n_segs + 1)) {
++ vm_map_deallocate(submap);
++ kr = KERN_RESOURCE_SHORTAGE;
++ break;
++ }
++ base_flags.vmkf_submap = true;
++ segs[n_segs].va = cur_va;
++ segs[n_segs].size = chunks[c].map_size;
++ segs[n_segs].object = (vm_object_t)(uintptr_t)submap;
++ segs[n_segs].offset = obj_offs;
++ segs[n_segs].cur_protection = chunk_cur_prot;
++ segs[n_segs].max_protection = chunk_max_prot;
++ segs[n_segs].inheritance = VM_INHERIT_NONE;
++ segs[n_segs].vmk_flags = base_flags;
++ segs[n_segs].is_submap = true;
++ segs[n_segs].needs_copy = false;
++ segs[n_segs].iokit_acct = false;
++ n_segs++;
++ chunks[c].data_addr_out = cur_va;
++ if (chunks[c].check_data_addr &&
++ chunks[c].data_addr_out != chunks[c].expected_data_addr) {
++ kr = KERN_INVALID_ARGUMENT;
++ break;
++ }
++ if (os_add_overflow(cur_va, chunks[c].map_size, &cur_va)) {
++ kr = KERN_INVALID_ARGUMENT;
++ break;
++ }
++ } else if (named_entry->is_object) {
++ vm_map_offset_t oim = 0;
++ if (chunks[c].return_data_addr) {
++ oim = obj_offs & map_mask;
++ obj_offs -= oim;
++ }
++ vm_object_t obj = vm_named_entry_to_vm_object(named_entry);
++ assert(obj != VM_OBJECT_NULL);
++ vm_object_lock(obj);
++ named_entry_unlock(named_entry);
++
++ uint8_t target_wimg = obj->wimg_bits;
++ if (req_access != MAP_MEM_NOOP) {
++ vm_prot_to_wimg(req_access, &target_wimg);
++ }
++ bool seg_wimg_override = (!obj->phys_contiguous && req_access != MAP_MEM_NOOP && !obj->nophyscache);
++ uint8_t effective_wimg = seg_wimg_override ? target_wimg : obj->wimg_bits;
++ if (!pmap_el0_wimg_supported(effective_wimg) ||
++ (req_access != MAP_MEM_NOOP && !pmap_el0_wimg_supported(target_wimg))) {
++ vm_object_unlock(obj);
++ kr = KERN_NOT_SUPPORTED;
++ break;
++ }
++ if (req_access != MAP_MEM_NOOP && !obj->nophyscache && obj->wimg_bits != target_wimg) {
++#if HAS_MTE
++ if (vm_object_is_mte_mappable(obj)) {
++ vm_object_unlock(obj);
++ kr = KERN_INVALID_ARGUMENT;
++ break;
++ }
++#endif
++ }
++ vm_object_reference_locked(obj);
++ vm_object_unlock(obj);
++
++ if (!el0_atomic_segs_grow(&segs, &seg_cap, n_segs + 1)) {
++ vm_object_deallocate(obj);
++ kr = KERN_RESOURCE_SHORTAGE;
++ break;
++ }
++ segs[n_segs].va = cur_va;
++ segs[n_segs].size = chunks[c].map_size;
++ segs[n_segs].object = obj;
++ segs[n_segs].offset = obj_offs;
++ segs[n_segs].cur_protection = chunk_cur_prot;
++ segs[n_segs].max_protection = chunk_max_prot;
++ segs[n_segs].inheritance = VM_INHERIT_NONE;
++ segs[n_segs].vmk_flags = base_flags;
++ segs[n_segs].is_submap = false;
++ segs[n_segs].needs_copy = false;
++ segs[n_segs].iokit_acct = iokit_acct;
++ segs[n_segs].wimg_will_override = seg_wimg_override;
++ n_segs++;
++ chunks[c].data_addr_out = cur_va + oim;
++ if (chunks[c].check_data_addr &&
++ chunks[c].data_addr_out != chunks[c].expected_data_addr) {
++ kr = KERN_INVALID_ARGUMENT;
++ break;
++ }
++ if (os_add_overflow(cur_va, chunks[c].map_size, &cur_va)) {
++ kr = KERN_INVALID_ARGUMENT;
++ break;
++ }
++ } else if (named_entry->is_copy) {
++ vm_map_copy_t copy_map = named_entry->backing.copy;
++ vm_map_copy_require(copy_map);
++ if (copy_map->type != VM_MAP_COPY_ENTRY_LIST) {
++ named_entry_unlock(named_entry);
++ kr = KERN_INVALID_ARGUMENT;
++ break;
++ }
++ vm_map_offset_t oim = chunks[c].return_data_addr ? (obj_offs & map_mask) : 0;
++ vm_map_copy_t target_copy_map = VM_MAP_COPY_NULL;
++ vm_map_offset_t overmap_start = 0, overmap_end = 0, trimmed_start = 0;
++ kr = vm_map_copy_adjust_to_target(copy_map, obj_offs, chunks[c].size,
++ target_map, FALSE, &target_copy_map,
++ &overmap_start, &overmap_end, &trimmed_start);
++ if (kr != KERN_SUCCESS) {
++ named_entry_unlock(named_entry);
++ break;
++ }
++ vm_map_size_t target_size = vm_map_round_page(target_copy_map->size, map_mask);
++ if (target_size != chunks[c].map_size) {
++ named_entry_unlock(named_entry);
++ if (target_copy_map != copy_map) {
++ vm_map_copy_discard(target_copy_map);
++ }
++ kr = KERN_INVALID_ARGUMENT;
++ break;
++ }
++ vm_map_address_t chunk_start_va = cur_va;
++ for (vm_map_entry_t ce = vm_map_copy_first_entry(target_copy_map);
++ ce != vm_map_copy_to_entry(target_copy_map);
++ ce = ce->vme_next) {
++ vm_map_size_t csz = ce->vme_end - ce->vme_start;
++ vm_object_t co = VM_OBJECT_NULL;
++ vm_object_offset_t coff = VME_OFFSET(ce);
++ boolean_t do_copy = FALSE;
++
++ if ((cur_va - chunk_start_va) + csz > chunks[c].map_size) {
++ kr = KERN_INVALID_ARGUMENT;
++ break;
++ }
++ if (ce->is_sub_map) {
++ vm_map_t submap = VME_SUBMAP(ce);
++ vm_map_reference(submap);
++ co = (vm_object_t)(uintptr_t)submap;
++ } else {
++ co = VME_OBJECT(ce);
++ if (co != VM_OBJECT_NULL) {
++ do_copy = ce->needs_copy;
++ if (co->copy_strategy == MEMORY_OBJECT_COPY_SYMMETRIC) {
++ bool is_writable = (ce->protection & VM_PROT_WRITE) != 0;
++#if __arm64e__
++ if (ce->used_for_tpro) {
++ is_writable = true;
++ }
++#endif
++ if (!co->shadowed) {
++ vm_object_lock(co);
++ VM_OBJECT_SET_SHADOWED(co, TRUE);
++ vm_object_unlock(co);
++ }
++ VME_OBJECT_SHADOW(ce, csz, TRUE);
++ assert(co != VME_OBJECT(ce));
++ if (!ce->needs_copy && is_writable) {
++ vm_prot_t rprot = ce->protection & ~VM_PROT_WRITE;
++ vm_object_pmap_protect(co, coff, csz,
++ PMAP_NULL, PAGE_SIZE, 0, rprot);
++ }
++ ce->needs_copy = FALSE;
++ do_copy = FALSE;
++ ce->is_shared = TRUE;
++ co = VME_OBJECT(ce);
++ coff = VME_OFFSET(ce);
++ vm_object_lock(co);
++ co->copy_strategy = MEMORY_OBJECT_COPY_DELAY;
++ VM_OBJECT_SET_TRUE_SHARE(co, TRUE);
++ } else {
++ vm_object_lock(co);
++ }
++ vm_object_mark_shared(co, VM_SHARE_TYPE_PERMANENT);
++ vm_object_unlock(co);
++ vm_object_reference(co);
++ }
+ }
+-
+- if (!entry_already_wired) {
+- kr = vm_fault_wire_resident_pages(cur_map,
+- entry, caller_prot, tag, physpage_p, ctx);
+- if (kr != KERN_SUCCESS) {
+- /*
+- * on error, vm_fault_wire_resident_pages
+- * unwires everything in the range
+- */
+- vm_map_wire_count_sub(cur_map, entry, user_wire);
+- cur_copy->wire_state = NOT_WIRED;
+-
+- vm_map_range_ex_unlock(ctx, &original_map);
+-
+- goto wire_error_unlocked;
++ if (!el0_atomic_segs_grow(&segs, &seg_cap, n_segs + 1)) {
++ if (co != VM_OBJECT_NULL) {
++ if (ce->is_sub_map) {
++ vm_map_deallocate((vm_map_t)(uintptr_t)co);
++ } else {
++ vm_object_deallocate(co);
++ }
+ }
+- faulted_pages = true;
++ kr = KERN_RESOURCE_SHORTAGE;
++ break;
+ }
+- cur_copy->wire_state = ENTRY_WIRED;
+- } else {
+- /*
+- * Some intermediate deletion happened.
+- * Unless otherwise noted, pretend that
+- * deletion happened after the wiring.
+- * That means the new memory would be unwired by the
+- * deletion and thus not need to be wired by this call.
+- */
+- if (!user_wire && vm_kernel_map_is_kernel(cur_map)) {
+- /*
+- * Kernel initiated wire that raced against deletion
+- * on the kernel map
+- * This is a bug, and thus we should panic
+- */
+- __vm_map_wire_kernel_deletion_panic(cur_map, start,
+- end, entry->vme_start, entry->vme_end);
+- } else if (!user_wire) {
+- /*
+- * Kernel initiated wire that raced against deletion
+- * on a user map.
+- * We can't say the deletion happened after the wiring,
+- * because the deletion would have waited for the wire
+- * count to go to zero.
+- * That means we have to pretend the deletion happened
+- * before the wiring.
+- * That means we need to restart from the top.
+- * goto the error path to drop all our state
+- * and let it restart.
+- */
+- need_restart = true;
+- vm_map_range_ex_unlock(ctx, &original_map);
+-
+- goto wire_error_unlocked;
++ vm_map_kernel_flags_t seg_flags = base_flags;
++ seg_flags.vmkf_submap = ce->is_sub_map;
++ seg_flags.vm_tag = chunk_tag ?: VME_ALIAS(ce);
++ segs[n_segs].va = cur_va;
++ segs[n_segs].size = csz;
++ segs[n_segs].object = co;
++ segs[n_segs].offset = coff;
++ segs[n_segs].cur_protection = chunk_cur_prot;
++ segs[n_segs].max_protection = chunk_max_prot;
++ segs[n_segs].inheritance = VM_INHERIT_NONE;
++ segs[n_segs].vmk_flags = seg_flags;
++ segs[n_segs].is_submap = ce->is_sub_map;
++ segs[n_segs].needs_copy = do_copy;
++ segs[n_segs].iokit_acct = iokit_acct && !ce->is_sub_map;
++ n_segs++;
++ cur_va += csz;
++ }
++ named_entry_unlock(named_entry);
++ if (target_copy_map != copy_map) {
++ vm_map_copy_discard(target_copy_map);
++ }
++ if (kr == KERN_SUCCESS) {
++ chunks[c].data_addr_out = chunk_start_va + oim + overmap_start;
++ if (chunks[c].check_data_addr &&
++ chunks[c].data_addr_out != chunks[c].expected_data_addr) {
++ kr = KERN_INVALID_ARGUMENT;
++ break;
+ }
+-
+- vm_fault_unwire_object_pages(cur_map, cur_copy->object,
+- cur_copy->offset, cur_copy->end - cur_copy->start);
+- cur_copy->wire_state = NOT_WIRED;
+ }
++ } else {
++ named_entry_unlock(named_entry);
++ kr = KERN_INVALID_OBJECT;
++ break;
+ }
+- assert(cur_copy->wire_state == ENTRY_WIRED || cur_copy->wire_state == NOT_WIRED);
++ }
+
+- /*
+- * If we didn't already get the ppnum from faulting the pages,
+- * get it now.
+- */
+- if (!faulted_pages && wire_and_extract) {
+- assert(!entry->is_sub_map); // enforced by preflight
+- if (cur_copy->wire_state == NOT_WIRED) {
+- kr = KERN_INVALID_ADDRESS;
+- vm_map_range_ex_unlock(ctx, &original_map);
++ if (kr == KERN_SUCCESS && (cur_va - base_addr) != total_map_size) {
++ kr = KERN_INVALID_ARGUMENT;
++ }
+
+- goto wire_error_unlocked;
++ if (kr == KERN_SUCCESS) {
++ vm_map_kernel_flags_t rsv_flags = {
++ .vmf_fixed = true,
++ .vmf_overwrite = true,
++ .vm_tag = tag,
++ };
++ kr = vm_map_el0_enter_entries_overwrite_atomic(target_map,
++ base_addr, total_map_size, 0, rsv_flags, segs, n_segs);
++ if (kr == KERN_SUCCESS) {
++ for (size_t c = 0; c < nchunks; c++) {
++ unsigned int req_access = (chunks[c].cache_perm != 0) ?
++ GET_MAP_MEM(chunks[c].cache_perm) : MAP_MEM_NOOP;
++ if (req_access != MAP_MEM_NOOP) {
++ vm_named_entry_t named_entry = mach_memory_entry_from_port(chunks[c].port);
++ named_entry_lock(named_entry);
++ if (named_entry->is_object) {
++ vm_object_t wobj = vm_named_entry_to_vm_object(named_entry);
++ if (wobj != VM_OBJECT_NULL) {
++ vm_object_lock(wobj);
++ uint8_t wimg_mode = wobj->wimg_bits;
++ vm_prot_to_wimg(req_access, &wimg_mode);
++ if (!wobj->nophyscache && wobj->wimg_bits != wimg_mode) {
++ vm_object_change_wimg_mode(wobj, wimg_mode);
++ }
++ named_entry->access = req_access;
++ vm_object_unlock(wobj);
++ }
++ }
++ named_entry_unlock(named_entry);
++ }
+ }
+- *physpage_p = get_page_for_wire_and_extract(entry);
+ }
+-
+- cur_copy = TAILQ_NEXT(cur_copy, chain);
+ }
+
+- vm_map_range_ex_unlock(ctx, &original_map);
+-
+- /* cleanup our copies */
+- vm_map_wire_cleanup_wire_copy_list(&copy_list);
+- vmlp_api_end(VM_MAP_WIRE_IMPL, KERN_SUCCESS);
+- return KERN_SUCCESS;
+-
+-wire_error_unlocked:
+- /*
+- * Note that this error path cannot be _locked, as we will wire
+- * entries in stage 1 and then drop it for stage 2. Therefore there is
+- * some path to this where the range lock is dropped
+- * and we later need to unwire entries.
+- *
+- * There are 3 states a copy can be in:
+- * 1) ENTRY_WIRED: We already wired the entry, so unwire that same range.
+- * 2) OBJ_WIRED: The obj is wired, so unwire it.
+- * 3) NOT_WIRED: nothing to do
+- */
+- assert(kr != KERN_SUCCESS || need_restart);
+-
+- TAILQ_FOREACH(cur_copy, &copy_list, chain) {
+- if (cur_copy->wire_state == ENTRY_WIRED) {
+- if (!cur_copy->is_sub_map) {
+- vm_map_unwire(cur_map, cur_copy->start, cur_copy->end,
+- user_wire);
++ if (kr != KERN_SUCCESS) {
++ for (size_t i = 0; i < n_segs; i++) {
++ if (segs[i].object != VM_OBJECT_NULL) {
++ if (segs[i].is_submap) {
++ vm_map_deallocate((vm_map_t)(uintptr_t)segs[i].object);
++ } else {
++ vm_object_deallocate(segs[i].object);
++ }
+ }
+- } else if (cur_copy->wire_state == OBJ_WIRED) {
+- mach_vm_size_t size = cur_copy->end - cur_copy->start;
+- assert(!cur_copy->is_sub_map);
+- vm_fault_unwire_object_pages(cur_map, cur_copy->object,
+- cur_copy->offset, size);
+ }
+ }
+-
+- vm_map_wire_cleanup_wire_copy_list(&copy_list);
+-
+- if (need_restart) {
+- /*
+- * We need to restart, but want to do exponential backoff from
+- * mutex_pause to prevent an attacker from causing us to busy
+- * loop in the kernel.
+- * We expect in practice hitting this is uncommon as we never
+- * hit this race in months of testing a branch that panicked here
+- * instead.
+- */
+- mutex_pause(wire_restarts);
+- /* overflow isn't a problem, this is used for backoff only */
+- wire_restarts++;
+- need_restart = false;
+-#if DEBUG || DEVELOPMENT
+- os_atomic_add(&wire_restarts_due_to_kernel_wiring, 1, relaxed);
+-#endif /* DEBUG || DEVELOPMENT */
+- goto restart;
++ if (segs != NULL) {
++ kfree_type(struct el0_atomic_seg, seg_cap, segs);
+ }
+-
+- vmlp_api_end(VM_MAP_WIRE_IMPL, kr);
+-
+ return kr;
+ }
+
+-kern_return_t
+-vm_map_wire_external(
+- vm_map_t map,
+- vm_map_offset_ut start_u,
+- vm_map_offset_ut end_u,
+- vm_prot_ut prot_u,
+- boolean_t user_wire)
+-{
+- vm_tag_t tag = vm_tag_bt();
+-
+- return vm_map_wire_kernel(map, start_u, end_u, prot_u, tag, user_wire);
+-}
+-
+-__mockable kern_return_t
+-vm_map_wire_kernel(
+- vm_map_t map,
+- vm_map_offset_ut start_u,
+- vm_map_offset_ut end_u,
+- vm_prot_ut prot_u,
+- vm_tag_t tag,
+- boolean_t user_wire)
+-{
+- return vm_map_wire_impl(map, start_u, end_u, prot_u, tag,
+- user_wire, NULL, VM_SANITIZE_CALLER_VM_MAP_WIRE);
+-}
+-
+-#if XNU_PLATFORM_MacOSX
+-
+-kern_return_t
+-vm_map_wire_and_extract(
+- vm_map_t map,
+- vm_map_offset_ut start_u,
+- vm_prot_ut prot_u,
+- boolean_t user_wire,
+- ppnum_t *physpage_p)
+-{
+- vm_tag_t tag = vm_tag_bt();
+- vm_map_size_ut size_u = vm_sanitize_wrap_size(VM_MAP_PAGE_SIZE(map));
+- vm_map_offset_ut end_u = vm_sanitize_compute_ut_end(start_u, size_u);
+-
+- return vm_map_wire_impl(map, start_u, end_u, prot_u, tag,
+- user_wire, physpage_p, VM_SANITIZE_CALLER_VM_MAP_WIRE);
+-}
+-
+-#endif /* XNU_PLATFORM_MacOSX */
+-
+-kern_return_t
+-vm_map_unwire(
+- vm_map_t map,
+- vm_map_offset_ut start_u,
+- vm_map_offset_ut end_u,
+- boolean_t user_wire)
+-{
+- return vm_map_unwire_impl(map, start_u, end_u, user_wire,
+- VM_SANITIZE_CALLER_VM_MAP_UNWIRE);
+-}
+-
+ static __attribute__((always_inline, warn_unused_result))
+ kern_return_t
+ vm_map_unwire_sanitize(
+@@ -8344,10 +10664,14 @@ vm_map_delete_preflight(
+
+ if (vmrl_is_kernel_pmap(ctx)) {
+ assert(entry->user_wired_count == 0);
++ if (linux64_el0 && entry->vme_el0_autowire) {
++ assert(wired_count > 0);
++ wired_count -= 1;
++ }
+ /*
+ * rdar://144237810 (vm_map_delete should reject VM_MAP_REMOVE_KUNWIRE calls when the wired_count is 0)
+ */
+- if (flags & VM_MAP_REMOVE_KUNWIRE) {
++ if ((flags & VM_MAP_REMOVE_KUNWIRE) && wired_count > 0) {
+ wired_count -= 1;
+ }
+ } else {
+@@ -8369,8 +10693,29 @@ vm_map_delete_preflight(
+ }
+
+ static void
+-vm_map_delete_handle_wired(vm_map_t map, vm_map_entry_t entry, vmr_flags_t flags)
+-{
++vm_map_delete_handle_wired(
++ vm_map_t map,
++ vm_map_entry_t entry,
++ vmr_flags_t flags,
++ struct el0_zap_saved *saved_cur)
++{
++ if (linux64_el0 && saved_cur != NULL && saved_cur->had_autowire &&
++ (flags & VM_MAP_REMOVE_TO_OVERWRITE) &&
++ !(flags & VM_MAP_REMOVE_KUNWIRE) &&
++ entry->user_wired_count == 0 &&
++ !entry->vme_kernel_object &&
++ !entry->is_sub_map) {
++ entry->vme_el0_autowire = 0;
++ vm_map_wire_count_sub(map, entry, FALSE);
++ assert(entry->wired_count == 0);
++ pmap_remove(map->pmap, entry->vme_start, entry->vme_end);
++ if (VME_OBJECT(entry) != VM_OBJECT_NULL &&
++ !VME_OBJECT(entry)->phys_contiguous) {
++ saved_cur->deferred_page_unwire = true;
+ }
++ return;
+ }
-+}
-diff --git a/osfmk/kern/stack.c b/osfmk/kern/stack.c
-index 1111ccf..9bc5118 100644
---- a/osfmk/kern/stack.c
-+++ b/osfmk/kern/stack.c
-@@ -30,6 +30,7 @@
- */
++
+ if (entry->user_wired_count) {
+ /*
+ * Collapse the wire count to 1, which will cause
+@@ -8379,7 +10724,12 @@ vm_map_delete_handle_wired(vm_map_t map, vm_map_entry_t entry, vmr_flags_t flags
+ entry->user_wired_count = 1;
+ }
- #include <mach/mach_host.h>
-+#include <linux64/linux64.h>
- #include <mach/mach_types.h>
- #include <mach/processor_set.h>
+- if (entry->user_wired_count || (flags & VM_MAP_REMOVE_KUNWIRE)) {
++ if (linux64_el0 && entry->vme_el0_autowire) {
++ entry->vme_el0_autowire = 0;
++ vm_map_wire_count_sub(map, entry, FALSE);
++ }
++
++ if (entry->user_wired_count || ((flags & VM_MAP_REMOVE_KUNWIRE) && entry->wired_count > 0)) {
+ vm_map_wire_count_sub(map, entry, entry->user_wired_count != 0);
+ }
-@@ -185,6 +186,24 @@ STARTUP(TUNABLES, STARTUP_RANK_MIDDLE, stack_init);
- * block.
- */
+@@ -8518,7 +10868,8 @@ vm_map_delete_handle_entry(
+ vm_map_t map,
+ vm_map_entry_t entry,
+ vm_map_entry_t sentinel,
+- vmr_flags_t flags)
++ vmr_flags_t flags,
++ struct el0_zap_saved *saved_cur)
+ {
+ vm_map_offset_t e_start = entry->vme_start;
+ vm_map_offset_t e_end = entry->vme_end;
+@@ -8529,7 +10880,7 @@ vm_map_delete_handle_entry(
+ */
-+/*
-+ * LINUX64 (xnulinux): an exception taken on an XNU kernel stack enters Linux's vectors, whose overflow check wants
-+ * bit THREAD_SHIFT (14) of sp clear, as on Linux's 2*THREAD_SIZE-aligned stacks. Hosted, each stack starts on a
-+ * 32 KiB boundary. The allocation's mask aligns the address after its first guard page (kernel_memory_allocate with
-+ * KMA_GUARD_FIRST: the start plus one page is 32 KiB aligned), so the stack sits one page plus 32 KiB above the start
-+ * (the two guard pages, then unused wired pages, then the stack, then the upper guard page), for any page size.
-+ */
-+static inline vm_offset_t
-+linux64_stack_lead(void)
-+{
-+ return linux64_hook ? ptoa(1) + 0x8000 : ptoa(2);
-+}
-+static inline vm_offset_t
-+linux64_stack_mask(void)
-+{
-+ return linux64_hook ? (stack_addr_mask | 0x7fff) : stack_addr_mask;
-+}
+ if (entry->wired_count) {
+- vm_map_delete_handle_wired(map, entry, flags);
++ vm_map_delete_handle_wired(map, entry, flags, saved_cur);
+ }
+
+ /*
+@@ -8799,12 +11150,61 @@ vm_map_delete_and_iunlock_internal(
+ kr = KERN_SUCCESS;
+ }
+ if (kr == KERN_SUCCESS) {
++ if (zap != NULL && (flags & VM_MAP_REMOVE_TO_OVERWRITE) &&
++ !(flags & VM_MAP_REMOVE_EL0_DISCARD_NEW) &&
++ linux64_el0 && ctx->vmlc_map->pmap == kernel_pmap &&
++ startup_phase >= STARTUP_SUB_ZALLOC) {
++ bool any_saved_ptes = false;
++ for (vm_map_entry_t e = ctx->__vmlc_atomic.first_entry;
++ e != VM_MAP_ENTRY_NULL && e != vm_map_to_entry(ctx->vmlc_map) &&
++ e->vme_start < ctx->vmlc_req_end;
++ e = e->vme_next) {
++ if (!VME_IS_SENTINEL(e)) {
++ if (e->is_sub_map && !e->use_pmap) {
++ el0_zap_free_saved(zap);
++ vm_map_range_ex_unlock(ctx, already_locked ? NULL : &map);
++ vmlp_api_end(VM_MAP_DELETE_AND_IUNLOCK, KERN_NOT_SUPPORTED);
++ return KERN_NOT_SUPPORTED;
++ }
++ kern_return_t save_kr = el0_zap_save_entry(zap, ctx->vmlc_map, e);
++ if (save_kr != KERN_SUCCESS) {
++ el0_zap_free_saved(zap);
++ vm_map_range_ex_unlock(ctx, already_locked ? NULL : &map);
++ vmlp_api_end(VM_MAP_DELETE_AND_IUNLOCK, save_kr);
++ return save_kr;
++ }
++ }
++ if (e->vme_end >= ctx->vmlc_req_end) {
++ break;
++ }
++ }
++ for (struct el0_zap_saved *s = zap->el0_saved_head; s != NULL; s = s->next) {
++ if (s->has_saved_ptes) {
++ any_saved_ptes = true;
++ break;
++ }
++ }
++ if (any_saved_ptes) {
++ kern_return_t tkr = pmap_el0_kmap_txn_begin(
++ ctx->vmlc_req_start,
++ ctx->vmlc_req_end - ctx->vmlc_req_start,
++ &zap->el0_kmap_txn);
++ if (tkr != KERN_SUCCESS) {
++ el0_zap_free_saved(zap);
++ vm_map_range_ex_unlock(ctx, already_locked ? NULL : &map);
++ vmlp_api_end(VM_MAP_DELETE_AND_IUNLOCK, tkr);
++ return tkr;
++ }
++ }
++ }
+
- static vm_offset_t
- stack_alloc_internal(void)
- {
-@@ -218,7 +237,7 @@ stack_alloc_internal(void)
- */
+ if (flags & VM_MAP_REMOVE_TO_OVERWRITE) {
+ /* initially zero-length, will be extended by vm_map_delete_handle_entry */
+ sentinel = vm_map_entry_create_sentinel_locked(orig_map, start, start);
+ *sentinel_out = sentinel;
+ }
- kernel_memory_allocate(kernel_map, &stack,
-- kernel_stack_size + ptoa(3), stack_addr_mask,
-+ kernel_stack_size + linux64_stack_lead() + ptoa(1), linux64_stack_mask(),
- flags, VM_KERN_MEMORY_STACK);
++ struct el0_zap_saved *saved_cur = (zap != NULL) ? zap->el0_saved_head : NULL;
+ while ((entry = vm_map_range_ex_pop_with_error(ctx, &kr))) {
+ if (vm_map_lock_ctx_is_descended(ctx)) {
+ /*
+@@ -8814,7 +11214,12 @@ vm_map_delete_and_iunlock_internal(
+ */
+ panic("Attempt to delete through transparent submap.");
+ }
+- if (vm_map_delete_handle_entry(ctx->vmlc_map, entry, sentinel, flags)) {
++ struct el0_zap_saved *entry_saved = NULL;
++ if (saved_cur != NULL && saved_cur->entry == entry) {
++ entry_saved = saved_cur;
++ saved_cur = saved_cur->next;
++ }
++ if (vm_map_delete_handle_entry(ctx->vmlc_map, entry, sentinel, flags, entry_saved)) {
+ if (ctx->vmlc_map != orig_map) {
+ /*
+ * wait_for_space wakeup below does not
+@@ -9002,7 +11407,7 @@ vm_map_remove_entry(vm_map_t map, vm_map_entry_t entry, vmr_flags_t flags)
+ VM_ENTRY_ASSERT_EXCL_OWNER(entry);
+ assert(!entry->vme_permanent);
+
+- (void)vm_map_delete_handle_entry(map, entry, VM_MAP_ENTRY_NULL, flags);
++ (void)vm_map_delete_handle_entry(map, entry, VM_MAP_ENTRY_NULL, flags, NULL);
+ }
+
+ kern_return_t
+@@ -10547,6 +12952,14 @@ vm_map_copyout_kernel_buffer(
+ if (kr != KERN_SUCCESS) {
+ return kr;
+ }
++ if (linux64_el0 && map->pmap == kernel_pmap) {
++ vm_map_size_t rsize = vm_map_round_page(copy_size, VM_MAP_PAGE_MASK(map));
++ kr = linux64_el0_prefault_kernel_map(map, *addr, rsize, VM_PROT_DEFAULT);
++ if (kr != KERN_SUCCESS) {
++ (void)vm_map_remove(map, *addr, *addr + rsize);
++ return kr;
++ }
++ }
+ #if KASAN
+ if (map->pmap == kernel_pmap) {
+ kasan_notify_address(*addr, copy->size);
+@@ -10904,7 +13317,8 @@ vm_map_copyout_internal(
+ }
+ adjustment = vmsr_start(rsv) - vm_copy_start;
+- if (!consume_on_success) {
++ bool el0_defer_consume = (linux64_el0 && dst_map->pmap == kernel_pmap && size != 0 && consume_on_success);
++ if (!consume_on_success || el0_defer_consume) {
/*
-@@ -226,7 +245,10 @@ stack_alloc_internal(void)
- * guard pages. Skip past them to get the actual stack base address.
- */
+ * We're not allowed to consume "copy", so we'll have to
+ * copy its map entries into the destination map below.
+@@ -11071,7 +13485,7 @@ after_adjustments:
+ * Link in the copy
+ */
-- stack += ptoa(2);
-+ stack += linux64_stack_lead();
-+ if (linux64_hook && (stack & 0x7fff)) { /* Linux would take an exception on it for a stack overflow */
-+ panic("linux64: kernel stack %p is not on a 32 KiB boundary", (void *)stack);
+- if (consume_on_success) {
++ if (consume_on_success && !el0_defer_consume) {
+ vm_map_copy_insert(dst_map, copy, rsv, vmk_flags);
+ if (copy != original_copy) {
+ /* the copy discarded in vm_map_copy_insert() might have been one which
+@@ -11081,8 +13495,11 @@ after_adjustments:
+ }
+ } else {
+ vm_map_copy_remap(dst_map, copy, rsv, vmk_flags,
+- adjustment, cur_protection, max_protection, inheritance);
+- if (copy != original_copy && original_copy != VM_MAP_COPY_NULL) {
++ adjustment,
++ el0_defer_consume ? VM_PROT_DEFAULT : cur_protection,
++ el0_defer_consume ? VM_PROT_ALL : max_protection,
++ el0_defer_consume ? VM_INHERIT_DEFAULT : inheritance);
++ if (!el0_defer_consume && copy != original_copy && original_copy != VM_MAP_COPY_NULL) {
+ /* if vm_map_copy_adjust_to_target() created a local copy, free it now */
+ vm_map_copy_discard(copy);
+ copy = original_copy;
+@@ -11091,6 +13508,26 @@ after_adjustments:
+
+
+ vm_map_ilk_unlock(dst_map);
++ if (linux64_el0 && dst_map->pmap == kernel_pmap && size != 0) {
++ vm_map_offset_t pf_addr = vm_map_trunc_page(*dst_addr, VM_MAP_PAGE_MASK(dst_map));
++ kern_return_t pkr = linux64_el0_prefault_kernel_map(dst_map,
++ pf_addr, size,
++ consume_on_success ? VM_PROT_DEFAULT : cur_protection);
++ if (pkr != KERN_SUCCESS) {
++ (void)vm_map_remove(dst_map, pf_addr, pf_addr + size);
++ if (el0_defer_consume && copy != original_copy && original_copy != VM_MAP_COPY_NULL) {
++ vm_map_copy_discard(copy);
++ }
++ vmlp_api_end(VM_MAP_COPYOUT_INTERNAL, pkr);
++ return pkr;
++ }
++ if (el0_defer_consume) {
++ if (copy != original_copy && original_copy != VM_MAP_COPY_NULL) {
++ vm_map_copy_discard(original_copy);
++ }
++ vm_map_copy_discard(copy);
+ }
++ }
+ vmlp_api_end(VM_MAP_COPYOUT_INTERNAL, KERN_SUCCESS);
+
+ return KERN_SUCCESS;
+@@ -17178,6 +19615,26 @@ vm_map_remap(
+ return KERN_NO_SPACE;
}
- return stack;
- }
-@@ -389,8 +411,8 @@ stack_collect(void)
- stack = (vm_offset_t)vm_map_trunc_page(
- stack,
- VM_MAP_PAGE_MASK(kernel_map));
-- stack -= ptoa(2);
-- kmem_free(kernel_map, stack, kernel_stack_size + ptoa(3),
-+ stack -= linux64_stack_lead();
-+ kmem_free(kernel_map, stack, kernel_stack_size + linux64_stack_lead() + ptoa(1),
- KMF_GUARD_FIRST | KMF_GUARD_LAST | KMF_GUARD_STACK);
- stack = 0;
-diff --git a/osfmk/mach/arm/thread_status.h b/osfmk/mach/arm/thread_status.h
-index 99971b0..efc6ab8 100644
---- a/osfmk/mach/arm/thread_status.h
-+++ b/osfmk/mach/arm/thread_status.h
-@@ -522,6 +522,7 @@ extern void ml_check_signed_state(const arm_saved_state_t *, uint64_t, uint32_t,
- asm volatile ( \
- "mov x9, lr" "\n" \
- "mov x0, %[iss]" "\n" \
-+ "mrs x10, SPSel" "\n" \
- "msr SPSel, #1" "\n" \
- "ldp x4, x5, [x0, %[SS64_X16]]" "\n" \
- "ldr x7, [x0, %[SS64_PC]]" "\n" \
-@@ -535,7 +536,7 @@ extern void ml_check_signed_state(const arm_saved_state_t *, uint64_t, uint32_t,
- _instr "\n" \
- "bl _ml_sign_thread_state" "\n" \
- "0:" "\n" \
-- "msr SPSel, #0" "\n" \
-+ "msr SPSel, x10" "\n" \
- "mov lr, x9" "\n" \
- : \
- : [iss] "r"(_iss), \
-@@ -544,7 +545,7 @@ extern void ml_check_signed_state(const arm_saved_state_t *, uint64_t, uint32_t,
- [SS64_CPSR] "i"(ss64_offsetof(cpsr)), \
- [SS64_LR] "i"(ss64_offsetof(lr)),##__VA_ARGS__ \
- : "x0", "x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", \
-- "x9", "x16", "x17" \
-+ "x9", "x10", "x16", "x17" \
- ); \
- ml_pac_safe_interrupts_restore(_intr); \
- } while (0)
-diff --git a/osfmk/mach/arm/vm_param.h b/osfmk/mach/arm/vm_param.h
-index bb62cdd..9bea611 100644
---- a/osfmk/mach/arm/vm_param.h
-+++ b/osfmk/mach/arm/vm_param.h
-@@ -149,6 +149,11 @@ extern int PAGE_SHIFT_CONST;
- #undef MACH_VM_MAX_ADDRESS_RAW
- #define MACH_VM_MAX_ADDRESS_RAW 0x00007FFFFE000000ULL
- #endif /* defined(XNU_PLATFORM_iPhoneOS) && EXTENDED_USER_VA_SUPPORT */
-+#if !__ARM_16K_PG__ && !defined(XNU_PLATFORM_MacOSX)
-+/* LINUX64 (xnulinux): 4 KiB user pmaps span 47 bits (pmap_pt_attr_4k_user), the macOS layout its userland expects */
-+#undef MACH_VM_MAX_ADDRESS_RAW
-+#define MACH_VM_MAX_ADDRESS_RAW 0x00007FFFFE000000ULL
-+#endif
- /* threshold for allocations to be placed in the large file range */
- #define VM_LARGE_FILE_THRESHOLD (1ULL << 30)
- #define MACH_VM_JUMBO_ADDRESS ((mach_vm_offset_t) 0x0000000FC0000000ULL)
-@@ -294,7 +299,7 @@ extern int PAGE_SHIFT_CONST;
++ if (linux64_el0 && target_map->pmap == kernel_pmap &&
++ !vmk_flags.vmf_resilient_codesign) {
++ bool has_exec = ((cur_protection & VM_PROT_ALLEXEC) != 0);
++ if (!has_exec) {
++ for (vm_map_entry_t ce = vm_map_copy_first_entry(copy_map);
++ ce != vm_map_copy_to_entry(copy_map);
++ ce = ce->vme_next) {
++ if (ce->protection & VM_PROT_ALLEXEC) {
++ has_exec = true;
++ break;
++ }
++ }
++ }
++ if (has_exec) {
++ vm_map_copy_discard(copy_map);
++ vmlp_api_end(VM_MAP_REMAP, KERN_NOT_SUPPORTED);
++ return KERN_NOT_SUPPORTED;
++ }
++ }
++
+ vm_map_ilk_lock(target_map);
- #if XNU_KERNEL_PRIVATE
- #define VM_KERNEL_STRIP_MASK (-1ULL << (64 - T1SZ_BOOT))
--#define VM_USER_STRIP_MASK (-1ULL >> (T0SZ_BOOT))
-+#define VM_USER_STRIP_MASK (-1ULL >> (T0SZ_HW)) /* LINUX64: user addresses span the width TTBR0 runs with */
- #define _VM_KERNEL_STRIP_PTR(_va) ({((_va) & 1ULL << 55) ? ((_va) | VM_KERNEL_STRIP_MASK) : ((_va) & VM_USER_STRIP_MASK);})
- #else /* XNU_KERNEL_PRIVATE */
+ if (vmk_flags.vmf_fixed) {
+@@ -17283,6 +19740,11 @@ vm_map_remap(
+ max_protection = VM_PROT_READ;
+ }
-diff --git a/osfmk/prng/prng_random.c b/osfmk/prng/prng_random.c
-index 44b993c..4ce279b 100644
---- a/osfmk/prng/prng_random.c
-+++ b/osfmk/prng/prng_random.c
-@@ -28,6 +28,7 @@
++ if (zap_list.el0_kmap_txn != 0) {
++ pmap_el0_kmap_txn_end(zap_list.el0_kmap_txn);
++ zap_list.el0_kmap_txn = 0;
++ }
++
+ vm_map_ilk_unlock(target_map);
+
+ vm_map_zap_dispose(target_map, &zap_list); /* if when result is not KERN_SUCCESS we could have added something */
+diff --git a/osfmk/vm/vm_map_internal.h b/osfmk/vm/vm_map_internal.h
+index d798dff..600a32c 100644
+--- a/osfmk/vm/vm_map_internal.h
++++ b/osfmk/vm/vm_map_internal.h
+@@ -334,6 +334,7 @@ __options_decl(vmr_flags_t, uint32_t, {
+ VM_MAP_REMOVE_IMMUTABLE_CODE = 0x040,
+ VM_MAP_REMOVE_RANGE_LOCKED = 0x080,
+ VM_MAP_REMOVE_ZERO_FILL = 0x100,
++ VM_MAP_REMOVE_EL0_DISCARD_NEW = 0x200,
+ });
+
+ extern void vm_map_remove_entry(
+diff --git a/osfmk/vm/vm_map_lock.c b/osfmk/vm/vm_map_lock.c
+index 987c9d5..2753796 100644
+--- a/osfmk/vm/vm_map_lock.c
++++ b/osfmk/vm/vm_map_lock.c
+@@ -524,9 +524,11 @@ __vmrl_clip_ilocked(
+ assert_vm_map_ilk_owned_ignore_sealed(map, LCK_RW_TYPE_EXCLUSIVE);
+ VM_ENTRY_ASSERT_EXCL_OWNER(entry);
+
++ extern unsigned int linux64_el0;
+ if (!entry->is_sub_map &&
+ VME_OBJECT(entry) &&
+- VME_OBJECT(entry)->phys_contiguous) {
++ VME_OBJECT(entry)->phys_contiguous &&
++ !(linux64_el0 && map->pmap == kernel_pmap)) {
+ pmap_remove(map->pmap, entry->vme_start, entry->vme_end);
+ }
- extern volatile unsigned long long port_crumb; /* port bring-up breadcrumb (link_compat.c) */
- #include <kern/locks.h>
-+#include <linux64/linux64.h>
- #include <kern/cpu_number.h>
- #include <libkern/section_keywords.h>
- #include <libkern/crypto/sha2.h>
-@@ -368,13 +369,23 @@ random_cpu_init(int cpu)
- panic("random_cpu_init: kernel prng has not been installed");
+@@ -1258,6 +1260,7 @@ vm_map_simplify_entry_with_prev_locked(
+
+ (prev_entry->wired_count == this_entry->wired_count) &&
+ (prev_entry->user_wired_count == this_entry->user_wired_count) &&
++ (prev_entry->vme_el0_autowire == this_entry->vme_el0_autowire) &&
+
+ ((prev_entry->vme_atomic == FALSE) && (this_entry->vme_atomic == FALSE)) &&
+ (prev_entry->is_shared == this_entry->is_shared) &&
+diff --git a/osfmk/vm/vm_map_xnu.h b/osfmk/vm/vm_map_xnu.h
+index 9d9e4a4..b804360 100644
+--- a/osfmk/vm/vm_map_xnu.h
++++ b/osfmk/vm/vm_map_xnu.h
+@@ -415,7 +415,7 @@ struct vm_map_entry {
+ /* boolean_t */ vme_no_copy_on_read:1,
+ /* boolean_t */ translated_allow_execute:1, /* execute in translated processes */
+ /* boolean_t */ vme_kernel_object:1, /* vme_object is a kernel_object */
+- /* boolean_t */ __unused3 :1;
++ /* boolean_t */ vme_el0_autowire:1; /* wired by linux64_el0_prefault_kernel_map */
+
+ unsigned short wired_count; /* can be paged if = 0 */
+ unsigned short user_wired_count; /* for vm_wire */
+diff --git a/osfmk/vm/vm_memory_entry.c b/osfmk/vm/vm_memory_entry.c
+index a92c3c0..fb96ef2 100644
+--- a/osfmk/vm/vm_memory_entry.c
++++ b/osfmk/vm/vm_memory_entry.c
+@@ -200,45 +200,49 @@ mach_make_memory_entry_mem_only(
+ size_u, offset_u, permission, user_entry, object_handle);
}
-- prng_funcs.initgen(prng_ctx, cpu);
-+ if (prng_funcs.initgen != NULL) {
-+ prng_funcs.initgen(prng_ctx, cpu);
-+ }
- }
++ named_entry_lock(parent_entry);
++
+ parent_is_object = parent_entry->is_object;
+ if (!parent_is_object) {
++ named_entry_unlock(parent_entry);
+ return mach_make_memory_entry_cleanup(KERN_INVALID_ARGUMENT, target_map,
+ size_u, offset_u, permission, user_entry, object_handle);
+ }
- /* export good random numbers to the rest of the kernel */
- __mockable void
- read_random(void * buffer, u_int numbytes)
- {
-+ /*
-+ * LINUX64 (xnulinux): without the corecrypto kext nobody calls register_and_init_prng() and prng_funcs stays
-+ * zeroed; hosted, the host's generator (Linux's get_random_bytes) stands in.
-+ */
-+ if (prng_funcs.generate == NULL && linux64_hook) {
-+ linux64_random(buffer, numbytes);
-+ return;
-+ }
- prng_funcs.refresh(prng_ctx);
- read_random_generate(buffer, numbytes);
- }
-@@ -433,7 +444,9 @@ write_random(void * buffer, u_int numbytes)
- memcpy(seed, buffer, numbytes);
+ if ((access != parent_entry->access) &&
+ !(parent_entry->protection & VM_PROT_WRITE)) {
++ named_entry_unlock(parent_entry);
+ return mach_make_memory_entry_cleanup(KERN_INVALID_RIGHT, target_map,
+ size_u, offset_u, permission, user_entry, object_handle);
}
-- prng_funcs.reseed(prng_ctx, sizeof(seed), seed);
-+ if (prng_funcs.reseed != NULL) {
-+ prng_funcs.reseed(prng_ctx, sizeof(seed), seed);
+ object = vm_named_entry_to_vm_object(parent_entry);
+ if (parent_is_object && object != VM_OBJECT_NULL) {
++ vm_object_lock(object);
+ wimg_mode = object->wimg_bits;
+- } else {
+- wimg_mode = VM_WIMG_USE_DEFAULT;
+- }
+- vm_prot_to_wimg(access, &wimg_mode);
+- if (parent_is_object && object &&
+- (access != MAP_MEM_NOOP) &&
+- (!(object->nophyscache))) {
+- if (object->wimg_bits != wimg_mode) {
+- vm_object_lock(object);
++ vm_prot_to_wimg(access, &wimg_mode);
++ if ((access != MAP_MEM_NOOP) &&
++ (!(object->nophyscache)) &&
++ (object->wimg_bits != wimg_mode)) {
+ #if HAS_MTE
+ if (vm_object_is_mte_mappable(object)) {
+ vm_object_unlock(object);
++ named_entry_unlock(parent_entry);
+ return mach_make_memory_entry_cleanup(KERN_INVALID_ARGUMENT,
+ target_map, size_u, offset_u, permission, user_entry,
+ object_handle);
+ }
+ #endif /* HAS_MTE */
+ vm_object_change_wimg_mode(object, wimg_mode);
+- vm_object_unlock(object);
+ }
+- }
+- if (access != MAP_MEM_NOOP) {
++ if (access != MAP_MEM_NOOP) {
++ parent_entry->access = access;
++ }
++ vm_object_unlock(object);
++ } else if (access != MAP_MEM_NOOP) {
+ parent_entry->access = access;
+ }
++ named_entry_unlock(parent_entry);
+ if (object_handle) {
+ *object_handle = IP_NULL;
+ }
+diff --git a/osfmk/vm/vm_object.c b/osfmk/vm/vm_object.c
+index da261ba..5c5c0b9 100644
+--- a/osfmk/vm/vm_object.c
++++ b/osfmk/vm/vm_object.c
+@@ -303,6 +303,7 @@ static const struct vm_object vm_object_template = {
+ .vo_copy = VM_OBJECT_NULL,
+ .vo_copy_version = 0,
+ .vo_inherit_copy_none = false,
++ .vo_el0_prewire_count = 0,
+ .shadow = VM_OBJECT_NULL,
+ .vo_shadow_offset = (vm_object_offset_t) 0,
+ .pager = MEMORY_OBJECT_NULL,
+@@ -333,6 +334,7 @@ static const struct vm_object vm_object_template = {
+ .named = FALSE,
+ .shadow_severed = FALSE,
+ .phys_contiguous = FALSE,
++ .vo_el0_populated = FALSE,
+ .nophyscache = FALSE,
+ /* End bitfields */
+
+@@ -3946,7 +3948,8 @@ Retry:
+ if (!vm_page_is_fictitious(p) &&
+ p->vmp_offset >= old_copy->vo_size &&
+ p->vmp_offset < copy_size) {
+- if (p->vmp_busy && p->vmp_absent) {
++ if (p->vmp_busy && p->vmp_absent &&
++ (src_object->vo_el0_prewire_count == 0 || !VM_PAGE_WIRED(p))) {
+ /*
+ * A busy/absent page is still
+ * waiting for its contents.
+@@ -5842,12 +5845,20 @@ vm_object_populate_with_private(
+
+ /* shadows on contiguous memory are not allowed */
+ /* we therefore can use the offset field */
+- object->vo_shadow_offset = (vm_object_offset_t)phys_page << PAGE_SHIFT;
++ vm_object_offset_t new_shadow_offset = (vm_object_offset_t)phys_page << PAGE_SHIFT;
+ assertf(page_aligned(size),
+ "object %p size 0x%llx",
+ object, (uint64_t)size);
++ if (object->vo_el0_populated) {
++ bool match = (object->vo_shadow_offset == new_shadow_offset &&
++ object->vo_size == size);
++ vm_object_unlock(object);
++ return match ? KERN_SUCCESS : KERN_INVALID_VALUE;
++ }
++ object->vo_shadow_offset = new_shadow_offset;
+ object->vo_size = size;
+ }
++ object->vo_el0_populated = TRUE;
+ vm_object_unlock(object);
+
+ return KERN_SUCCESS;
+@@ -6626,6 +6637,7 @@ vm_object_transpose(
+ object1_locked = TRUE;
+ if (!object1->alive || object1->terminating ||
+ object1->vo_copy || object1->shadow || object1->shadowed ||
++ object1->vo_el0_prewire_count != 0 ||
+ object1->purgable != VM_PURGABLE_DENY) {
+ /*
+ * We don't deal with copy or shadow objects (yet).
+@@ -6655,12 +6667,17 @@ vm_object_transpose(
+ object2_locked = TRUE;
+ if (!object2->alive || object2->terminating ||
+ object2->vo_copy || object2->shadow || object2->shadowed ||
++ object2->vo_el0_prewire_count != 0 ||
+ object2->purgable != VM_PURGABLE_DENY) {
+ retval = KERN_INVALID_VALUE;
+ goto done;
+ }
+ vm_object_paging_only_wait(object2, THREAD_UNINT);
+
++ if (object1->vo_el0_prewire_count != 0 || object2->vo_el0_prewire_count != 0) {
++ retval = KERN_INVALID_VALUE;
++ goto done;
+ }
- cc_clear(sizeof(seed), seed);
- return 0;
+ if (object1->vo_size != object2->vo_size ||
+ object1->vo_size != transpose_size) {
+@@ -6805,6 +6822,7 @@ MACRO_END
+ __TRANSPOSE_FIELD(named);
+ /* "shadow_severed" refers to the object not its contents */
+ __TRANSPOSE_FIELD(phys_contiguous);
++ __TRANSPOSE_FIELD(vo_el0_populated);
+ __TRANSPOSE_FIELD(nophyscache);
+ __TRANSPOSE_FIELD(no_pager_reason);
+ /* "cached_list.next" points to transposed object */
+diff --git a/osfmk/vm/vm_object_xnu.h b/osfmk/vm/vm_object_xnu.h
+index a496f76..946ca59 100644
+--- a/osfmk/vm/vm_object_xnu.h
++++ b/osfmk/vm/vm_object_xnu.h
+@@ -371,7 +371,8 @@ struct vm_object {
+ * so this shouldn't be used for
+ * policy decisions */
+ has_been_clipped:1, /* true if it's ever been clipped */
+- __object4_unused_bits:5;
++ vo_el0_populated:1,
++ __object4_unused_bits:4;
+
+ #if VM_OBJECT_ACCESS_TRACKING
+ uint32_t access_tracking_reads;
+@@ -426,6 +427,7 @@ struct vm_object {
+ */
+ vm_map_serial_t vmo_provenance;
+ uint32_t vmo_pl_req_in_progress; /* page list request in progress */
++ uint32_t vo_el0_prewire_count; /* active EL0 vm_map_protect pre-wire holds */
+ uint32_t vo_inherit_copy_none:1,
+ __vo_unused_padding:31;
+ };
+diff --git a/osfmk/vm/vm_sanitize.c b/osfmk/vm/vm_sanitize.c
+index d1ff7d0..362f39f 100644
+--- a/osfmk/vm/vm_sanitize.c
++++ b/osfmk/vm/vm_sanitize.c
+@@ -640,7 +640,8 @@ vm_sanitize_addr_size(
+ * instead of assuming it is 48 bits.
+ * This is excluded from unit-test build due to being EL1 only instruction
+ */
+- assert((__builtin_arm_rsr64("ID_AA64MMFR2_EL1") & ID_AA64MMFR2_EL1_VARANGE_MASK) == 0);
++ extern unsigned int linux64_el0;
++ assert(linux64_el0 || (__builtin_arm_rsr64("ID_AA64MMFR2_EL1") & ID_AA64MMFR2_EL1_VARANGE_MASK) == 0);
+ #endif /* defined(__arm64__) && MACH_ASSERT && !__BUILDING_XNU_LIBRARY__ */
+ const uint64_t max_va_bits = 48;
+ const mach_vm_offset_t va_range_upper_bound = (1ULL << max_va_bits);
+diff --git a/osfmk/vm/vm_shared_region.c b/osfmk/vm/vm_shared_region.c
+index a9b12f4..6a4302b 100644
+--- a/osfmk/vm/vm_shared_region.c
++++ b/osfmk/vm/vm_shared_region.c
+@@ -79,6 +79,12 @@
+ #include <arm/cpu_data_internal.h>
+ #include <arm/misc_protos.h>
+ #endif
++#include <linux64/linux64.h>
++extern kern_return_t linux64_el0_prefault_kernel_map(
++ vm_map_t map,
++ mach_vm_offset_t addr,
++ mach_vm_size_t size,
++ vm_prot_t prot);
+
+ /*
+ * the following codes are used in the subclass
+@@ -788,7 +794,7 @@ vm_shared_region_create(
+ #endif /* CODE_SIGNING_MONITOR */
+ int vm_map_pageshift = PAGE_SHIFT;
+ #if !defined(APPLE_ARM64_ARCH_FAMILY) && !__ARM_16K_PG__
+- vm_map_pageshift = FOURK_PAGE_SHIFT;
++ vm_map_pageshift = PAGE_SHIFT; /* LINUX64: as the task maps (mach_loader.c) */
+ #else
+ if (is_64bit ||
+ page_shift_user32 == SIXTEENK_PAGE_SHIFT) {
+@@ -1617,6 +1623,22 @@ vm_shared_region_map_file_setup(
+ break;
+ }
+
++ /*
++ * Prefault & autowire BEFORE taking the extra object reference so
++ * vm_map_wire_stabilize_entry_object sees ref_count == 1 and does
++ * not shadow `object` (otherwise bzero/copyin would write to the
++ * shadow object and leave `object` empty for sr_map).
++ */
++ if (linux64_el0) {
++ kr = linux64_el0_prefault_kernel_map(kernel_map, kaddr, obj_size,
++ VM_PROT_READ | VM_PROT_WRITE);
++ if (kr != KERN_SUCCESS) {
++ vm_map_remove(kernel_map, kaddr, kaddr + obj_size);
++ object = VM_OBJECT_NULL;
++ break;
++ }
++ }
++
+ /*
+ * We'll need another reference to keep the object alive after
+ * we vm_map_remove() it from the kernel.
diff --git a/pexpert/arm/pe_kprintf.c b/pexpert/arm/pe_kprintf.c
index fea9411..cdccb1f 100644
--- a/pexpert/arm/pe_kprintf.c
@@ -2417,45 +12394,3 @@ index fea9411..cdccb1f 100644
if (!disable_serial_output && !disable_kprintf_output) {
va_start(listp, fmt);
va_copy(listp2, listp);
-diff --git a/bsd/kern/mach_loader.c b/bsd/kern/mach_loader.c
-index 6ce6141..8fb290b 100644
---- a/bsd/kern/mach_loader.c
-+++ b/bsd/kern/mach_loader.c
-@@ -801,7 +801,7 @@ load_machfile(
- #if defined(__arm64__)
- if (result->is_64bit_addr) {
- #if !defined(APPLE_ARM64_ARCH_FAMILY) && !__ARM_16K_PG__
-- vm_map_pageshift = FOURK_PAGE_SHIFT;
-+ vm_map_pageshift = PAGE_SHIFT; /* LINUX64: the kernel's VM page (16 KB over a 4 KB granule with linux64_vm16k) */
- #else
- /* enforce 16KB alignment of VM map entries */
- vm_map_pageshift = SIXTEENK_PAGE_SHIFT;
-diff --git a/osfmk/vm/vm_shared_region.c b/osfmk/vm/vm_shared_region.c
-index a9b12f4..263775c 100644
---- a/osfmk/vm/vm_shared_region.c
-+++ b/osfmk/vm/vm_shared_region.c
-@@ -788,7 +788,7 @@ vm_shared_region_create(
- #endif /* CODE_SIGNING_MONITOR */
- int vm_map_pageshift = PAGE_SHIFT;
- #if !defined(APPLE_ARM64_ARCH_FAMILY) && !__ARM_16K_PG__
-- vm_map_pageshift = FOURK_PAGE_SHIFT;
-+ vm_map_pageshift = PAGE_SHIFT; /* LINUX64: as the task maps (mach_loader.c) */
- #else
- if (is_64bit ||
- page_shift_user32 == SIXTEENK_PAGE_SHIFT) {
-diff --git a/osfmk/arm/commpage/commpage.c b/osfmk/arm/commpage/commpage.c
-index 1f672e9..0413ad9 100644
---- a/osfmk/arm/commpage/commpage.c
-+++ b/osfmk/arm/commpage/commpage.c
-@@ -155,8 +155,9 @@ commpage_populate(void)
- *((uint8_t*)(_COMM_PAGE_USER_PAGE_SHIFT_32_LEGACY + _COMM_PAGE_RW_OFFSET)) = (uint8_t) page_shift_user32;
- *((uint8_t*)(_COMM_PAGE_USER_PAGE_SHIFT_32 + _COMM_PAGE_RO_OFFSET)) = (uint8_t) page_shift_user32;
- #if !defined(APPLE_ARM64_ARCH_FAMILY) && !__ARM_16K_PG__
-- *((uint8_t*)(_COMM_PAGE_USER_PAGE_SHIFT_64_LEGACY + _COMM_PAGE_RW_OFFSET)) = (uint8_t) FOURK_PAGE_SHIFT;
-- *((uint8_t*)(_COMM_PAGE_USER_PAGE_SHIFT_64 + _COMM_PAGE_RO_OFFSET)) = (uint8_t) FOURK_PAGE_SHIFT;
-+ /* LINUX64: user maps take the kernel's VM page (mach_loader.c) */
-+ *((uint8_t*)(_COMM_PAGE_USER_PAGE_SHIFT_64_LEGACY + _COMM_PAGE_RW_OFFSET)) = (uint8_t) PAGE_SHIFT;
-+ *((uint8_t*)(_COMM_PAGE_USER_PAGE_SHIFT_64 + _COMM_PAGE_RO_OFFSET)) = (uint8_t) PAGE_SHIFT;
- #else
- *((uint8_t*)(_COMM_PAGE_USER_PAGE_SHIFT_64_LEGACY + _COMM_PAGE_RW_OFFSET)) = (uint8_t) SIXTEENK_PAGE_SHIFT;
- *((uint8_t*)(_COMM_PAGE_USER_PAGE_SHIFT_64 + _COMM_PAGE_RO_OFFSET)) = (uint8_t) SIXTEENK_PAGE_SHIFT;
diff --git a/xnu-patches/include/linux64.h b/xnu-patches/include/linux64.h
index aeb3087..45929be 100644
--- a/xnu-patches/include/linux64.h
+++ b/xnu-patches/include/linux64.h
@@ -30,15 +30,24 @@ extern "C" {
#endif
/*
- * xnu.ko's entry point (0: not hosted) and the slide it applied. TPIDR_EL1 is Linux's per-CPU base: XNU's kernel keeps
- * its thread pointer in TPIDRRO_EL0 (per CPU), and user space gets its TSD there on each return to EL0.
+ * xnu.ko's entry point (0: not hosted), EL0-host flag (1: hosted kernel runs at EL0) and the slide it applied.
+ * TPIDR_EL1 is Linux's per-CPU base (or inaccessible at EL0): XNU's kernel keeps its thread pointer in TPIDR_EL0
+ * (per CPU), and user space gets its own TLS registers on each return to EL0.
*/
extern unsigned long linux64_hook;
extern unsigned long linux64_slide;
-/* This CPU's slot in the per-CPU arrays (LINUX64_CPU_SLOT of its MPIDR): valid before XNU knows its cpu number */
+extern unsigned int linux64_el0;
+extern unsigned int linux64_el0_caps;
+/* This CPU's slot in the per-CPU arrays: valid before XNU knows its cpu number */
static inline unsigned
linux64_cpu_slot(void)
{
+ if (linux64_el0) {
+ unsigned long id;
+
+ __asm__ volatile ("mrs %0, TPIDRRO_EL0" : "=r"(id));
+ return (unsigned)(id & (LINUX64_CPU_SLOTS - 1));
+ }
unsigned long mpidr;
__asm__ volatile ("mrs %0, MPIDR_EL1" : "=r"(mpidr));
@@ -118,6 +127,10 @@ 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));
+struct thread;
+void linux64_el0_fpu_switch_out(struct thread *old);
+void linux64_el0_fpu_flush(struct thread *thread);
+void linux64_el0_fpu_invalidate(struct thread *thread);
/* 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) */
diff --git a/xnu-patches/include/linux64_abi.h b/xnu-patches/include/linux64_abi.h
index 5d0db6d..3833936 100644
--- a/xnu-patches/include/linux64_abi.h
+++ b/xnu-patches/include/linux64_abi.h
@@ -23,10 +23,26 @@
#ifndef _LINUX64_ABI_H_
#define _LINUX64_ABI_H_
-#define LINUX64_ABI_VERSION 3
+#define LINUX64_ABI_VERSION 4
enum linux64_call {
LINUX64_CALL_KERNEL_TABLES = 210, /* boot: a1 = XNU's kernel L1 table; the host installs its kernel-range entries */
+ LINUX64_CALL_KMAP = 211, /* EL0 host: a1 = struct linux64_map_req: map [va, va+size) -> pa in high window */
+ LINUX64_CALL_KUNMAP = 212, /* EL0 host: a1 = struct linux64_map_req: unmap [va, va+size) from high window */
+ LINUX64_CALL_KFLUSH = 213, /* EL0 host: flush high window TLB */
+ LINUX64_CALL_KMAP_TXN = 214, /* EL0 host: a1 = struct linux64_map_req: high-window overwrite rollback txn */
+ LINUX64_CALL_AS_CREATE = 220, /* EL0 host: create user address space */
+ LINUX64_CALL_AS_DESTROY = 221, /* EL0 host: destroy user address space */
+ LINUX64_CALL_AS_MAP = 222, /* EL0 host: map pages in user address space */
+ LINUX64_CALL_AS_UNMAP = 223, /* EL0 host: unmap pages in user address space */
+ LINUX64_CALL_AS_FLUSH = 224, /* EL0 host: flush user address space TLB */
+ /* 225 retired (former LINUX64_CALL_UTCB_RUN before ABI v4 handshake) */
+ LINUX64_CALL_UTCB_FPU_SYNC = 226, /* EL0 host: flush/invalidate user FPU state */
+ LINUX64_CALL_UTCB_RESUME = 227, /* EL0 host: resume user context with unchanged GP regs after PF */
+ LINUX64_CALL_UTCB_SYNC_REGS = 228, /* EL0 host: read full GP regs after a lazy PF stop */
+ LINUX64_CALL_ICACHE_FLUSH = 229, /* EL0 host: a1 = va, a2 = size: cross-CPU icache flush */
+ LINUX64_CALL_USER_PAC_OP = 230, /* EL0 host: a1 = struct linux64_user_pac_req: user JOP key sign/auth */
+ LINUX64_CALL_UTCB_RUN = 231, /* EL0 host: run user context */
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 */
@@ -52,6 +68,84 @@ enum linux64_call {
LINUX64_CALL_USER_ENTER = 9100, /* a1 = user pc: the first entry into user space */
};
+/* Page mapping protection bits (match FKI_PROT_*). */
+#define LINUX64_PROT_READ (1 << 0)
+#define LINUX64_PROT_WRITE (1 << 1)
+#define LINUX64_PROT_EXEC (1 << 2)
+
+/* EL0 host capability bits exported to XNU via linux64_el0_caps. */
+#define LINUX64_EL0_CAP_EXEC_ONLY (1U << 0) /* host supports execute-only (--x) user mappings */
+#define LINUX64_EL0_CAP_XO_COMPAT (1U << 1) /* opt-in: relax --x to r-x when host lacks EXEC_ONLY */
+
+/* High-window overwrite transaction ops (LINUX64_CALL_KMAP_TXN, passed in linux64_map_req.prot). */
+enum {
+ LINUX64_KMAP_TXN_BEGIN = 0,
+ LINUX64_KMAP_TXN_RESTORE = 1,
+ LINUX64_KMAP_TXN_END = 2,
+};
+
+/* Kernel/user page mapping request for EL0 hosts (LINUX64_CALL_KMAP/KUNMAP/KMAP_TXN/AS_*). */
+struct linux64_map_req {
+ __UINT64_TYPE__ as_handle;
+ __UINT64_TYPE__ va;
+ __UINT64_TYPE__ pa;
+ __UINT64_TYPE__ size;
+ __UINT64_TYPE__ prot;
+ __INT64_TYPE__ result;
+};
+
+/* User-context stop reasons (match FKI_STOP_*). */
+enum {
+ LINUX64_STOP_SYSCALL = 1,
+ LINUX64_STOP_PAGEFAULT = 2,
+ LINUX64_STOP_EXCEPTION = 3,
+ LINUX64_STOP_INTERRUPT = 4,
+};
+
+/* User-context FPU sync request for EL0 hosts (LINUX64_CALL_UTCB_FPU_SYNC). */
+#define LINUX64_FPU_FLUSH (1U << 0)
+#define LINUX64_FPU_INVALIDATE (1U << 1)
+
+struct linux64_fpu_sync_req {
+ __UINT64_TYPE__ thread_id;
+ __UINT64_TYPE__ neon_ptr; /* &thread->machine.uNeon->ns_64 (520B) */
+ __UINT32_TYPE__ flags;
+ __INT32_TYPE__ result;
+};
+
+/* User-context execution request for EL0 hosts (LINUX64_CALL_UTCB_RUN). */
+struct linux64_utcb_req {
+ __UINT64_TYPE__ as_handle;
+ __UINT64_TYPE__ thread_id;
+ __UINT64_TYPE__ disable_jop;
+ __UINT64_TYPE__ rop_pid;
+ __UINT64_TYPE__ jop_pid;
+ __UINT64_TYPE__ x[31];
+ __UINT64_TYPE__ sp, pc, pstate, tpidr, tpidrro;
+ __UINT64_TYPE__ neon_ptr; /* &thread->machine.uNeon->ns_64 (520B) */
+ __UINT32_TYPE__ fpu_dirty;
+ __INT32_TYPE__ stop_kind;
+ __UINT64_TYPE__ fault_addr, fault_ip, esr;
+ __INT64_TYPE__ result;
+};
+
+/* User JOP-key PAC sign/auth request for EL0 hosts (LINUX64_CALL_USER_PAC_OP). */
+enum {
+ LINUX64_PAC_KEY_IA = 0,
+ LINUX64_PAC_KEY_DA = 2,
+};
+
+struct linux64_user_pac_req {
+ __UINT64_TYPE__ value;
+ __UINT64_TYPE__ discriminator;
+ __UINT64_TYPE__ jop_key;
+ __UINT64_TYPE__ result;
+ __UINT32_TYPE__ key; /* LINUX64_PAC_KEY_IA or LINUX64_PAC_KEY_DA */
+ __UINT32_TYPE__ is_auth; /* 0: sign, 1: auth */
+ __INT32_TYPE__ err; /* 0 on success, negative Linux errno on PAC swap failure */
+ __UINT32_TYPE__ reserved;
+};
+
/* A buffer: bytes to send or room to receive into. */
struct linux64_buf_req {
void *buf;