XNU as a loadable kernel module inside Linux (macOS personality for arm64 Linux)
C
M2b step 1: XNU at its link address in the top window on real contiguous memory (mode=3)
Heyang Zhoube2593c2260b
diff --git a/fki-ko/fki.h b/fki-ko/fki.hindex 99cb768..5fe0bf8 100644--- a/fki-ko/fki.h+++ b/fki-ko/fki.h@@ -52,6 +52,18 @@ void 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);+/*+ * Physically contiguous memory with real physical addresses (for a foreign kernel whose own page tables+ * the hardware walks). va is a kernel linear-map address (RW, not executable). size rounds up to a power of two.+ */+int fki_contig_alloc(unsigned long size, struct fki_region *r);+void fki_contig_free(struct fki_region *r);+/*+ * The top foreign window: the L1 table that Linux's TTBR1 L0 entry for va points to. A foreign kernel may+ * own L1 entries Linux leaves empty in that table; fki_window_set installs one (then a full TLB flush).+ */+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);/* Keep the calling task on one CPU (the hosted kernel sees that CPU's MPIDR). */int fki_bind_cpu(int cpu);#ifdef __cplusplusdiff --git a/fki-ko/fki_mod.c b/fki-ko/fki_mod.cindex 00b0e31..07cc3de 100644--- a/fki-ko/fki_mod.c+++ b/fki-ko/fki_mod.c@@ -21,6 +21,8 @@#include <linux/vmalloc.h>#include <asm/arch_timer.h>#include <asm/sysreg.h>+#include <asm/tlbflush.h>+#include <asm/barrier.h>#include <linux/kprobes.h>int fki_version(void)@@ -41,6 +43,10 @@ EXPORT_SYMBOL(fki_log);* 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;static set_memory_fn p_set_memory_x, p_set_memory_nx;static int fki_resolve(void)@@ -57,6 +63,10 @@ static int fki_resolve(void)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_set_memory_nx = (set_memory_fn)lookup("set_memory_nx");return p_set_memory_x && p_set_memory_nx ? 0 : -ENOENT;}@@ -191,5 +201,62 @@ int fki_bind_cpu(int cpu)}EXPORT_SYMBOL(fki_bind_cpu);+/* ---- contiguous memory and the top foreign window ---- */++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 (!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 (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);+MODULE_LICENSE("GPL");MODULE_DESCRIPTION("Foreign kernel interface v0 (out-of-tree form for stock kernels)");diff --git a/linux/include/linux/fki.h b/linux/include/linux/fki.hindex 99cb768..5fe0bf8 100644--- a/linux/include/linux/fki.h+++ b/linux/include/linux/fki.h@@ -52,6 +52,18 @@ void 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);+/*+ * Physically contiguous memory with real physical addresses (for a foreign kernel whose own page tables+ * the hardware walks). va is a kernel linear-map address (RW, not executable). size rounds up to a power of two.+ */+int fki_contig_alloc(unsigned long size, struct fki_region *r);+void fki_contig_free(struct fki_region *r);+/*+ * The top foreign window: the L1 table that Linux's TTBR1 L0 entry for va points to. A foreign kernel may+ * own L1 entries Linux leaves empty in that table; fki_window_set installs one (then a full TLB flush).+ */+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);/* Keep the calling task on one CPU (the hosted kernel sees that CPU's MPIDR). */int fki_bind_cpu(int cpu);#ifdef __cplusplusdiff --git a/xnu-ko/macho.c b/xnu-ko/macho.cindex 22645f1..a1b5c17 100644--- a/xnu-ko/macho.c+++ b/xnu-ko/macho.c@@ -12,6 +12,7 @@ int macho_load(struct xnu_image *img, const void *file, unsigned long size, unsi{const struct mh64 *mh = file;int err;+ (void)err;img->file = file; img->file_size = size;if (size < sizeof(*mh) || mh->magic != MH_MAGIC_64)@@ -40,16 +41,24 @@ int macho_load(struct xnu_image *img, const void *file, unsigned long size, unsi}if (img->vmhigh <= img->vmlow)return -ENOEXEC;+ if (extra == ~0UL) /* parse only: the caller places the image (macho_copy) */+ return 0;err = fki_region_alloc(img->vmhigh - img->vmlow + extra, &img->region);if (err)return err;img->slide = (u64_t)img->region.va - img->vmlow;+ return macho_copy(img, img->region.va);+}++/* Copy the segments to dst, which is where vmlow will live. */+int macho_copy(struct xnu_image *img, void *dst)+{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 > size) return -ENOEXEC;- x_memcpy((char *)img->region.va + (s->vmaddr - img->vmlow), img->file + s->fileoff, s->filesize);+ if (s->fileoff + s->filesize > img->file_size) return -ENOEXEC;+ x_memcpy((char *)dst + (s->vmaddr - img->vmlow), img->file + s->fileoff, s->filesize);}return 0;}diff --git a/xnu-ko/macho.h b/xnu-ko/macho.hindex dd29902..53e5b18 100644--- a/xnu-ko/macho.h+++ b/xnu-ko/macho.h@@ -27,6 +27,7 @@ struct xnu_image {};int macho_load(struct xnu_image *img, const void *file, unsigned long size, unsigned long extra);+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);u64_t macho_sym(struct xnu_image *img, const char *name); /* runtime address or 0 */diff --git a/xnu-ko/xnu_main.c b/xnu-ko/xnu_main.cindex 667dea5..09cbab8 100644--- a/xnu-ko/xnu_main.c+++ b/xnu-ko/xnu_main.c@@ -120,14 +120,14 @@ long xnu_hook(unsigned long stage, unsigned long a1, unsigned long a2)return (long)stage >= stop;}-static int run_m2a(void)+/*+ * Boot handoff. The XNU "DRAM" region is described by (virtBase, physBase, size): XNU sees base_va as the+ * kernel virtual address of physBase. The image's vmlow sits at base_va + image_off.+ */+static struct boot_args_v2 *build_boot(unsigned char *base_va, u64_t phys, u64_t size, u64_t image_off, u64_t image_size){- u64_t image_size = img.vmhigh - img.vmlow;- unsigned char *base = img.region.va;- unsigned long region = img.region.size;- /* region: [image][boot args][ADT][free "DRAM" ...] */- u64_t off_args = (image_size + 0x3fff) & ~0x3fffULL;- struct boot_args_v2 *ba = (void *)(base + off_args);+ u64_t off_args = (image_off + image_size + 0x3fff) & ~0x3fffULL;+ struct boot_args_v2 *ba = (void *)(base_va + off_args);u64_t off_dt = off_args + 0x4000;struct adt a;static unsigned char seed[256];@@ -135,21 +135,22 @@ static int run_m2a(void)fki_random(seed, sizeof(seed));/* XNU identifies its CPU by MPIDR: run on CPU 0 and describe exactly that CPU. */int berr = fki_bind_cpu(0);- if (berr) { logkv("xnu: cannot bind to cpu0, err", (u64_t)berr); return berr; }+ if (berr) { logkv("xnu: cannot bind to cpu0, err", (u64_t)berr); return 0; }u64_t mpidr; __asm__ volatile("mrs %0, mpidr_el1" : "=r"(mpidr));mpidr &= 0xffff; /* XNU compares Aff1:Aff0 */logkv("xnu: running on MPIDR Aff1:Aff0", mpidr);- adt_init(&a, base + off_dt, 0x10000);++ adt_init(&a, base_va + off_dt, 0x10000);adt_node(&a, 3, 3); /* / */adt_prop_str(&a, "name", "device-tree");adt_prop_str(&a, "compatible", "xnulinux,linux64");adt_prop_str(&a, "model", "xnulinux");adt_node(&a, 6, 0); /* /chosen */adt_prop_str(&a, "name", "chosen");- adt_prop_u64(&a, "dram-base", XNU_FAKE_PHYS);- adt_prop_u64(&a, "dram-size", region);+ adt_prop_u64(&a, "dram-base", phys);+ adt_prop_u64(&a, "dram-size", size);adt_prop(&a, "random-seed", seed, sizeof(seed));- adt_prop_str(&a, "firmware-version", "xnulinux-m2a");+ adt_prop_str(&a, "firmware-version", "xnulinux-m2");adt_prop_u32(&a, "debug-enabled", 1);adt_node(&a, 1, 1); /* /cpus */adt_prop_str(&a, "name", "cpus");@@ -164,23 +165,26 @@ static int run_m2a(void)adt_prop_str(&a, "name", "arm-io");adt_prop_str(&a, "device_type", "linux64-io");{ u64_t ranges[3] = { 0, 0x7000000000ULL, 0x10000000ULL }; adt_prop(&a, "ranges", ranges, sizeof(ranges)); }- if (a.err) { logs("xnu: ADT overflow"); return -12; }+ if (a.err) { logs("xnu: ADT overflow"); return 0; }u64_t dt_len = adt_size(&a);ba->Revision = 2; ba->Version = 2;- ba->virtBase = (u64_t)base;- ba->physBase = XNU_FAKE_PHYS;- ba->memSize = region;- ba->memSizeActual = region;- ba->topOfKernelData = XNU_FAKE_PHYS + ((off_dt + dt_len + 0x3fff) & ~0x3fffULL);- ba->deviceTreeP = base + off_dt;+ ba->virtBase = (u64_t)base_va;+ ba->physBase = phys;+ ba->memSize = size;+ ba->memSizeActual = size;+ ba->topOfKernelData = phys + ((off_dt + dt_len + 0x3fff) & ~0x3fffULL);+ ba->deviceTreeP = base_va + off_dt;ba->deviceTreeLength = (unsigned)dt_len;x_memcpy(ba->CommandLine, cmdline, x_strlen(cmdline) + 1);logkv("xnu: boot args at", (u64_t)ba);logkv("xnu: ADT bytes", dt_len);- logkv("xnu: topOfKernelData (XNU phys)", ba->topOfKernelData);+ logkv("xnu: topOfKernelData (phys)", ba->topOfKernelData);+ return ba;+}- /* Slide and sign here (XNU skips its own rebase when hosted). */+static int enter_arm_init(struct boot_args_v2 *ba)+{struct fki_pac_keys saved; unsigned long c = fki_enter(&xnu_W.xnu_keys, &saved);int n = macho_rebase(&img);fki_leave(c, &saved);@@ -203,6 +207,62 @@ static int run_m2a(void)return 0;}+/* M2a: the image in a vmalloc region with synthetic physical addresses. */+static int run_m2a(void)+{+ u64_t image_size = img.vmhigh - img.vmlow;+ struct boot_args_v2 *ba = build_boot(img.region.va, XNU_FAKE_PHYS, img.region.size, 0, image_size);+ if (!ba) return -22;+ return enter_arm_init(ba);+}++/*+ * M2b: XNU at its own link address in the top foreign window, on physically contiguous memory with real+ * physical addresses, so that the page tables XNU builds can be walked by the hardware.+ */+#define XNU_WINDOW_BASE 0xfffffff007000000ULL /* 2 MiB aligned, at or below the image's vmlow */+static struct fki_region l2page;+static unsigned long long *window_slot;++static int run_m2b(void)+{+ u64_t image_size = img.vmhigh - img.vmlow;+ if (img.vmlow < XNU_WINDOW_BASE || img.vmlow - XNU_WINDOW_BASE >= 0x200000) { logs("xnu: unexpected link address"); return -22; }+ u64_t image_off = img.vmlow - XNU_WINDOW_BASE;+ u64_t want = image_off + image_size + 0x20000 + ((u64_t)ram_mb << 20);+ int err = fki_contig_alloc(want, &img.region);+ if (err) { logkv("xnu: contiguous allocation failed, err", (u64_t)err); return err; }+ logkv("xnu: contiguous DRAM at phys", img.region.pa);+ logkv("xnu: contiguous DRAM size", img.region.size);+ if ((img.region.pa & 0x1fffff) || img.region.size > (1ULL << 30)) { logs("xnu: region not 2 MiB aligned or above 1 GiB"); return -22; }++ err = fki_contig_alloc(4096, &l2page);+ if (err) return err;+ unsigned long long *l2 = l2page.va;+ unsigned first = (XNU_WINDOW_BASE >> 21) & 511;+ for (u64_t o = 0; o < img.region.size; o += 0x200000) {+ /* 2 MiB block: normal WB (AttrIdx 0 in Linux's MAIR), inner shareable, AF, EL1 RWX, UXN */+ l2[first + (o >> 21)] = (img.region.pa + o) | (1ULL << 54) | (1ULL << 10) | (3ULL << 8) | 1;+ }+ unsigned long long *l1; fki_u64 l1pa;+ err = fki_window_l1(XNU_WINDOW_BASE, &l1, &l1pa);+ if (err) { logs("xnu: no L1 table for the top window"); return err; }+ unsigned idx = (XNU_WINDOW_BASE >> 30) & 511;+ logkv("xnu: top window L1 table at phys", l1pa);+ logkv("xnu: L1 slot", idx);+ if (l1[idx]) { logkv("xnu: L1 slot already used by Linux:", l1[idx]); return -16; }+ window_slot = &l1[idx];+ fki_window_set(window_slot, l2page.pa | 3);+ logs("xnu: bootstrap window mapped");++ unsigned char *base = (unsigned char *)XNU_WINDOW_BASE;+ macho_copy(&img, base + image_off);+ 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 int __init xnu_init(void){const void *data; unsigned long size;@@ -212,22 +272,28 @@ static int __init xnu_init(void)return -22;err = fki_blob_get(image, &data, &size, &blob);if (err) { logkv("xnu: cannot read image, err", (u64_t)err); return err; }- err = macho_load(&img, data, size, mode == 2 ? (unsigned long)ram_mb << 20 : 0);+ 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; }logkv("xnu: image vmlow", img.vmlow);logkv("xnu: image size", img.vmhigh - img.vmlow);- logkv("xnu: region at", (u64_t)img.region.va);- logkv("xnu: region size", img.region.size);+ if (mode != 3) {+ logkv("xnu: region at", (u64_t)img.region.va);+ logkv("xnu: region size", img.region.size);+ }fki_random(&xnu_W.xnu_keys, sizeof(xnu_W.xnu_keys));xnu_W.xnu_keys.sctlr_en = ~0ULL;- return mode == 1 ? run_m1() : run_m2a();+ return mode == 1 ? run_m1() : mode == 3 ? run_m2b() : run_m2a();}static void __exit xnu_exit(void){- if (img.region.va) fki_region_free(&img.region);+ if (window_slot) fki_window_set(window_slot, 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);}