Skip to content

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

C

Host GPU for sandboxed processes; the hosted kernel's DRAM reserved at host boot

Heyang Zhoufde88c4ce3fa
diff --git a/fki-ko/fki_mod.c b/fki-ko/fki_mod.c
index ef4a7ec..cb6ea91 100644
--- a/fki-ko/fki_mod.c
+++ b/fki-ko/fki_mod.c
@@ -374,6 +374,29 @@ EXPORT_SYMBOL(fki_phys_peek);
/* ---- contiguous memory and the top foreign window ---- */
+/*
+ * reserve_mb: take that much from the CMA area when fki loads (early in the host's boot, while the area is clean) and
+ * keep it for the foreign kernel's DRAM. Later, a single page the host pinned in the middle of the area (a buffer-head
+ * page of a file system, say) is enough to make a multi-GB cma_alloc fail for good.
+ */
+static unsigned long reserve_mb;
+module_param(reserve_mb, ulong, 0444);
+static struct page *resv_pg;
+static unsigned long resv_cnt;
+static bool resv_used;
+
+static void fki_reserve(void)
+{
+ unsigned long cnt = ALIGN(reserve_mb << 20, SZ_2M) >> PAGE_SHIFT;
+
+ 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)");
+}
+
int fki_contig_alloc(unsigned long size, struct fki_region *r)
{
unsigned long n = 1;
@@ -382,6 +405,15 @@ int fki_contig_alloc(unsigned long size, struct fki_region *r)
if (err)
return err;
+ 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
@@ -417,6 +449,10 @@ EXPORT_SYMBOL(fki_contig_alloc);
void fki_contig_free(struct fki_region *r)
{
+ 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;
@@ -695,6 +731,7 @@ static int __init fki_init(void)
int err;
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);
@@ -719,6 +756,8 @@ static int __init fki_init(void)
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);
diff --git a/gpu/xnu-drm/darwin/xnudrm.c b/gpu/xnu-drm/darwin/xnudrm.c
index aa4fddf..66aa939 100644
--- a/gpu/xnu-drm/darwin/xnudrm.c
+++ b/gpu/xnu-drm/darwin/xnudrm.c
@@ -50,9 +50,11 @@ static int debug(void) { static int d = -1; if (d < 0) d = getenv("XNUDRM_DEBUG"
static int open_conn(io_connect_t *c)
{
- io_service_t sv = IOServiceGetMatchingService(kIOMainPortDefault, IOServiceMatching("XnuDrm"));
+ /* the user client hangs off the Metal accelerator (an IOAccelerator: sandboxes let drawing processes open it) */
+ io_service_t sv = IOServiceGetMatchingService(kIOMainPortDefault, IOServiceMatching("XnuCpuMetalAccelerator"));
+ if (!sv) sv = IOServiceGetMatchingService(kIOMainPortDefault, IOServiceMatching("XnuDrm"));
if (!sv) { if (debug()) fprintf(stderr, "xnudrm: no XnuDrm service\n"); return -ENODEV; }
- kern_return_t kr = IOServiceOpen(sv, mach_task_self(), 0, c);
+ kern_return_t kr = IOServiceOpen(sv, mach_task_self(), XNUDRM_CONNECT_TYPE, c);
IOObjectRelease(sv);
if (kr != KERN_SUCCESS) { if (debug()) fprintf(stderr, "xnudrm: IOServiceOpen %#x\n", kr); return -EIO; }
if (!buf) buf = malloc(sizeof(struct xnudrm_hdr) + XNUDRM_MAX_MSG);
diff --git a/gpu/xnu-drm/xnudrm_proto.h b/gpu/xnu-drm/xnudrm_proto.h
index d838999..ec345f6 100644
--- a/gpu/xnu-drm/xnudrm_proto.h
+++ b/gpu/xnu-drm/xnudrm_proto.h
@@ -14,6 +14,7 @@
#define XNUDRM_MAGIC 0x4d52444eu /* "NDRM" */
#define XNUDRM_VERSION 1
#define XNUDRM_MAX_MSG (8u << 20)
+#define XNUDRM_CONNECT_TYPE 0x584e4452u /* IOServiceOpen type of the bridge's user client: 'XNDR' */
/* status is a Linux errno; the ones a client tests by value (macOS numbers some differently: ETIME is 101 there) */
#define XNUDRM_ETIME 62
diff --git a/kexts/XnuCpuMetal/XnuCpuMetal.cpp b/kexts/XnuCpuMetal/XnuCpuMetal.cpp
index 86d2773..a1cdc4c 100644
--- a/kexts/XnuCpuMetal/XnuCpuMetal.cpp
+++ b/kexts/XnuCpuMetal/XnuCpuMetal.cpp
@@ -29,6 +29,9 @@ bool XnuCpuMetalAccelerator::start(IOService *provider)
// No "Removable" / "SafeEjectRequested": Metal (-[MTLIOAccelService initWithAcceleratorPort:deviceClass:]) skips
// a service on which either is present at all, whatever the value.
setProperty("model", "XnuCpuMetal (lavapipe)");
+ // The GPU bridge's user client (kexts/XnuDrm) hangs off this service: the sandbox's system-graphics rules let
+ // processes that draw open user clients of an IOAccelerator ((iokit-connection "IOAccelerator")), whatever their class.
+ setProperty("IOUserClientClass", "AGXDeviceUserClient");
registerService();
IOLog("xnucpumetal: Metal accelerator published on %s\n", provider->getName());
return true;
diff --git a/kexts/XnuDrm/XnuDrm.cpp b/kexts/XnuDrm/XnuDrm.cpp
index a4b140e..f2172e7 100644
--- a/kexts/XnuDrm/XnuDrm.cpp
+++ b/kexts/XnuDrm/XnuDrm.cpp
@@ -4,9 +4,11 @@
// fki) answered by xnudrmd, the Linux service that owns the DRM render node. Buffer mappings come back as the physical
// pages Linux mapped, which this kext maps into the calling task: the process and the GPU share the memory, no copies.
//
-// The user client's class is named AGXDeviceUserClient, the name Apple GPUs' device user client has: the sandbox profiles
-// of the processes that draw (apps, WebKit's GPU process, agents) let them open user clients of that class and of few
-// others, and refuse any other (MACF: "IOUC ... failed MACF"). No AGX kext is in the hosted collection, so the name is free.
+// Processes open the user client on the Metal accelerator service (kexts/XnuCpuMetal names it as its IOUserClientClass):
+// the sandbox profiles of processes that draw allow user clients of an IOAccelerator (system.sb's system-graphics) and
+// refuse others ("IOUC ... failed MACF"). The class is named AGXDeviceUserClient, Apple GPUs' device user client, which
+// the profiles that list classes by name admit too; no AGX kext is in the hosted collection, so the name is free. The
+// XnuDrm service itself only says the bridge is there.
//
// Methods (IOConnectCallScalarMethod):
// 0 call(in_ptr, in_len, out_ptr, out_max) -> reply_len a message for xnudrmd (xnudrm_proto.h), client id filled in
@@ -63,15 +65,19 @@ public:
OSDefineMetaClassAndStructors(XnuDrm, IOService)
OSDefineMetaClassAndStructors(AGXDeviceUserClient, IOUserClient)
+static bool bridgeInit()
+{
+ if (gCallLock) return true;
+ gIn = (uint8_t *)IOMallocData(sizeof(xnudrm_hdr) + XNUDRM_MAX_MSG);
+ gOut = (uint8_t *)IOMallocData(sizeof(xnudrm_hdr) + XNUDRM_MAX_MSG);
+ gCallLock = gIn && gOut ? IOLockAlloc() : nullptr;
+ return gCallLock != nullptr;
+}
+
bool XnuDrm::start(IOService *provider)
{
if (!IOService::start(provider)) return false;
- if (!gCallLock) {
- gCallLock = IOLockAlloc();
- gIn = (uint8_t *)IOMallocData(sizeof(xnudrm_hdr) + XNUDRM_MAX_MSG);
- gOut = (uint8_t *)IOMallocData(sizeof(xnudrm_hdr) + XNUDRM_MAX_MSG);
- if (!gCallLock || !gIn || !gOut) return false;
- }
+ if (!bridgeInit()) return false;
setProperty("IOUserClientClass", "AGXDeviceUserClient");
registerService();
IOLog("XnuDrm: GPU bridge ready\n");
@@ -80,7 +86,10 @@ bool XnuDrm::start(IOService *provider)
bool AGXDeviceUserClient::initWithTask(task_t owningTask, void *securityID, UInt32 type)
{
+ // only libxnudrm's opens (type 'XNDR'): Metal or anything else opening the accelerator gets no bridge client
+ if (type != XNUDRM_CONNECT_TYPE) return false;
if (!IOUserClient::initWithTask(owningTask, securityID, type)) return false;
+ if (!bridgeInit()) return false; // opened on the accelerator before XnuDrm started
fTask = owningTask;
xnudrm_hdr r;
long n = simple(XNUDRM_OPEN, XNUDRM_VERSION, 0, &r);
diff --git a/scripts/vm-install-fki-service.sh b/scripts/vm-install-fki-service.sh
new file mode 100755
index 0000000..bf33420
--- /dev/null
+++ b/scripts/vm-install-fki-service.sh
@@ -0,0 +1,24 @@
+#!/bin/bash
+# In the VM (once): load fki.ko early in every boot, reserving the hosted kernel's DRAM while the CMA area is still clean
+# (fki reserve_mb). xnulinux-boot.sh then finds fki loaded with the reservation and uses it.
+set -euo pipefail
+P=$(cd "$(dirname "$0")/.." && pwd)
+RESERVE_MB=${RESERVE_MB:-8156}
+sudo tee /etc/systemd/system/xnulinux-fki.service >/dev/null <<UNIT
+[Unit]
+Description=xnulinux: fki.ko with the hosted kernel's DRAM reserved
+DefaultDependencies=no
+After=local-fs.target
+Before=sysinit.target
+
+[Service]
+Type=oneshot
+RemainAfterExit=yes
+ExecStart=/usr/sbin/insmod $P/fki-ko/fki.ko reserve_mb=$RESERVE_MB
+
+[Install]
+WantedBy=sysinit.target
+UNIT
+sudo systemctl daemon-reload
+sudo systemctl enable xnulinux-fki.service
+echo "fki.ko loads at boot with reserve_mb=$RESERVE_MB (rebuild fki-ko before a reboot when it changes)"
diff --git a/scripts/xnulinux-boot.sh b/scripts/xnulinux-boot.sh
index fff16b2..60caa70 100755
--- a/scripts/xnulinux-boot.sh
+++ b/scripts/xnulinux-boot.sh
@@ -25,19 +25,26 @@ build() { # a module; its compiler errors on failure
build fki-ko
build xnu-ko "KBUILD_EXTRA_SYMBOLS=$PWD/fki-ko/Module.symvers"
sudo dmesg -n "${CONLEVEL:-8}"
-sudo systemctl stop xnudrmd 2>/dev/null || true # it holds fki's /dev/xnu-hostcall
-sudo rmmod fki 2>/dev/null || true
-sudo insmod fki-ko/fki.ko
+# fki keeps the hosted kernel's DRAM reserved from when it first loaded (reserve_mb): reload it only when it changed
+RESERVE_MB=${RESERVE_MB:-8156} # the same as scripts/vm-install-fki-service.sh
+if [ "$(cat /sys/module/fki/srcversion 2>/dev/null)" != "$(modinfo -F srcversion fki-ko/fki.ko)" ]; then
+ sudo systemctl stop xnudrmd 2>/dev/null || true # it holds fki's /dev/xnu-hostcall
+ sudo rmmod fki 2>/dev/null || true
+ sudo insmod fki-ko/fki.ko reserve_mb="$RESERVE_MB"
+fi
+grep -q . /sys/module/fki/parameters/reserve_mb 2>/dev/null && [ "$(cat /sys/module/fki/parameters/reserve_mb)" != 0 ] ||
+ echo "fki loaded without a DRAM reservation: the allocation may fail on a long-running host" >&2
bash scripts/vm-net-up.sh
# the hosted system's files on the host: console and input queues, the framebuffer xnu.ko writes, the keystore
: > "$CONSOLE_IN"; : > "$INPUT_IN"; : > "$FB_DUMP"
rm -f "$KEYSTORE"; truncate -s 1M "$KEYSTORE" # fresh each boot, as the disk was made (persisting it: production.md)
# XNU's DRAM is one physically contiguous block (GBs, from CMA): free the page cache and compact first. Right after the VM
-# boots the allocation can still fail with the area free (pages not yet migratable): wait and try again.
+# boots the allocation can still fail with the area free (a page in the way not yet migratable): wait and try again,
+# for up to three minutes.
# mode=3: the kernel collection; the run lasts until the hosted system halts (no stage stop, no line or idle budget).
# insmod returns when the run ends: it runs detached, its output in /var/tmp/xnu-insmod.log.
-for try in 1 2 3 4; do
+for try in 1 2 3 4 5 6 7 8 9; do
sync; echo 3 | sudo tee /proc/sys/vm/drop_caches >/dev/null; echo 1 | sudo tee /proc/sys/vm/compact_memory >/dev/null
sudo dmesg -C
sudo setsid nohup insmod xnu-ko/xnu.ko mode=3 stop=899 kmax=1000000000 idle_max=2000000000 ram_mb="$RAM_MB" image="$IMAGE" \
@@ -46,7 +53,7 @@ for try in 1 2 3 4; do
> /var/tmp/xnu-insmod.log 2>&1 < /dev/null &
sleep 5
sudo dmesg | grep -aq "contiguous allocation failed" || break
- [ $try = 4 ] && { echo "no contiguous memory for XNU (CMA: $(grep CmaFree /proc/meminfo))" >&2; exit 1; }
+ [ $try = 9 ] && { echo "no contiguous memory for XNU (CMA: $(grep CmaFree /proc/meminfo))" >&2; exit 1; }
echo "no contiguous memory for XNU yet: trying again in 20 s"; sleep 20
done
if [ "$GPU" != off ] && [ -e /dev/dri/renderD128 ]; then