Skip to content

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

C

GPU: a DRM bridge from the hosted macOS to Linux's render node; Venus on the host GPU

Heyang Zhoub30ffd5f73fc
diff --git a/docs/production.md b/docs/production.md
new file mode 100644
index 0000000..f1e35a9
--- /dev/null
+++ b/docs/production.md
@@ -0,0 +1,64 @@
+# From PoC to production
+
+What the PoC did to get each step running, and what replaces it. Ordered by what it costs if left in place.
+
+## 1. XNU patches
+
+| Now | Replace with |
+|---|---|
+| One 4300-line patch (`xnu-patches/0001-linux64-stage-hook.patch`, 61 files) | A topic series: `00xx-linux64-{config,el0,pmap,timer,upcall,iokit-platform,bsd-root,syscalls,amfi,debug}.patch`, each building on its own |
+| `extern uintptr_t linux64_hook;` declared inline at ~60 call sites, `if (linux64_hook)` as the hosted test | One header (`osfmk/arm64/linux64.h`): `linux64_hosted()`, typed upcall wrappers; code under `CONFIG_LINUX64` so a non-hosted build is the stock kernel |
+| Debug instrumentation in the hot paths (`linux64_dbg[16]` counters in the idle loop, scheduler, EL0 entry; a thread dump every 150000 idle rounds; `DEBUG_BSDINIT 1`) | Behind `LINUX64_DEBUG` (off by default), thread dump on demand (an upcall from the host), not on an idle counter |
+| Dead paths from earlier milestones: the BSD `ifnet` half of `bsd/net/if_linux64.c` (`kexts/XnuEthernet` is en0 now; only its frame transport stays, as ABI calls), memdev host mode `hostdisk=` (replaced by `kexts/XnuDisk`), HFS+ read-write root | Removed |
+
+## 2. The xnu.ko ↔ XNU boundary
+
+| Now | Replace with |
+|---|---|
+| Upcalls are bare stage numbers (810–821, 993–995) with ad-hoc argument structs | `xnu-ko/linux64_abi.h`, shared by both sides: an enum of named calls, one request struct per call, a version number checked at load |
+| Console input, input events, framebuffer: host files appended to or dumped on a timer (`console_in=`, `input_in=`, `fb_dump=`) | Character devices from fki.ko (`/dev/xnu/console`, `/dev/xnu/input`, `/dev/xnu/fb` with mmap), so a host program talks to them like any device |
+| Module parameters for everything (`stop`, `kmax`, `idle_max`, `mode`, bisecting knobs) | Drop the PoC-only ones; the run ends when XNU halts, not on a counter |
+
+## 3. Boot and the system disk
+
+| Now | Replace with |
+|---|---|
+| `mk-macvm-disk.sh` merges the OS cryptex into the sealed System volume (breaks the seal) | Graft the OS and App cryptexes at boot as macOS does (`graftdmg`), so the System volume stays sealed and an OS update replaces only the cryptex |
+| `kc-amfi-platform.py` patches AMFI's expected platform version in the kernel collection | Build the collection from the same macOS build as the disk (one version source), no byte patching |
+| `amfi_get_out_of_my_way=1`, `lp-sip0=0x802`, `kern.memorystatus_highwater_enabled=0` | Keep SIP/AMFI on; sign our plugin and kexts (ad-hoc trust cache of our own), only the unauthenticated-root bit stays |
+| `/chosen` UUIDs passed by hand (`root_uuid=`, `preboot_uuid=`) | Read from the disk's APFS container at load (xnu.ko or a host tool), no manual parameters |
+
+## 4. Scripts and tests
+
+| Now | Replace with |
+|---|---|
+| ~30 scripts; the boot itself runs from `vm-m2-kbisect.sh` (`mode=3 stop=899 kmax=…`, a bisecting tool's knobs); several have session paths (`/Users/admin/...`), tty names, fixed `sleep`s | One driver (`xnulinux` CLI): `build`, `disk`, `boot`, `console`, `screenshot`, `test`; configuration in one file |
+| HFS+ route scripts (`mk-fulldisk.sh`, `vm-sysdisk-*`, `vm-mk-sysdisk.sh`, `vm-m2-*`, `run-poc.sh`) | Removed (APFS route only) |
+| `tools/hosted/tests/t*.sh`, `af*.sh`: one-off probes | A test suite with expected results: boot to desktop, Safari/Chrome page load (screenshot compare), `xcodebuild` of a pinned project, Metal unit tests |
+| No CI | CI: fki.ko/xnu.ko build against a pinned kernel, XNU + collection build (x86_64 Linux works with the DroidVM toolchain), GPU plugin host tests on macOS |
+
+## 5. GPU
+
+| Now | Replace with |
+|---|---|
+| CPU only: Metal → metal2vulkan → lavapipe in every process (WindowServer's GPU work runs on the CPU) | Hardware: the same plugin over Mesa's Vulkan driver for the host's GPU, through a DRM bridge (below) |
+
+The DRM bridge: a Mesa Vulkan driver built for Darwin runs in the macOS process; its DRM calls go to an IOKit user client
+(`kexts/XnuDrm`) and through FKI to the Linux DRM device. Buffer objects are Linux pages mapped straight into the macOS task
+(same physical memory, no copies). On an Apple Silicon host the Linux DRM device is virtio-gpu with Venus (krunkit:
+Venus → MoltenVK → Metal on the host GPU); on a Linux machine with its own GPU it is that GPU's driver.
+
+### Status of the bridge
+
+- Linux under krunkit (`scripts/krun-vm.sh`) sees the host GPU through Venus: `Virtio-GPU Venus (Apple M5 Max)`, and
+ `gpu/venus/test/compute.c` (a compute dispatch over 16 MB of host-visible memory) reads back correct results. Mesa needs
+ 16 KiB blob alignment for a macOS host (`gpu/venus/patches/0001`). Mesa 25.x also refused a renderer without
+ `VK_KHR_external_memory_fd` (virglrenderer on macOS shares mappings in-process instead of exporting fds); 26.x no longer
+ checks.
+- The bridge works end to end: in the hosted macOS, `gpu/venus/test/compute.c` built for macOS loads the Darwin Venus
+ driver (`gpu/venus/build-darwin.sh`), sees `Virtio-GPU Venus (Apple M5 Max)` and its compute dispatch over 16 MB of
+ shared memory reads back correct results (6.7 ms). Pieces: `fki-ko/fki_hostcall.c` (`/dev/xnu-hostcall`), xnu.ko
+ upcall 830, `kexts/XnuDrm` (user client; maps Linux's pages into the task), `gpu/xnu-drm/xnudrmd.c` (Linux service on
+ the render node), `gpu/xnu-drm/darwin` (libxnudrm, compiled into Mesa by `gpu/venus/patches/0002`).
+- Next: the Metal plugin on this driver instead of lavapipe (arm64e build, IOSurface sharing), so WindowServer and apps
+ render on the host GPU.
diff --git a/fki-ko/Makefile b/fki-ko/Makefile
index a97867d..f47a81b 100644
--- a/fki-ko/Makefile
+++ b/fki-ko/Makefile
@@ -1,2 +1,2 @@
obj-m += fki.o
-fki-y := fki_mod.o
+fki-y := fki_mod.o fki_hostcall.o
diff --git a/fki-ko/fki.h b/fki-ko/fki.h
index f59e497..aac3732 100644
--- a/fki-ko/fki.h
+++ b/fki-ko/fki.h
@@ -119,6 +119,11 @@ long fki_file_rw(void *file, int write, void *buf, unsigned long len, fki_u64 of
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/fki-ko/fki_hostcall.c b/fki-ko/fki_hostcall.c
new file mode 100644
index 0000000..48f3595
--- /dev/null
+++ b/fki-ko/fki_hostcall.c
@@ -0,0 +1,233 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Host calls: a message channel from the foreign kernel to a Linux user process (a host service such as the DRM bridge,
+ * gpu/xnu-drm/xnudrmd). The foreign kernel calls fki_hostcall() with a request; the service reads it from
+ * /dev/xnu-hostcall, does the work with ordinary system calls and writes the reply back. fki only moves bytes: the
+ * message format belongs to the two ends.
+ *
+ * One call at a time (the foreign kernel's single CPU is blocked in the call). The service also asks fki to translate
+ * its own mappings into physical addresses (XNU_HOSTCALL_XLATE), so the foreign kernel can map the same pages.
+ */
+#include "fki.h"
+#include "fki_internal.h"
+#include <linux/fs.h>
+#include <linux/miscdevice.h>
+#include <linux/mm.h>
+#include <linux/module.h>
+#include <linux/mutex.h>
+#include <linux/sched.h>
+#include <linux/slab.h>
+#include <linux/uaccess.h>
+#include <linux/vmalloc.h>
+#include <linux/wait.h>
+
+#define HC_MAX (8UL << 20) /* largest request or reply */
+#define HC_TIMEOUT (120 * HZ) /* a service that does not answer: the call fails */
+
+struct xnu_hostcall_xlate {
+ __u64 va, len; /* a range of the caller's address space, 4 KiB aligned */
+ __u64 out; /* user pointer: one __u64 physical address per 4 KiB page */
+ __u64 max; /* entries at out */
+};
+#define XNU_HOSTCALL_XLATE _IOWR('X', 1, struct xnu_hostcall_xlate)
+
+static DECLARE_WAIT_QUEUE_HEAD(hc_req_wait);
+static DECLARE_WAIT_QUEUE_HEAD(hc_done_wait);
+static DEFINE_SPINLOCK(hc_lock);
+static void *hc_buf; /* request, then reply */
+static unsigned long hc_len;
+static u64 hc_seq; /* the call in flight (0: none) */
+static int hc_state; /* 0 idle, 1 request waiting, 2 read by the service, 3 replied */
+static long hc_result;
+
+struct hc_call { const void *req; unsigned long len; void *reply; unsigned long max; long result; };
+
+static void hc_call_body(void *p)
+{
+ struct hc_call *c = p;
+ static u64 seq;
+ long r;
+
+ local_irq_enable();
+ preempt_enable();
+ if (!hc_buf)
+ hc_buf = kvmalloc(HC_MAX, GFP_KERNEL);
+ if (!hc_buf || c->len > HC_MAX) {
+ r = hc_buf ? -EMSGSIZE : -ENOMEM;
+ goto out;
+ }
+ preempt_disable(); local_irq_disable();
+ memcpy(hc_buf, c->req, c->len); /* the foreign kernel's memory: read with interrupts off */
+ local_irq_enable(); preempt_enable();
+ spin_lock(&hc_lock);
+ hc_len = c->len;
+ hc_seq = ++seq;
+ hc_state = 1;
+ spin_unlock(&hc_lock);
+ wake_up_interruptible(&hc_req_wait);
+ if (!wait_event_timeout(hc_done_wait, READ_ONCE(hc_state) == 3, HC_TIMEOUT)) {
+ spin_lock(&hc_lock);
+ hc_state = 0; hc_seq = 0;
+ spin_unlock(&hc_lock);
+ r = -ETIMEDOUT;
+ goto out;
+ }
+ r = hc_result;
+ if (r >= 0) {
+ unsigned long n = min_t(unsigned long, hc_len, c->max);
+ preempt_disable(); local_irq_disable();
+ memcpy(c->reply, hc_buf, n);
+ local_irq_enable(); preempt_enable();
+ r = hc_len > c->max ? -EMSGSIZE : (long)n;
+ }
+ spin_lock(&hc_lock);
+ hc_state = 0; hc_seq = 0;
+ spin_unlock(&hc_lock);
+out:
+ preempt_disable();
+ local_irq_disable();
+ c->result = r;
+}
+
+/*
+ * From inside fki_enter(): send len bytes at req to the service and wait for its reply (at most max bytes into reply).
+ * Returns the reply's length, -EMSGSIZE when it does not fit, -ETIMEDOUT when no service answered in time.
+ */
+long fki_hostcall(const void *req, unsigned long len, void *reply, unsigned long max)
+{
+ struct hc_call c = { req, len, reply, max, -EIO };
+
+ fki_linux_runs_ext(hc_call_body, &c);
+ return c.result;
+}
+EXPORT_SYMBOL(fki_hostcall);
+
+/* The service: read() the next request, prefixed with its 8-byte sequence number. */
+static ssize_t hc_read(struct file *f, char __user *buf, size_t n, loff_t *off)
+{
+ u64 seq;
+ int err;
+
+ err = wait_event_interruptible(hc_req_wait, READ_ONCE(hc_state) == 1);
+ if (err)
+ return err;
+ spin_lock(&hc_lock);
+ if (hc_state != 1) {
+ spin_unlock(&hc_lock);
+ return -EAGAIN;
+ }
+ hc_state = 2;
+ seq = hc_seq;
+ spin_unlock(&hc_lock);
+ if (n < 8 + hc_len)
+ return -EMSGSIZE;
+ if (copy_to_user(buf, &seq, 8) || copy_to_user(buf + 8, hc_buf, hc_len))
+ return -EFAULT;
+ return 8 + hc_len;
+}
+
+/* The service: write() the reply, prefixed with the request's sequence number. */
+static ssize_t hc_write(struct file *f, const char __user *buf, size_t n, loff_t *off)
+{
+ u64 seq;
+
+ if (n < 8 || n - 8 > HC_MAX)
+ return -EINVAL;
+ if (copy_from_user(&seq, buf, 8))
+ return -EFAULT;
+ spin_lock(&hc_lock);
+ if (hc_state != 2 || seq != hc_seq) {
+ spin_unlock(&hc_lock);
+ return -ESTALE; /* the call timed out meanwhile */
+ }
+ spin_unlock(&hc_lock);
+ if (copy_from_user(hc_buf, buf + 8, n - 8))
+ return -EFAULT;
+ hc_len = n - 8;
+ hc_result = 0;
+ WRITE_ONCE(hc_state, 3);
+ wake_up(&hc_done_wait);
+ return n;
+}
+
+static long hc_xlate_one(struct mm_struct *mm, unsigned long va, u64 *pa)
+{
+ struct vm_area_struct *vma = vma_lookup(mm, va);
+ struct page *pg;
+
+ if (!vma)
+ return -EFAULT;
+ if (vma->vm_flags & (VM_IO | VM_PFNMAP)) {
+ struct follow_pfnmap_args args = { .vma = vma, .address = va };
+ int err = follow_pfnmap_start(&args);
+ if (err)
+ return err;
+ *pa = (u64)args.pfn << PAGE_SHIFT;
+ follow_pfnmap_end(&args);
+ return 0;
+ }
+ if (get_user_pages_remote(mm, va, 1, FOLL_WRITE, &pg, NULL) != 1)
+ return -EFAULT;
+ *pa = page_to_phys(pg);
+ put_page(pg); /* the mapping's owner (a GEM object) keeps the page */
+ return 0;
+}
+
+static long hc_xlate(struct xnu_hostcall_xlate __user *ua)
+{
+ struct xnu_hostcall_xlate a;
+ struct mm_struct *mm = current->mm;
+ unsigned long i, n;
+ long err = 0;
+
+ if (copy_from_user(&a, ua, sizeof(a)))
+ return -EFAULT;
+ if ((a.va | a.len) & (PAGE_SIZE - 1))
+ return -EINVAL;
+ n = a.len >> PAGE_SHIFT;
+ if (n > a.max)
+ return -E2BIG;
+ mmap_read_lock(mm);
+ for (i = 0; i < n && !err; i++) {
+ u64 pa;
+ err = hc_xlate_one(mm, a.va + (i << PAGE_SHIFT), &pa);
+ if (!err && put_user(pa, (u64 __user *)a.out + i))
+ err = -EFAULT;
+ }
+ mmap_read_unlock(mm);
+ return err;
+}
+
+static long hc_ioctl(struct file *f, unsigned int cmd, unsigned long arg)
+{
+ if (cmd == XNU_HOSTCALL_XLATE)
+ return hc_xlate((struct xnu_hostcall_xlate __user *)arg);
+ return -ENOTTY;
+}
+
+static const struct file_operations hc_fops = {
+ .owner = THIS_MODULE,
+ .read = hc_read,
+ .write = hc_write,
+ .unlocked_ioctl = hc_ioctl,
+ .llseek = noop_llseek,
+};
+
+static struct miscdevice hc_dev = {
+ .minor = MISC_DYNAMIC_MINOR,
+ .name = "xnu-hostcall",
+ .fops = &hc_fops,
+ .mode = 0600,
+};
+
+int fki_hostcall_init(void)
+{
+ return misc_register(&hc_dev);
+}
+
+void fki_hostcall_exit(void)
+{
+ misc_deregister(&hc_dev);
+ kvfree(hc_buf);
+ hc_buf = NULL;
+}
diff --git a/fki-ko/fki_internal.h b/fki-ko/fki_internal.h
new file mode 100644
index 0000000..4a4b196
--- /dev/null
+++ b/fki-ko/fki_internal.h
@@ -0,0 +1,9 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/* 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);
+int fki_hostcall_init(void);
+void fki_hostcall_exit(void);
+#endif
diff --git a/fki-ko/fki_mod.c b/fki-ko/fki_mod.c
index 4c79f75..ef4a7ec 100644
--- a/fki-ko/fki_mod.c
+++ b/fki-ko/fki_mod.c
@@ -7,6 +7,7 @@
* re-exported.
*/
#include "fki.h"
+#include "fki_internal.h"
#include <linux/firmware.h>
#include <linux/gfp.h>
#include <linux/irqflags.h>
@@ -492,6 +493,11 @@ static void fki_linux_runs(void (*fn)(void *), void *arg)
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;
@@ -689,6 +695,9 @@ static int __init fki_init(void)
int 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 */
@@ -709,6 +718,7 @@ static int __init fki_init(void)
static void __exit fki_exit(void)
{
+ fki_hostcall_exit();
if (fki_netdev) {
unregister_netdev(fki_netdev);
free_netdev(fki_netdev);
diff --git a/gpu/venus/build-darwin.sh b/gpu/venus/build-darwin.sh
new file mode 100755
index 0000000..b3cc0c4
--- /dev/null
+++ b/gpu/venus/build-darwin.sh
@@ -0,0 +1,44 @@
+#!/bin/bash
+# On a Mac: build Mesa's Venus Vulkan driver for the hosted macOS, its renderer talking to the Linux host's GPU over the
+# DRM bridge (gpu/xnu-drm: libxnudrm in the driver, kexts/XnuDrm in the hosted kernel, xnudrmd on Linux). Patches as for
+# the Linux guest (patches/), plus libxnudrm copied into the tree. Also builds test/compute.c against it.
+# Output: $OUT/lib/libvulkan_virtio.dylib, $OUT/share/vulkan/icd.d/virtio_icd.*.json, $OUT/bin/venus-compute.
+set -euo pipefail
+HERE="$(cd "$(dirname "$0")" && pwd)"
+MESA=26.3.1
+ARCH=${ARCH:-arm64} # arm64e for system processes (Metal plugin); arm64 for a test program
+W=${W:-$HOME/w/venus-darwin}; OUT=${OUT:-$W/out-$ARCH}; mkdir -p "$W"; cd "$W"
+export PATH=$W/venv/bin:/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin
+# Mesa wants Python >= 3.10 (macOS ships 3.9): uv's own when there is uv, else Homebrew's
+if ! { [ -x venv/bin/meson ] && venv/bin/python3 -c 'import sys; sys.exit(sys.version_info < (3, 10))'; }; then
+ rm -rf venv
+ if command -v uv >/dev/null; then uv venv -q -p 3.13 venv && VIRTUAL_ENV=$W/venv uv pip install -q meson ninja mako pyyaml packaging
+ else /opt/homebrew/bin/python3 -m venv venv && venv/bin/pip -q install meson ninja mako pyyaml packaging; fi
+fi
+[ -f mesa-$MESA.tar.xz ] || curl -sSLo mesa-$MESA.tar.xz https://archive.mesa3d.org/mesa-$MESA.tar.xz
+rm -rf mesa && mkdir mesa && tar -C mesa --strip-components=1 -xf mesa-$MESA.tar.xz
+for p in "$HERE"/patches/*.patch; do patch -d mesa -p1 --no-backup-if-mismatch -s < "$p"; done
+mkdir -p mesa/src/virtio/vulkan/xnudrm
+cp "$HERE"/../xnu-drm/darwin/* "$HERE"/../xnu-drm/xnudrm_proto.h mesa/src/virtio/vulkan/xnudrm/
+cat > cross-$ARCH.txt <<X
+[binaries]
+c = ['/usr/bin/clang', '-arch', '$ARCH']
+cpp = ['/usr/bin/clang++', '-arch', '$ARCH']
+objc = ['/usr/bin/clang', '-arch', '$ARCH']
+ar = '/usr/bin/ar'
+strip = '/usr/bin/strip'
+[host_machine]
+system = 'darwin'
+cpu_family = 'aarch64'
+cpu = '$ARCH'
+endian = 'little'
+X
+meson setup mesa/build-$ARCH mesa --cross-file cross-$ARCH.txt --prefix="$OUT" --buildtype=release \
+ -Dvulkan-drivers=virtio -Dgallium-drivers= -Dplatforms= -Dglx=disabled -Degl=disabled -Dgbm=disabled -Dllvm=disabled \
+ -Dopengl=false -Dgles1=disabled -Dgles2=disabled -Dvideo-codecs= -Dzstd=disabled -Dxmlconfig=disabled \
+ -Dbuild-tests=false >/dev/null || { tail -40 mesa/build-$ARCH/meson-logs/meson-log.txt; exit 1; }
+ninja -C mesa/build-$ARCH install > ninja-$ARCH.log 2>&1 || { grep -E "error|FAILED|Undefined" ninja-$ARCH.log | head -30; exit 1; }
+ls -la "$OUT"/lib/libvulkan_virtio.dylib
+mkdir -p "$OUT"/bin
+# the test talks to the driver directly (no loader in the hosted system): vk_icdGetInstanceProcAddr
+/usr/bin/clang -arch $ARCH -O2 -I mesa/include "$HERE"/test/compute.c -o "$OUT"/bin/venus-compute
diff --git a/gpu/venus/build-linux.sh b/gpu/venus/build-linux.sh
new file mode 100755
index 0000000..de9cc47
--- /dev/null
+++ b/gpu/venus/build-linux.sh
@@ -0,0 +1,26 @@
+#!/bin/bash
+# In the Linux guest: build Mesa's Venus Vulkan driver with our patches (patches/), then check it on the GPU behind
+# virtio-gpu: list the device and run test/compute.c (a compute dispatch over 16 MB of host-visible memory, read back and
+# compared). Output: $OUT/lib/libvulkan_virtio.so and $OUT/share/vulkan/icd.d/virtio_icd.*.json.
+set -euo pipefail
+HERE="$(cd "$(dirname "$0")" && pwd)"
+MESA=26.3.1
+W=${W:-$HOME/w/venus}; OUT=${OUT:-$W/out}; mkdir -p "$W"; cd "$W"
+sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq ninja-build libdrm-dev glslang-tools bison flex pkg-config \
+ libexpat1-dev zlib1g-dev libudev-dev libzstd-dev libvulkan-dev vulkan-tools python3-venv >/dev/null
+[ -x venv/bin/meson ] || { python3 -m venv venv && venv/bin/pip -q install meson mako pyyaml packaging; }
+export PATH=$W/venv/bin:$PATH
+[ -f mesa-$MESA.tar.xz ] || curl -sSLo mesa-$MESA.tar.xz https://archive.mesa3d.org/mesa-$MESA.tar.xz
+rm -rf mesa && mkdir mesa && tar -C mesa --strip-components=1 -xf mesa-$MESA.tar.xz
+for p in "$HERE"/patches/*.patch; do patch -d mesa -p1 --no-backup-if-mismatch -s < "$p"; done
+meson setup mesa/build mesa --prefix="$OUT" --buildtype=release -Dvulkan-drivers=virtio -Dgallium-drivers= \
+ -Dplatforms= -Dglx=disabled -Degl=disabled -Dgbm=disabled -Dllvm=disabled -Dopengl=false -Dgles1=disabled \
+ -Dgles2=disabled -Dvideo-codecs= >/dev/null
+ninja -C mesa/build install > ninja.log 2>&1 || { grep -E "error|FAILED" ninja.log | head -30; exit 1; }
+ICD=$(ls "$OUT"/share/vulkan/icd.d/virtio_icd.*.json)
+glslangValidator -V "$HERE"/test/compute.comp -o "$W"/compute.spv >/dev/null
+cc -O2 "$HERE"/test/compute.c -o "$W"/compute -ldl
+# /dev/dri/renderD128 is root:render; run as root unless the user is in render
+SUDO=; [ -r /dev/dri/renderD128 ] && [ -w /dev/dri/renderD128 ] || SUDO=sudo
+$SUDO env VK_ICD_FILENAMES="$ICD" vulkaninfo --summary 2>/dev/null | grep -E "deviceName|driverInfo"
+$SUDO env VK_ICD_FILENAMES="$ICD" "$W"/compute "$W"/compute.spv
diff --git a/gpu/venus/patches/0001-venus-16k-host-page-alignment.patch b/gpu/venus/patches/0001-venus-16k-host-page-alignment.patch
new file mode 100644
index 0000000..bce65db
--- /dev/null
+++ b/gpu/venus/patches/0001-venus-16k-host-page-alignment.patch
@@ -0,0 +1,54 @@
+Upstream: Mesa 26.3.1 (https://archive.mesa3d.org/mesa-26.3.1.tar.xz)
+Upstream-License: MIT
+Patch-License: MIT (provided under the same license as upstream)
+Origin: Sergio Lopez, gitlab.freedesktop.org/slp/mesa commit 761ef1ec ("virtio/vulkan: force 16k alignment for allocations")
+Subject: venus: align ring, shmem, blob and device memory sizes to 16 KiB
+
+On a macOS host (krunkit/libkrun), the VMM maps virtio-gpu blobs into the guest with hv_vm_map, which needs host-page
+(16 KiB) aligned sizes; the guest kernel rounds them only to its own 4 KiB pages. Linux 7.2 exposes the device's blob
+alignment (VIRTIO_GPU_F_BLOB_ALIGNMENT); until Mesa reads it, align everything to 16 KiB.
+
+--- a/src/virtio/vulkan/vn_device_memory.c
++++ b/src/virtio/vulkan/vn_device_memory.c
+@@ -31,6 +31,10 @@ vn_device_memory_alloc_simple(struct vn_device *dev,
+ {
+ VkDevice dev_handle = vn_device_to_handle(dev);
+ VkDeviceMemory mem_handle = vn_device_memory_to_handle(mem);
++
++ ((VkMemoryAllocateInfo *)alloc_info)->allocationSize =
++ align64(alloc_info->allocationSize, 16384);
++
+ if (VN_PERF(NO_ASYNC_MEM_ALLOC)) {
+ return vn_call_vkAllocateMemory(dev->primary_ring, dev_handle,
+ alloc_info, NULL, &mem_handle);
+--- a/src/virtio/vulkan/vn_renderer_virtgpu.c
++++ b/src/virtio/vulkan/vn_renderer_virtgpu.c
+@@ -1241,6 +1241,8 @@ virtgpu_bo_create_from_device_memory(
+ const uint32_t blob_flags =
+ virtgpu_bo_blob_flags(gpu, flags, external_handles);
+
++ size = align64(size, 16384);
++
+ uint32_t res_id;
+ uint32_t gem_handle = virtgpu_ioctl_resource_create_blob(
+ gpu, gpu->bo_blob_mem, blob_flags, size, mem_id, &res_id);
+@@ -1291,6 +1293,8 @@ virtgpu_shmem_create(struct vn_renderer *renderer, size_t size)
+ {
+ struct virtgpu *gpu = (struct virtgpu *)renderer;
+
++ size = align64(size, 16384);
++
+ struct vn_renderer_shmem *cached_shmem =
+ vn_renderer_shmem_cache_get(&gpu->shmem_cache, size);
+ if (cached_shmem) {
+--- a/src/virtio/vulkan/vn_ring.c
++++ b/src/virtio/vulkan/vn_ring.c
+@@ -264,7 +264,7 @@ vn_ring_get_layout(size_t buf_size,
+ layout->extra_offset = layout->buffer_offset + layout->buffer_size;
+ layout->extra_size = extra_size;
+
+- layout->shmem_size = layout->extra_offset + layout->extra_size;
++ layout->shmem_size = align64(layout->extra_offset + layout->extra_size, 16384);
+ }
+
+ struct vn_ring *
diff --git a/gpu/venus/patches/0002-venus-virtgpu-over-xnudrm-on-macos.patch b/gpu/venus/patches/0002-venus-virtgpu-over-xnudrm-on-macos.patch
new file mode 100644
index 0000000..7a397f3
--- /dev/null
+++ b/gpu/venus/patches/0002-venus-virtgpu-over-xnudrm-on-macos.patch
@@ -0,0 +1,78 @@
+Upstream: Mesa 26.3.1 (https://archive.mesa3d.org/mesa-26.3.1.tar.xz)
+Upstream-License: MIT
+Patch-License: MIT (provided under the same license as upstream)
+Subject: venus: the virtgpu renderer on macOS over the xnulinux DRM bridge
+
+In the hosted macOS of xnulinux, the GPU is the Linux host's virtio-gpu render node, reached through kexts/XnuDrm.
+gpu/xnu-drm/darwin (libxnudrm: xf86drm.h, the render node's open/mmap/poll) is copied to src/virtio/vulkan/xnudrm by the
+build (gpu/venus/build-darwin.sh) and compiled into the driver; syncobjs are simulated (vn_renderer_sim_syncobj).
+The vtest renderer (a socket to a local virglrenderer) is left out on macOS.
+
+--- a/src/virtio/vulkan/meson.build
++++ b/src/virtio/vulkan/meson.build
+@@ -124,7 +124,7 @@
+
+ vn_libs = []
+
+-if not with_platform_windows
++if not with_platform_windows and host_machine.system() != 'darwin'
+ libvn_files += files('vn_renderer_vtest.c')
+ endif
+
+@@ -134,6 +134,18 @@
+ 'vn_renderer_virtgpu.c',
+ )
+ vn_deps += dep_libdrm
++elif host_machine.system() == 'darwin'
++ # the hosted macOS of xnulinux: the Linux host's virtio-gpu render node through kexts/XnuDrm (libxnudrm, xnudrm/)
++ libvn_files += files(
++ 'vn_renderer_sim_syncobj.c',
++ 'vn_renderer_virtgpu.c',
++ 'xnudrm/xnudrm.c',
++ )
++ vn_incs += include_directories('xnudrm')
++ vn_c_args += ['-DVN_XNUDRM', '-include', meson.current_source_dir() / 'xnudrm' / 'xnudrm_compat.h']
++ # the runtime's entrypoint tables name weak symbols venus does not define (ELF leaves them NULL): the same on Mach-O;
++ # dead-stripping drops the runtime code venus never calls (as --gc-sections does on ELF), with its references
++ vn_link_args += ['-framework', 'IOKit', '-framework', 'CoreFoundation', '-Wl,-undefined,dynamic_lookup', '-Wl,-dead_strip']
+ endif
+
+ if with_platform_wayland or with_platform_x11 or \
+--- a/src/virtio/vulkan/vn_renderer.h
++++ b/src/virtio/vulkan/vn_renderer.h
+@@ -213,7 +213,7 @@
+ struct vn_renderer_sync_ops sync_ops;
+ };
+
+-#ifdef HAVE_LIBDRM
++#if defined(HAVE_LIBDRM) || defined(VN_XNUDRM)
+ VkResult
+ vn_renderer_create_virtgpu(struct vn_instance *instance,
+ const VkAllocationCallbacks *alloc,
+@@ -242,6 +242,8 @@
+ result = vn_renderer_create_vtest(instance, alloc, renderer);
+ }
+ return result;
++#elif defined(VN_XNUDRM)
++ return vn_renderer_create_virtgpu(instance, alloc, renderer);
+ #else
+ return vn_renderer_create_vtest(instance, alloc, renderer);
+ #endif
+--- a/src/virtio/vulkan/vn_renderer_virtgpu.c
++++ b/src/virtio/vulkan/vn_renderer_virtgpu.c
+@@ -980,6 +980,7 @@
+ * simulated syncobj. Here we rely on util_sync_provider::timeline_signal
+ * being conditioned upon DRM_CAP_SYNCOBJ_TIMELINE.
+ */
++#ifndef VN_XNUDRM /* no DRM syncobjs over the bridge */
+ if (!VN_DEBUG(NO_DRM_SYNCOBJ)) {
+ gpu->sync = util_sync_provider_drm(gpu->fd);
+ if (!gpu->sync->timeline_signal) {
+@@ -987,6 +988,7 @@
+ gpu->sync = NULL;
+ }
+ }
++#endif
+
+ if (!gpu->sync)
+ gpu->sync = vn_renderer_sim_syncobj_get_sync();
diff --git a/gpu/venus/test/compute.c b/gpu/venus/test/compute.c
new file mode 100644
index 0000000..91102de
--- /dev/null
+++ b/gpu/venus/test/compute.c
@@ -0,0 +1,132 @@
+#define VK_NO_PROTOTYPES
+#include <vulkan/vulkan.h>
+#include <dlfcn.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+static PFN_vkCreateInstance vkCreateInstance;
+static PFN_vkEnumeratePhysicalDevices vkEnumeratePhysicalDevices;
+static PFN_vkGetPhysicalDeviceProperties vkGetPhysicalDeviceProperties;
+static PFN_vkCreateDevice vkCreateDevice;
+static PFN_vkGetDeviceQueue vkGetDeviceQueue;
+static PFN_vkCreateBuffer vkCreateBuffer;
+static PFN_vkGetBufferMemoryRequirements vkGetBufferMemoryRequirements;
+static PFN_vkGetPhysicalDeviceMemoryProperties vkGetPhysicalDeviceMemoryProperties;
+static PFN_vkAllocateMemory vkAllocateMemory;
+static PFN_vkBindBufferMemory vkBindBufferMemory;
+static PFN_vkMapMemory vkMapMemory;
+static PFN_vkCreateShaderModule vkCreateShaderModule;
+static PFN_vkCreateDescriptorSetLayout vkCreateDescriptorSetLayout;
+static PFN_vkCreatePipelineLayout vkCreatePipelineLayout;
+static PFN_vkCreateComputePipelines vkCreateComputePipelines;
+static PFN_vkCreateDescriptorPool vkCreateDescriptorPool;
+static PFN_vkAllocateDescriptorSets vkAllocateDescriptorSets;
+static PFN_vkUpdateDescriptorSets vkUpdateDescriptorSets;
+static PFN_vkCreateCommandPool vkCreateCommandPool;
+static PFN_vkAllocateCommandBuffers vkAllocateCommandBuffers;
+static PFN_vkBeginCommandBuffer vkBeginCommandBuffer;
+static PFN_vkCmdBindPipeline vkCmdBindPipeline;
+static PFN_vkCmdBindDescriptorSets vkCmdBindDescriptorSets;
+static PFN_vkCmdDispatch vkCmdDispatch;
+static PFN_vkCmdPipelineBarrier vkCmdPipelineBarrier;
+static PFN_vkEndCommandBuffer vkEndCommandBuffer;
+static PFN_vkCreateFence vkCreateFence;
+static PFN_vkQueueSubmit vkQueueSubmit;
+static PFN_vkWaitForFences vkWaitForFences;
+
+/* The Vulkan entry points: from the loader (Linux) or straight from a driver (VT_ICD=path: the hosted macOS has no loader) */
+static PFN_vkGetInstanceProcAddr gipa;
+static void load_global(void) {
+ const char *icd = getenv("VT_ICD");
+ void *h = dlopen(icd ? icd : "libvulkan.so.1", RTLD_NOW | RTLD_LOCAL);
+ if (!h) { printf("FAIL dlopen %s: %s\n", icd ? icd : "libvulkan.so.1", dlerror()); exit(1); }
+ gipa = (PFN_vkGetInstanceProcAddr)dlsym(h, icd ? "vk_icdGetInstanceProcAddr" : "vkGetInstanceProcAddr");
+ if (!gipa) { printf("FAIL no GetInstanceProcAddr\n"); exit(1); }
+ vkCreateInstance = (PFN_vkCreateInstance)gipa(NULL, "vkCreateInstance");
+}
+static void load_instance(VkInstance inst) {
+#define L(f) f = (PFN_##f)gipa(inst, #f); if (!f) { printf("FAIL no %s\n", #f); exit(1); }
+ L(vkEnumeratePhysicalDevices)
+ L(vkGetPhysicalDeviceProperties)
+ L(vkCreateDevice)
+ L(vkGetDeviceQueue)
+ L(vkCreateBuffer)
+ L(vkGetBufferMemoryRequirements)
+ L(vkGetPhysicalDeviceMemoryProperties)
+ L(vkAllocateMemory)
+ L(vkBindBufferMemory)
+ L(vkMapMemory)
+ L(vkCreateShaderModule)
+ L(vkCreateDescriptorSetLayout)
+ L(vkCreatePipelineLayout)
+ L(vkCreateComputePipelines)
+ L(vkCreateDescriptorPool)
+ L(vkAllocateDescriptorSets)
+ L(vkUpdateDescriptorSets)
+ L(vkCreateCommandPool)
+ L(vkAllocateCommandBuffers)
+ L(vkBeginCommandBuffer)
+ L(vkCmdBindPipeline)
+ L(vkCmdBindDescriptorSets)
+ L(vkCmdDispatch)
+ L(vkCmdPipelineBarrier)
+ L(vkEndCommandBuffer)
+ L(vkCreateFence)
+ L(vkQueueSubmit)
+ L(vkWaitForFences)
+#undef L
+}
+#define CK(x) do{VkResult r=(x); if(r){printf("FAIL %s = %d\n",#x,r); exit(1);}}while(0)
+int main(int argc,char**argv){
+ const uint32_t N=1u<<22; /* 4M uints = 16 MB */
+ VkInstance inst; VkApplicationInfo ai={VK_STRUCTURE_TYPE_APPLICATION_INFO,0,"vt",1,0,0,VK_API_VERSION_1_1};
+ VkInstanceCreateInfo ic={VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,0,0,&ai};
+ load_global();
+ CK(vkCreateInstance(&ic,0,&inst));
+ load_instance(inst);
+ uint32_t n=1; VkPhysicalDevice pd; CK(vkEnumeratePhysicalDevices(inst,&n,&pd));
+ VkPhysicalDeviceProperties pp; vkGetPhysicalDeviceProperties(pd,&pp); printf("device: %s\n",pp.deviceName);
+ float pr=1; VkDeviceQueueCreateInfo qc={VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO,0,0,0,1,&pr};
+ VkDeviceCreateInfo dc={VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO,0,0,1,&qc};
+ VkDevice dev; CK(vkCreateDevice(pd,&dc,0,&dev)); VkQueue q; vkGetDeviceQueue(dev,0,0,&q);
+ VkBufferCreateInfo bc={VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,0,0,N*4,VK_BUFFER_USAGE_STORAGE_BUFFER_BIT};
+ VkBuffer buf; CK(vkCreateBuffer(dev,&bc,0,&buf));
+ VkMemoryRequirements mr; vkGetBufferMemoryRequirements(dev,buf,&mr);
+ VkPhysicalDeviceMemoryProperties mp; vkGetPhysicalDeviceMemoryProperties(pd,&mp);
+ uint32_t mt=~0u; for(uint32_t i=0;i<mp.memoryTypeCount;i++) if((mr.memoryTypeBits>>i&1)&&(mp.memoryTypes[i].propertyFlags&(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT|VK_MEMORY_PROPERTY_HOST_COHERENT_BIT))==(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT|VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)){mt=i;break;}
+ printf("memtype %u flags 0x%x\n",mt,mp.memoryTypes[mt].propertyFlags);
+ VkMemoryAllocateInfo ma={VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,0,mr.size,mt}; VkDeviceMemory mem; CK(vkAllocateMemory(dev,&ma,0,&mem));
+ CK(vkBindBufferMemory(dev,buf,mem,0)); uint32_t*p; CK(vkMapMemory(dev,mem,0,N*4,0,(void**)&p));
+ for(uint32_t i=0;i<N;i++) p[i]=i;
+ FILE*f=fopen(argv[1],"rb"); fseek(f,0,2); long sz=ftell(f); rewind(f); uint32_t*code=malloc(sz); if(fread(code,1,sz,f)!=(size_t)sz){printf("short read\n");return 1;} fclose(f);
+ VkShaderModuleCreateInfo sc={VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO,0,0,sz,code}; VkShaderModule sm; CK(vkCreateShaderModule(dev,&sc,0,&sm));
+ VkDescriptorSetLayoutBinding lb={0,VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,1,VK_SHADER_STAGE_COMPUTE_BIT};
+ VkDescriptorSetLayoutCreateInfo lc={VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO,0,0,1,&lb}; VkDescriptorSetLayout dl; CK(vkCreateDescriptorSetLayout(dev,&lc,0,&dl));
+ VkPipelineLayoutCreateInfo plc={VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO,0,0,1,&dl}; VkPipelineLayout pl; CK(vkCreatePipelineLayout(dev,&plc,0,&pl));
+ VkComputePipelineCreateInfo cpc={VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO,0,0,{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,0,0,VK_SHADER_STAGE_COMPUTE_BIT,sm,"main"},pl};
+ VkPipeline pipe; CK(vkCreateComputePipelines(dev,0,1,&cpc,0,&pipe));
+ VkDescriptorPoolSize ps={VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,1}; VkDescriptorPoolCreateInfo dpc={VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO,0,0,1,1,&ps}; VkDescriptorPool dp; CK(vkCreateDescriptorPool(dev,&dpc,0,&dp));
+ VkDescriptorSetAllocateInfo dsa={VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO,0,dp,1,&dl}; VkDescriptorSet ds; CK(vkAllocateDescriptorSets(dev,&dsa,&ds));
+ VkDescriptorBufferInfo dbi={buf,0,VK_WHOLE_SIZE}; VkWriteDescriptorSet w={VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,0,ds,0,0,1,VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,0,&dbi}; vkUpdateDescriptorSets(dev,1,&w,0,0);
+ VkCommandPoolCreateInfo cpi={VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,0,0,0}; VkCommandPool cp; CK(vkCreateCommandPool(dev,&cpi,0,&cp));
+ VkCommandBufferAllocateInfo cba={VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,0,cp,0,1}; VkCommandBuffer cb; CK(vkAllocateCommandBuffers(dev,&cba,&cb));
+ VkCommandBufferBeginInfo bi={VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; CK(vkBeginCommandBuffer(cb,&bi));
+ vkCmdBindPipeline(cb,VK_PIPELINE_BIND_POINT_COMPUTE,pipe); vkCmdBindDescriptorSets(cb,VK_PIPELINE_BIND_POINT_COMPUTE,pl,0,1,&ds,0,0);
+ vkCmdDispatch(cb,N/64,1,1);
+ VkMemoryBarrier mb={VK_STRUCTURE_TYPE_MEMORY_BARRIER,0,VK_ACCESS_SHADER_WRITE_BIT,VK_ACCESS_HOST_READ_BIT};
+ vkCmdPipelineBarrier(cb,VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,VK_PIPELINE_STAGE_HOST_BIT,0,1,&mb,0,0,0,0);
+ CK(vkEndCommandBuffer(cb));
+ VkFenceCreateInfo fc={VK_STRUCTURE_TYPE_FENCE_CREATE_INFO}; VkFence fe; CK(vkCreateFence(dev,&fc,0,&fe));
+ struct timespec t0,t1; clock_gettime(CLOCK_MONOTONIC,&t0);
+ VkSubmitInfo si={VK_STRUCTURE_TYPE_SUBMIT_INFO,0,0,0,0,1,&cb}; CK(vkQueueSubmit(q,1,&si,fe)); CK(vkWaitForFences(dev,1,&fe,1,~0ull));
+ clock_gettime(CLOCK_MONOTONIC,&t1);
+ uint32_t bad=0; for(uint32_t i=0;i<N;i++) if(p[i]!=i*2u+1u){ if(bad<3) printf("mismatch %u: %u\n",i,p[i]); bad++; }
+ printf("compute %u elems: %s (%u bad), %.2f ms\n",N,bad?"FAIL":"OK",bad,(t1.tv_sec-t0.tv_sec)*1e3+(t1.tv_nsec-t0.tv_nsec)/1e6);
+ if (bad) { /* tell a wait that returned early from results that never arrive */
+ struct timespec d = { 1, 0 }; nanosleep(&d, NULL);
+ uint32_t late = 0; for(uint32_t i=0;i<N;i++) if(p[i]!=i*2u+1u) late++;
+ printf("after 1 s more: %u bad\n", late);
+ }
+ return bad?1:0;
+}
diff --git a/gpu/venus/test/compute.comp b/gpu/venus/test/compute.comp
new file mode 100644
index 0000000..1d6d744
--- /dev/null
+++ b/gpu/venus/test/compute.comp
@@ -0,0 +1,4 @@
+#version 450
+layout(local_size_x=64) in;
+layout(std430, binding=0) buffer B { uint d[]; };
+void main(){ uint i=gl_GlobalInvocationID.x; d[i]=d[i]*2u+1u; }
diff --git a/gpu/xnu-drm/Makefile b/gpu/xnu-drm/Makefile
new file mode 100644
index 0000000..0784ca8
--- /dev/null
+++ b/gpu/xnu-drm/Makefile
@@ -0,0 +1,6 @@
+# The Linux end (xnudrmd); the macOS ends are kexts/XnuDrm and darwin/ (libxnudrm, built with Mesa).
+CFLAGS ?= -O2 -Wall -Wextra -Wno-unused-parameter
+xnudrmd: xnudrmd.c xnudrm_proto.h
+ $(CC) $(CFLAGS) -o $@ xnudrmd.c
+clean:
+ rm -f xnudrmd
diff --git a/gpu/xnu-drm/darwin/xf86drm.h b/gpu/xnu-drm/darwin/xf86drm.h
new file mode 100644
index 0000000..8a7cd57
--- /dev/null
+++ b/gpu/xnu-drm/darwin/xf86drm.h
@@ -0,0 +1,56 @@
+/* SPDX-License-Identifier: MIT */
+/*
+ * The part of libdrm's xf86drm.h that Mesa's Venus driver (vn_renderer_virtgpu.c) uses, for macOS: libxnudrm implements
+ * it over kexts/XnuDrm, which forwards to the Linux host's virtio-gpu render node (gpu/xnu-drm).
+ */
+#ifndef XNUDRM_XF86DRM_H
+#define XNUDRM_XF86DRM_H
+#include <stdint.h>
+#include <stddef.h>
+#include "drm-uapi/drm.h"
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define DRM_NODE_PRIMARY 0
+#define DRM_NODE_CONTROL 1
+#define DRM_NODE_RENDER 2
+#define DRM_NODE_MAX 3
+#define DRM_BUS_PCI 0
+#define DRM_BUS_USB 1
+#define DRM_BUS_PLATFORM 2
+#define DRM_BUS_HOST1X 3
+
+typedef struct _drmVersion {
+ int version_major, version_minor, version_patchlevel;
+ int name_len; char *name;
+ int date_len; char *date;
+ int desc_len; char *desc;
+} drmVersion, *drmVersionPtr;
+
+typedef struct _drmPciBusInfo { uint16_t domain; uint8_t bus, dev, func; } drmPciBusInfo, *drmPciBusInfoPtr;
+typedef struct _drmPciDeviceInfo {
+ uint16_t vendor_id, device_id, subvendor_id, subdevice_id;
+ uint8_t revision_id;
+} drmPciDeviceInfo, *drmPciDeviceInfoPtr;
+typedef struct _drmPlatformBusInfo { char fullname[512]; } drmPlatformBusInfo, *drmPlatformBusInfoPtr;
+typedef struct _drmPlatformDeviceInfo { char **compatible; } drmPlatformDeviceInfo, *drmPlatformDeviceInfoPtr;
+
+typedef struct _drmDevice {
+ char **nodes;
+ int available_nodes;
+ int bustype;
+ union { drmPciBusInfoPtr pci; drmPlatformBusInfoPtr platform; } businfo;
+ union { drmPciDeviceInfoPtr pci; drmPlatformDeviceInfoPtr platform; } deviceinfo;
+} drmDevice, *drmDevicePtr;
+
+int drmIoctl(int fd, unsigned long request, void *arg);
+int drmGetDevices2(uint32_t flags, drmDevicePtr devices[], int max_devices);
+void drmFreeDevices(drmDevicePtr devices[], int count);
+drmVersionPtr drmGetVersion(int fd);
+void drmFreeVersion(drmVersionPtr v);
+
+#ifdef __cplusplus
+}
+#endif
+#endif
diff --git a/gpu/xnu-drm/darwin/xnudrm.c b/gpu/xnu-drm/darwin/xnudrm.c
new file mode 100644
index 0000000..98640b6
--- /dev/null
+++ b/gpu/xnu-drm/darwin/xnudrm.c
@@ -0,0 +1,385 @@
+// SPDX-License-Identifier: MIT
+/*
+ * libxnudrm: Linux's virtio-gpu render node for Mesa's Venus driver inside the hosted macOS. The node is a user client of
+ * kexts/XnuDrm; each DRM ioctl becomes one message to xnudrmd on the Linux host (xnudrm_proto.h), with the ioctl struct's
+ * user pointers turned into offsets into the message. Buffer mappings are Linux's own pages, mapped into this process by
+ * the kext. Fences are pipes whose read end stands for the fence (so dup'ed descriptors stay the same fence); poll() on
+ * one asks xnudrmd, and once the fence signals the pipe is made readable for good.
+ */
+#ifdef XNUDRM_COMPAT_H /* force-included into the whole driver: this file means the system's own calls */
+#undef open
+#undef close
+#undef mmap
+#undef munmap
+#undef stat
+#undef poll
+#endif
+#include <errno.h>
+#include <fcntl.h>
+#include <poll.h>
+#include <pthread.h>
+#include <stdarg.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/mman.h>
+#include <sys/stat.h>
+#include <time.h>
+#include <unistd.h>
+#include <IOKit/IOKitLib.h>
+#include "drm-uapi/drm.h"
+#include "drm-uapi/virtgpu_drm.h"
+#include "xnudrm_proto.h"
+#include "xf86drm.h"
+
+#define NODE_RENDER "/dev/dri/renderD128"
+#define NODE_PRIMARY "/dev/dri/card0"
+
+static pthread_mutex_t lk = PTHREAD_MUTEX_INITIALIZER;
+static io_connect_t conn; /* one user client per process */
+static int node_fd = -1; /* the descriptor handed out for the render node (a /dev/null) */
+static int node_refs;
+static struct xmap { void *va; size_t len; uint64_t id; } *maps;
+static unsigned nmaps;
+static struct xfence { dev_t dev; ino_t ino; int wfd; uint64_t id; } *fences;
+static unsigned nfences;
+static uint8_t *buf; /* message, then reply */
+
+static int debug(void) { static int d = -1; if (d < 0) d = getenv("XNUDRM_DEBUG") != NULL; return d; }
+
+static int connect_kext(void)
+{
+ if (conn) return 0;
+ io_service_t s = IOServiceGetMatchingService(kIOMainPortDefault, IOServiceMatching("XnuDrm"));
+ if (!s) { if (debug()) fprintf(stderr, "xnudrm: no XnuDrm service\n"); return -ENODEV; }
+ kern_return_t kr = IOServiceOpen(s, mach_task_self(), 0, &conn);
+ IOObjectRelease(s);
+ if (kr != KERN_SUCCESS) { if (debug()) fprintf(stderr, "xnudrm: IOServiceOpen %#x\n", kr); conn = 0; return -EIO; }
+ if (!buf) buf = malloc(sizeof(struct xnudrm_hdr) + XNUDRM_MAX_MSG);
+ return buf ? 0 : -ENOMEM;
+}
+
+/* buf holds a header and plen bytes of payload; the reply replaces it. Returns the reply's status or -errno. */
+static int call(uint32_t plen)
+{
+ uint64_t in[4] = { (uintptr_t)buf, sizeof(struct xnudrm_hdr) + plen, (uintptr_t)buf, sizeof(struct xnudrm_hdr) + XNUDRM_MAX_MSG };
+ uint64_t out = 0;
+ uint32_t nout = 1;
+ kern_return_t kr = IOConnectCallScalarMethod(conn, 0, in, 4, &out, &nout);
+ if (kr != KERN_SUCCESS) { if (debug()) fprintf(stderr, "xnudrm: call %#x\n", kr); return -EIO; }
+ return ((struct xnudrm_hdr *)buf)->status;
+}
+
+static struct xnudrm_hdr *hdr(uint32_t op, uint64_t a0, uint64_t a1)
+{
+ struct xnudrm_hdr *h = (void *)buf;
+ *h = (struct xnudrm_hdr){ .magic = XNUDRM_MAGIC, .op = op, .arg0 = a0, .arg1 = a1 };
+ return h;
+}
+
+/* ---- the render node as a file ---- */
+
+int xnudrm_open(const char *path, int flags, ...)
+{
+ if (path && !strcmp(path, NODE_RENDER)) {
+ pthread_mutex_lock(&lk);
+ int r = connect_kext();
+ if (!r && node_fd < 0) node_fd = open("/dev/null", O_RDWR | O_CLOEXEC);
+ if (!r && node_fd >= 0) node_refs++;
+ int fd = r ? (errno = -r, -1) : node_fd;
+ pthread_mutex_unlock(&lk);
+ return fd;
+ }
+ if (flags & O_CREAT) {
+ va_list ap; va_start(ap, flags); int mode = va_arg(ap, int); va_end(ap);
+ return open(path, flags, mode);
+ }
+ return open(path, flags);
+}
+
+int xnudrm_close(int fd)
+{
+ pthread_mutex_lock(&lk);
+ if (fd >= 0 && fd == node_fd) {
+ if (--node_refs == 0) {
+ /* the user client stays open: closing it drops every mapping the process still has */
+ }
+ pthread_mutex_unlock(&lk);
+ return 0;
+ }
+ pthread_mutex_unlock(&lk);
+ return close(fd);
+}
+
+int xnudrm_stat(const char *path, struct stat *st)
+{
+ if (path && !strcmp(path, NODE_RENDER)) {
+ memset(st, 0, sizeof(*st));
+ st->st_mode = S_IFCHR | 0666;
+ st->st_rdev = makedev(226, 128);
+ return 0;
+ }
+ if (path && !strcmp(path, NODE_PRIMARY)) { errno = ENOENT; return -1; }
+ return stat(path, st);
+}
+
+/* ---- ioctls ---- */
+
+/* Append len bytes at p (or zeros) to the payload; the field becomes the offset. */
+static int put(uint32_t *plen, uint64_t *field, const void *p, uint64_t len)
+{
+ if (!len) { *field = 0; return 0; }
+ if (*plen + len > XNUDRM_MAX_MSG) return -E2BIG;
+ uint8_t *pl = buf + sizeof(struct xnudrm_hdr);
+ if (p) memcpy(pl + *plen, p, len); else memset(pl + *plen, 0, len);
+ *field = *plen;
+ *plen += (uint32_t)((len + 7) & ~7ull);
+ return 0;
+}
+
+static int new_fence(uint64_t id)
+{
+ int p[2];
+ if (pipe(p)) return -1;
+ fcntl(p[0], F_SETFD, FD_CLOEXEC); fcntl(p[1], F_SETFD, FD_CLOEXEC);
+ struct stat st; fstat(p[0], &st);
+ struct xfence *nf = realloc(fences, (nfences + 1) * sizeof(*fences));
+ if (!nf) { close(p[0]); close(p[1]); return -1; }
+ fences = nf;
+ fences[nfences++] = (struct xfence){ st.st_dev, st.st_ino, p[1], id };
+ return p[0];
+}
+
+static int do_ioctl(unsigned long request, void *arg)
+{
+ uint32_t nr = request & 0xff, size = (request >> 16) & 0x1fff, plen = 0;
+ uint8_t *pl = buf + sizeof(struct xnudrm_hdr);
+ uint64_t f0 = 0, f1 = 0;
+ int r;
+
+ if (size > 256) return -EINVAL;
+ if (nr == DRM_COMMAND_BASE + DRM_VIRTGPU_MAP) { /* answered here: see xnudrm_mmap */
+ struct drm_virtgpu_map *m = arg;
+ m->offset = (uint64_t)m->handle << 12;
+ return 0;
+ }
+ hdr(XNUDRM_IOCTL, nr, 0);
+ memcpy(pl, arg, size);
+ plen = (size + 7) & ~7u;
+ switch (nr) {
+ case DRM_COMMAND_BASE + DRM_VIRTGPU_GETPARAM: {
+ struct drm_virtgpu_getparam *a = (void *)pl;
+ f0 = a->value; if ((r = put(&plen, &a->value, NULL, 8))) return r;
+ break;
+ }
+ case DRM_COMMAND_BASE + DRM_VIRTGPU_GET_CAPS: {
+ struct drm_virtgpu_get_caps *a = (void *)pl;
+ f0 = a->addr; if ((r = put(&plen, &a->addr, NULL, a->size))) return r;
+ break;
+ }
+ case DRM_COMMAND_BASE + DRM_VIRTGPU_CONTEXT_INIT: {
+ struct drm_virtgpu_context_init *a = (void *)pl;
+ if ((r = put(&plen, &a->ctx_set_params, (void *)(uintptr_t)a->ctx_set_params, (uint64_t)a->num_params * sizeof(struct drm_virtgpu_context_set_param)))) return r;
+ break;
+ }
+ case DRM_COMMAND_BASE + DRM_VIRTGPU_RESOURCE_CREATE_BLOB: {
+ struct drm_virtgpu_resource_create_blob *a = (void *)pl;
+ if ((r = put(&plen, &a->cmd, (void *)(uintptr_t)a->cmd, a->cmd_size))) return r;
+ break;
+ }
+ case DRM_COMMAND_BASE + DRM_VIRTGPU_EXECBUFFER: {
+ struct drm_virtgpu_execbuffer *a = (void *)pl;
+ if (a->num_in_syncobjs || a->num_out_syncobjs || (a->flags & VIRTGPU_EXECBUF_FENCE_FD_IN)) return -EOPNOTSUPP;
+ if ((r = put(&plen, &a->command, (void *)(uintptr_t)a->command, a->size))) return r;
+ if ((r = put(&plen, &a->bo_handles, (void *)(uintptr_t)a->bo_handles, (uint64_t)a->num_bo_handles * 4))) return r;
+ break;
+ }
+ case DRM_COMMAND_BASE + DRM_VIRTGPU_RESOURCE_INFO:
+ case DRM_COMMAND_BASE + DRM_VIRTGPU_WAIT:
+ case 0x09: /* GEM_CLOSE */
+ break;
+ default:
+ return -ENOTTY; /* PRIME, syncobj: not over the bridge */
+ }
+ r = call(plen);
+ if (r && r != -EINTR) { if (debug()) fprintf(stderr, "xnudrm: ioctl %#x: %d\n", nr, r); }
+ /* copy the outputs back: the struct, then the out-buffers its pointers named */
+ switch (nr) {
+ case DRM_COMMAND_BASE + DRM_VIRTGPU_GETPARAM: {
+ struct drm_virtgpu_getparam *a = (void *)pl;
+ if (!r) memcpy((void *)(uintptr_t)f0, pl + a->value, sizeof(int));
+ a->value = f0;
+ break;
+ }
+ case DRM_COMMAND_BASE + DRM_VIRTGPU_GET_CAPS: {
+ struct drm_virtgpu_get_caps *a = (void *)pl;
+ if (!r) memcpy((void *)(uintptr_t)f0, pl + a->addr, a->size);
+ a->addr = f0;
+ break;
+ }
+ case DRM_COMMAND_BASE + DRM_VIRTGPU_CONTEXT_INIT:
+ case DRM_COMMAND_BASE + DRM_VIRTGPU_RESOURCE_CREATE_BLOB:
+ case DRM_COMMAND_BASE + DRM_VIRTGPU_EXECBUFFER: {
+ /* pointer fields go back to the caller's values */
+ uint8_t saved[256];
+ memcpy(saved, arg, size);
+ if (nr == DRM_COMMAND_BASE + DRM_VIRTGPU_CONTEXT_INIT) ((struct drm_virtgpu_context_init *)pl)->ctx_set_params = ((struct drm_virtgpu_context_init *)saved)->ctx_set_params;
+ if (nr == DRM_COMMAND_BASE + DRM_VIRTGPU_RESOURCE_CREATE_BLOB) ((struct drm_virtgpu_resource_create_blob *)pl)->cmd = ((struct drm_virtgpu_resource_create_blob *)saved)->cmd;
+ if (nr == DRM_COMMAND_BASE + DRM_VIRTGPU_EXECBUFFER) {
+ struct drm_virtgpu_execbuffer *a = (void *)pl, *s = (void *)saved;
+ a->command = s->command; a->bo_handles = s->bo_handles;
+ if (!r && (a->flags & VIRTGPU_EXECBUF_FENCE_FD_OUT)) a->fence_fd = new_fence((uint32_t)a->fence_fd);
+ if (debug()) fprintf(stderr, "xnudrm: execbuffer flags %#x size %u ring %u -> %d, fence fd %d\n", a->flags, a->size, a->ring_idx, r, a->fence_fd);
+ }
+ break;
+ }
+ }
+ (void)f1;
+ memcpy(arg, pl, size);
+ return r;
+}
+
+int drmIoctl(int fd, unsigned long request, void *arg)
+{
+ if (fd != node_fd || fd < 0) { errno = EBADF; return -1; }
+ pthread_mutex_lock(&lk);
+ int r = do_ioctl(request, arg);
+ pthread_mutex_unlock(&lk);
+ if (r) { errno = -r; return -1; }
+ return 0;
+}
+
+/* ---- mappings: mmap(node fd, offset) after DRM_IOCTL_VIRTGPU_MAP ---- */
+
+/*
+ * VIRTGPU_MAP's offset is the GEM handle's mmap cookie on Linux; xnudrmd maps by handle, so the shim answers MAP itself
+ * with the handle as the offset (MAP is never forwarded) and mmap() maps that handle.
+ */
+void *xnudrm_mmap(void *addr, size_t len, int prot, int flags, int fd, off_t off)
+{
+ if (fd < 0 || fd != node_fd) return mmap(addr, len, prot, flags, fd, off);
+ uint64_t in[2] = { (uint64_t)off >> 12, len }, out[2] = { 0, 0 };
+ uint32_t nout = 2;
+ pthread_mutex_lock(&lk);
+ kern_return_t kr = IOConnectCallScalarMethod(conn, 1, in, 2, out, &nout);
+ if (kr == KERN_SUCCESS) {
+ struct xmap *nm = realloc(maps, (nmaps + 1) * sizeof(*maps));
+ if (nm) { maps = nm; maps[nmaps++] = (struct xmap){ (void *)(uintptr_t)out[0], len, out[1] }; }
+ }
+ pthread_mutex_unlock(&lk);
+ if (kr != KERN_SUCCESS) { if (debug()) fprintf(stderr, "xnudrm: map handle %llu: %#x\n", (unsigned long long)in[0], kr); errno = ENOMEM; return MAP_FAILED; }
+ if (addr && (flags & MAP_FIXED) && addr != (void *)(uintptr_t)out[0]) {
+ /* a placed mapping (VkPhysicalDeviceMapMemoryPlacedFeaturesEXT): not supported over the bridge */
+ xnudrm_munmap((void *)(uintptr_t)out[0], len);
+ errno = EINVAL;
+ return MAP_FAILED;
+ }
+ return (void *)(uintptr_t)out[0];
+}
+
+int xnudrm_munmap(void *addr, size_t len)
+{
+ pthread_mutex_lock(&lk);
+ for (unsigned i = 0; i < nmaps; i++) {
+ if (maps[i].va == addr) {
+ uint64_t id = maps[i].id;
+ maps[i] = maps[--nmaps];
+ IOConnectCallScalarMethod(conn, 2, &id, 1, NULL, NULL);
+ pthread_mutex_unlock(&lk);
+ return 0;
+ }
+ }
+ pthread_mutex_unlock(&lk);
+ return munmap(addr, len);
+}
+
+/* ---- fences ---- */
+
+static struct xfence *fence_of(int fd)
+{
+ struct stat st;
+ if (fstat(fd, &st)) return NULL;
+ for (unsigned i = 0; i < nfences; i++)
+ if (fences[i].ino == st.st_ino && fences[i].dev == st.st_dev) return &fences[i];
+ return NULL;
+}
+
+/* 1 signalled, 0 not yet, <0 error. Called with lk held. */
+static int fence_check(struct xfence *f)
+{
+ if (!f->id) return 1;
+ hdr(XNUDRM_FENCE_WAIT, f->id, 0);
+ int r = call(0);
+ if (r == -XNUDRM_ETIME) return 0;
+ hdr(XNUDRM_FENCE_CLOSE, f->id, 0);
+ call(0);
+ f->id = 0;
+ (void)!write(f->wfd, "s", 1); /* signalled for good */
+ close(f->wfd);
+ f->wfd = -1;
+ return r ? r : 1;
+}
+
+int xnudrm_poll(struct pollfd *fds, nfds_t n, int timeout)
+{
+ struct timespec t0, now;
+ clock_gettime(CLOCK_MONOTONIC, &t0);
+ for (;;) {
+ int pending = 0;
+ pthread_mutex_lock(&lk);
+ for (nfds_t i = 0; i < n; i++) {
+ struct xfence *f = nfences ? fence_of(fds[i].fd) : NULL;
+ if (f && f->id && fence_check(f) == 0) pending = 1;
+ }
+ pthread_mutex_unlock(&lk);
+ if (debug()) fprintf(stderr, "xnudrm: poll %u fds, timeout %d: %s\n", (unsigned)n, timeout, pending ? "pending" : "ready");
+ if (!pending) return poll(fds, n, timeout); /* signalled fences are readable pipes now */
+ clock_gettime(CLOCK_MONOTONIC, &now);
+ long ms = (now.tv_sec - t0.tv_sec) * 1000 + (now.tv_nsec - t0.tv_nsec) / 1000000;
+ if (timeout >= 0 && ms >= timeout) return poll(fds, n, 0);
+ /* each check stops the hosted CPU for one host call: back off a little */
+ struct timespec d = { 0, 200000 };
+ nanosleep(&d, NULL);
+ }
+}
+
+/* ---- device discovery ---- */
+
+int drmGetDevices2(uint32_t flags, drmDevicePtr devices[], int max)
+{
+ if (!devices) return 1;
+ if (max < 1) return 0;
+ drmDevicePtr d = calloc(1, sizeof(*d) + DRM_NODE_MAX * sizeof(char *) + sizeof(drmPciBusInfo) + sizeof(drmPciDeviceInfo));
+ if (!d) return -ENOMEM;
+ d->nodes = (char **)(d + 1);
+ d->nodes[DRM_NODE_PRIMARY] = NODE_PRIMARY;
+ d->nodes[DRM_NODE_RENDER] = NODE_RENDER;
+ d->available_nodes = 1 << DRM_NODE_RENDER;
+ d->bustype = DRM_BUS_PCI;
+ d->businfo.pci = (drmPciBusInfoPtr)(d->nodes + DRM_NODE_MAX);
+ d->deviceinfo.pci = (drmPciDeviceInfoPtr)(d->businfo.pci + 1);
+ d->deviceinfo.pci->vendor_id = 0x1af4; /* virtio */
+ d->deviceinfo.pci->device_id = 0x1050; /* virtio-gpu */
+ devices[0] = d;
+ return 1;
+}
+
+void drmFreeDevices(drmDevicePtr devices[], int count)
+{
+ for (int i = 0; i < count; i++) free(devices[i]);
+}
+
+drmVersionPtr drmGetVersion(int fd)
+{
+ if (fd != node_fd) return NULL;
+ drmVersionPtr v = calloc(1, sizeof(*v));
+ if (!v) return NULL;
+ v->name = "virtio_gpu";
+ v->name_len = 10;
+ v->desc = "virtio GPU over the xnulinux DRM bridge";
+ v->date = "0";
+ return v;
+}
+
+void drmFreeVersion(drmVersionPtr v) { free(v); }
diff --git a/gpu/xnu-drm/darwin/xnudrm_compat.h b/gpu/xnu-drm/darwin/xnudrm_compat.h
new file mode 100644
index 0000000..9936a9b
--- /dev/null
+++ b/gpu/xnu-drm/darwin/xnudrm_compat.h
@@ -0,0 +1,33 @@
+/* SPDX-License-Identifier: MIT */
+/*
+ * Force-included (pkg-config Cflags) into Mesa's Venus driver on macOS: the render node and its mappings and fences live
+ * behind kexts/XnuDrm, so open/close/mmap/munmap/stat/poll on them go to libxnudrm. Everything else falls through to the
+ * system's own calls.
+ */
+#ifndef XNUDRM_COMPAT_H
+#define XNUDRM_COMPAT_H
+#include <fcntl.h>
+#include <poll.h>
+#include <sys/mman.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
+#ifdef __cplusplus
+extern "C" {
+#endif
+int xnudrm_open(const char *path, int flags, ...);
+int xnudrm_close(int fd);
+void *xnudrm_mmap(void *addr, size_t len, int prot, int flags, int fd, off_t off);
+int xnudrm_munmap(void *addr, size_t len);
+int xnudrm_stat(const char *path, struct stat *st);
+int xnudrm_poll(struct pollfd *fds, nfds_t n, int timeout);
+#ifdef __cplusplus
+}
+#endif
+#define open xnudrm_open
+#define close xnudrm_close
+#define mmap xnudrm_mmap
+#define munmap xnudrm_munmap
+#define stat(p, s) xnudrm_stat(p, s)
+#define poll xnudrm_poll
+#endif
diff --git a/gpu/xnu-drm/xnudrm_proto.h b/gpu/xnu-drm/xnudrm_proto.h
new file mode 100644
index 0000000..d838999
--- /dev/null
+++ b/gpu/xnu-drm/xnudrm_proto.h
@@ -0,0 +1,45 @@
+/* SPDX-License-Identifier: MIT */
+/*
+ * The DRM bridge's messages: from a macOS process (libxnudrm, through kexts/XnuDrm and a host call) to xnudrmd, the Linux
+ * service that owns the DRM render node. Shared by all three ends; plain C, fixed-size little-endian fields.
+ *
+ * A message is a header and a payload. XNUDRM_IOCTL carries a Linux DRM ioctl: the payload is the ioctl's argument struct
+ * followed by an aux area; each user pointer inside the struct is replaced by an offset into the payload (from the start of
+ * the payload), and the reply's payload has the same layout with the outputs filled in.
+ */
+#ifndef XNUDRM_PROTO_H
+#define XNUDRM_PROTO_H
+#include <stdint.h>
+
+#define XNUDRM_MAGIC 0x4d52444eu /* "NDRM" */
+#define XNUDRM_VERSION 1
+#define XNUDRM_MAX_MSG (8u << 20)
+/* status is a Linux errno; the ones a client tests by value (macOS numbers some differently: ETIME is 101 there) */
+#define XNUDRM_ETIME 62
+
+enum xnudrm_op {
+ XNUDRM_OPEN = 1, /* -> client (a new DRM file on the render node); arg0 = XNUDRM_VERSION */
+ XNUDRM_CLOSE, /* client: closes the file, its mappings and fences */
+ XNUDRM_IOCTL, /* client, arg0 = Linux ioctl number; payload as above */
+ XNUDRM_MAP, /* client, arg0 = GEM handle, arg1 = size -> arg0 = map id; payload: struct xnudrm_range[] */
+ XNUDRM_UNMAP, /* client, arg0 = map id */
+ XNUDRM_FENCE_WAIT, /* client, arg0 = fence id, arg1 = timeout in ns (0: poll) -> status 0, -XNUDRM_ETIME */
+ XNUDRM_FENCE_CLOSE, /* client, arg0 = fence id */
+};
+
+struct xnudrm_hdr {
+ uint32_t magic;
+ uint32_t op;
+ uint32_t client;
+ int32_t status; /* reply: 0 or a negative Linux errno */
+ uint64_t arg0, arg1;
+ uint32_t payload_len;
+ uint32_t pad;
+};
+
+/* A physically contiguous piece of a mapping, in order. */
+struct xnudrm_range {
+ uint64_t pa, len;
+};
+
+#endif
diff --git a/gpu/xnu-drm/xnudrmd.c b/gpu/xnu-drm/xnudrmd.c
new file mode 100644
index 0000000..8c52cee
--- /dev/null
+++ b/gpu/xnu-drm/xnudrmd.c
@@ -0,0 +1,268 @@
+// SPDX-License-Identifier: MIT
+/*
+ * xnudrmd: the Linux end of the DRM bridge. It serves the hosted macOS's GPU clients (kexts/XnuDrm, libxnudrm) from
+ * Linux's virtio-gpu render node: each request comes as a host call on /dev/xnu-hostcall (fki), is carried out with an
+ * ordinary DRM ioctl, mmap or poll, and answered with the outputs. Mappings are translated into physical addresses
+ * (fki's XNU_HOSTCALL_XLATE) so the hosted kernel maps the very same pages into its process: no copies.
+ *
+ * Usage: xnudrmd [render node, default /dev/dri/renderD128]. Run as root (the hostcall device is 0600).
+ */
+#define _GNU_SOURCE
+#include <errno.h>
+#include <fcntl.h>
+#include <poll.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/ioctl.h>
+#include <sys/mman.h>
+#include <unistd.h>
+#include <drm/drm.h>
+#include <drm/virtgpu_drm.h>
+#include "xnudrm_proto.h"
+
+struct xnu_hostcall_xlate { uint64_t va, len, out, max; };
+#define XNU_HOSTCALL_XLATE _IOWR('X', 1, struct xnu_hostcall_xlate)
+
+#define MAX_CLIENTS 256
+#define MAX_MAPS 65536
+#define MAX_FENCES 65536
+
+static const char *node = "/dev/dri/renderD128";
+static int hc = -1;
+static int verbose;
+static int clients[MAX_CLIENTS]; /* DRM fd + 1 (0: free) */
+static struct map { int client; void *va; size_t len; } maps[MAX_MAPS];
+static struct fence { int client; int fd; } fences[MAX_FENCES]; /* fd + 1 */
+
+static uint8_t *msg, *rep;
+#define PAYLOAD(m) ((m) + 8 + sizeof(struct xnudrm_hdr))
+
+static int client_fd(uint32_t c) { return c && c < MAX_CLIENTS && clients[c] ? clients[c] - 1 : -1; }
+
+/* A pointer field of an ioctl struct: an offset into the payload, checked to lie inside it with len bytes. */
+static int ptr_field(uint8_t *payload, uint32_t plen, __u64 *field, uint64_t len)
+{
+ uint64_t off = *field;
+ if (len == 0) { *field = 0; return 0; }
+ if (off > plen || len > plen - off) return -EINVAL;
+ *field = (uint64_t)(uintptr_t)(payload + off);
+ return 0;
+}
+static void unptr_field(uint8_t *payload, __u64 *field)
+{
+ if (*field) *field = (uint64_t)((uint8_t *)(uintptr_t)*field - payload);
+}
+
+static int do_ioctl(int fd, uint32_t client, uint32_t nr, uint8_t *p, uint32_t plen)
+{
+ int r = 0;
+#define NEED(type) do { if (plen < sizeof(type)) return -EINVAL; } while (0)
+ switch (nr) {
+ case DRM_COMMAND_BASE + DRM_VIRTGPU_GETPARAM: {
+ struct drm_virtgpu_getparam *a = (void *)p; NEED(*a);
+ if ((r = ptr_field(p, plen, &a->value, sizeof(int)))) return r;
+ r = ioctl(fd, DRM_IOCTL_VIRTGPU_GETPARAM, a);
+ unptr_field(p, &a->value);
+ break;
+ }
+ case DRM_COMMAND_BASE + DRM_VIRTGPU_GET_CAPS: {
+ struct drm_virtgpu_get_caps *a = (void *)p; NEED(*a);
+ if ((r = ptr_field(p, plen, &a->addr, a->size))) return r;
+ r = ioctl(fd, DRM_IOCTL_VIRTGPU_GET_CAPS, a);
+ unptr_field(p, &a->addr);
+ break;
+ }
+ case DRM_COMMAND_BASE + DRM_VIRTGPU_CONTEXT_INIT: {
+ struct drm_virtgpu_context_init *a = (void *)p; NEED(*a);
+ if ((r = ptr_field(p, plen, &a->ctx_set_params, (uint64_t)a->num_params * sizeof(struct drm_virtgpu_context_set_param)))) return r;
+ r = ioctl(fd, DRM_IOCTL_VIRTGPU_CONTEXT_INIT, a);
+ unptr_field(p, &a->ctx_set_params);
+ break;
+ }
+ case DRM_COMMAND_BASE + DRM_VIRTGPU_RESOURCE_CREATE_BLOB: {
+ struct drm_virtgpu_resource_create_blob *a = (void *)p; NEED(*a);
+ if ((r = ptr_field(p, plen, &a->cmd, a->cmd_size))) return r;
+ r = ioctl(fd, DRM_IOCTL_VIRTGPU_RESOURCE_CREATE_BLOB, a);
+ unptr_field(p, &a->cmd);
+ break;
+ }
+ case DRM_COMMAND_BASE + DRM_VIRTGPU_RESOURCE_INFO: {
+ NEED(struct drm_virtgpu_resource_info);
+ r = ioctl(fd, DRM_IOCTL_VIRTGPU_RESOURCE_INFO, p);
+ break;
+ }
+ case DRM_COMMAND_BASE + DRM_VIRTGPU_WAIT: {
+ NEED(struct drm_virtgpu_3d_wait);
+ r = ioctl(fd, DRM_IOCTL_VIRTGPU_WAIT, p);
+ break;
+ }
+ case 0x09: { /* DRM_IOCTL_GEM_CLOSE */
+ NEED(struct drm_gem_close);
+ r = ioctl(fd, DRM_IOCTL_GEM_CLOSE, p);
+ break;
+ }
+ case DRM_COMMAND_BASE + DRM_VIRTGPU_EXECBUFFER: {
+ struct drm_virtgpu_execbuffer *a = (void *)p; NEED(*a);
+ if (a->num_in_syncobjs || a->num_out_syncobjs || (a->flags & VIRTGPU_EXECBUF_FENCE_FD_IN)) return -EOPNOTSUPP;
+ if ((r = ptr_field(p, plen, &a->command, a->size))) return r;
+ if ((r = ptr_field(p, plen, &a->bo_handles, (uint64_t)a->num_bo_handles * 4))) return r;
+ a->fence_fd = -1;
+ r = ioctl(fd, DRM_IOCTL_VIRTGPU_EXECBUFFER, a);
+ unptr_field(p, &a->command);
+ unptr_field(p, &a->bo_handles);
+ if (r == 0 && (a->flags & VIRTGPU_EXECBUF_FENCE_FD_OUT)) {
+ int i;
+ for (i = 1; i < MAX_FENCES && fences[i].fd; i++) ;
+ if (i == MAX_FENCES) { close(a->fence_fd); a->fence_fd = -1; return -EMFILE; }
+ fences[i].fd = a->fence_fd + 1;
+ fences[i].client = client;
+ a->fence_fd = i; /* the fence's id */
+ }
+ break;
+ }
+ default:
+ return -ENOTTY;
+ }
+ return r < 0 ? -errno : 0;
+}
+
+static int do_map(int fd, uint32_t client, struct xnudrm_hdr *h, uint8_t *out, uint32_t *outlen)
+{
+ struct drm_virtgpu_map m = { .handle = (uint32_t)h->arg0 };
+ size_t len = (h->arg1 + 4095) & ~(size_t)4095;
+ struct xnudrm_range *rg = (void *)out;
+ uint32_t nr = 0, maxr = (XNUDRM_MAX_MSG - sizeof(*h)) / sizeof(*rg);
+ uint64_t *pa;
+ size_t i, n = len >> 12;
+ int id;
+ void *va;
+
+ if (!len) return -EINVAL;
+ for (id = 1; id < MAX_MAPS && maps[id].va; id++) ;
+ if (id == MAX_MAPS) return -ENOMEM;
+ if (ioctl(fd, DRM_IOCTL_VIRTGPU_MAP, &m)) return -errno;
+ va = mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, m.offset);
+ if (va == MAP_FAILED) return -errno;
+ for (i = 0; i < n; i++) (void)*(volatile uint8_t *)((uint8_t *)va + (i << 12)); /* fault every page in */
+ pa = malloc(n * 8);
+ if (!pa) { munmap(va, len); return -ENOMEM; }
+ struct xnu_hostcall_xlate x = { (uintptr_t)va, len, (uintptr_t)pa, n };
+ if (ioctl(hc, XNU_HOSTCALL_XLATE, &x)) { int e = -errno; free(pa); munmap(va, len); return e; }
+ for (i = 0; i < n; i++) {
+ if (nr && rg[nr - 1].pa + rg[nr - 1].len == pa[i]) { rg[nr - 1].len += 4096; continue; }
+ if (nr == maxr) { free(pa); munmap(va, len); return -E2BIG; }
+ rg[nr].pa = pa[i]; rg[nr].len = 4096; nr++;
+ }
+ free(pa);
+ maps[id] = (struct map){ client, va, len };
+ h->arg0 = id;
+ *outlen = nr * sizeof(*rg);
+ if (verbose) fprintf(stderr, "map %d: handle %u, %zu bytes, %u ranges, first pa %#llx\n", id, m.handle, len, nr, (unsigned long long)rg[0].pa);
+ return 0;
+}
+
+static void drop_client(uint32_t c)
+{
+ int i;
+ for (i = 1; i < MAX_MAPS; i++) if (maps[i].va && maps[i].client == (int)c) { munmap(maps[i].va, maps[i].len); maps[i].va = NULL; }
+ for (i = 1; i < MAX_FENCES; i++) if (fences[i].fd && fences[i].client == (int)c) { close(fences[i].fd - 1); fences[i].fd = 0; }
+ if (clients[c]) close(clients[c] - 1);
+ clients[c] = 0;
+}
+
+static void serve(uint8_t *in, size_t inlen, uint8_t *out, size_t *outlen)
+{
+ struct xnudrm_hdr *h = (void *)(in + 8), *rh = (void *)(out + 8);
+ uint8_t *payload = PAYLOAD(in), *rpayload = PAYLOAD(out);
+ uint32_t rlen = 0;
+ int fd, st = 0;
+
+ memcpy(out, in, 8); /* the call's sequence number */
+ if (inlen < 8 + sizeof(*h) || h->magic != XNUDRM_MAGIC || h->payload_len > inlen - 8 - sizeof(*h)) {
+ *rh = (struct xnudrm_hdr){ .magic = XNUDRM_MAGIC, .status = -EINVAL };
+ *outlen = 8 + sizeof(*rh);
+ return;
+ }
+ *rh = *h;
+ rh->payload_len = 0;
+ fd = client_fd(h->client);
+ switch (h->op) {
+ case XNUDRM_OPEN: {
+ int c, f;
+ if (h->arg0 != XNUDRM_VERSION) { st = -EPROTO; break; }
+ for (c = 1; c < MAX_CLIENTS && clients[c]; c++) ;
+ if (c == MAX_CLIENTS) { st = -EMFILE; break; }
+ f = open(node, O_RDWR | O_CLOEXEC);
+ if (f < 0) { st = -errno; break; }
+ clients[c] = f + 1;
+ rh->client = c;
+ if (verbose) fprintf(stderr, "open: client %d\n", c);
+ break;
+ }
+ case XNUDRM_CLOSE:
+ if (fd < 0) { st = -EBADF; break; }
+ drop_client(h->client);
+ if (verbose) fprintf(stderr, "close: client %u\n", h->client);
+ break;
+ case XNUDRM_IOCTL:
+ if (fd < 0) { st = -EBADF; break; }
+ memcpy(rpayload, payload, h->payload_len);
+ st = do_ioctl(fd, h->client, (uint32_t)h->arg0, rpayload, h->payload_len);
+ rlen = h->payload_len;
+ if (verbose > 1) fprintf(stderr, "ioctl %#x: %d\n", (unsigned)h->arg0, st);
+ break;
+ case XNUDRM_MAP:
+ if (fd < 0) { st = -EBADF; break; }
+ st = do_map(fd, h->client, rh, rpayload, &rlen);
+ break;
+ case XNUDRM_UNMAP:
+ if (h->arg0 == 0 || h->arg0 >= MAX_MAPS || !maps[h->arg0].va || maps[h->arg0].client != (int)h->client) { st = -EINVAL; break; }
+ munmap(maps[h->arg0].va, maps[h->arg0].len);
+ maps[h->arg0].va = NULL;
+ break;
+ case XNUDRM_FENCE_WAIT:
+ case XNUDRM_FENCE_CLOSE: {
+ struct fence *f = h->arg0 && h->arg0 < MAX_FENCES ? &fences[h->arg0] : NULL;
+ if (!f || !f->fd || f->client != (int)h->client) { st = -EINVAL; break; }
+ if (h->op == XNUDRM_FENCE_CLOSE) { close(f->fd - 1); f->fd = 0; break; }
+ struct pollfd p = { .fd = f->fd - 1, .events = POLLIN };
+ int ms = h->arg1 ? (int)((h->arg1 + 999999) / 1000000) : 0;
+ int r = poll(&p, 1, ms > 60000 ? 60000 : ms); /* the hosted CPU waits in the call: never longer than a minute */
+ st = r < 0 ? -errno : r == 0 ? -XNUDRM_ETIME : 0;
+ break;
+ }
+ default:
+ st = -ENOSYS;
+ }
+ rh->status = st;
+ rh->payload_len = st == 0 || h->op == XNUDRM_IOCTL ? rlen : 0;
+ *outlen = 8 + sizeof(*rh) + rh->payload_len;
+}
+
+int main(int argc, char **argv)
+{
+ int a;
+ for (a = 1; a < argc; a++) {
+ if (!strcmp(argv[a], "-v")) verbose++;
+ else node = argv[a];
+ }
+ hc = open("/dev/xnu-hostcall", O_RDWR | O_CLOEXEC);
+ if (hc < 0) { perror("/dev/xnu-hostcall"); return 1; }
+ msg = malloc(8 + XNUDRM_MAX_MSG + sizeof(struct xnudrm_hdr));
+ rep = malloc(8 + XNUDRM_MAX_MSG + sizeof(struct xnudrm_hdr));
+ if (!msg || !rep) return 1;
+ fprintf(stderr, "xnudrmd: serving %s\n", node);
+ for (;;) {
+ ssize_t n = read(hc, msg, 8 + XNUDRM_MAX_MSG + sizeof(struct xnudrm_hdr));
+ size_t rn;
+ if (n < 0) {
+ if (errno == EINTR || errno == EAGAIN) continue;
+ perror("read");
+ return 1;
+ }
+ serve(msg, (size_t)n, rep, &rn);
+ if (write(hc, rep, rn) < 0 && errno != ESTALE) perror("write");
+ }
+}
diff --git a/kexts/XnuDrm/XnuDrm.cpp b/kexts/XnuDrm/XnuDrm.cpp
new file mode 100644
index 0000000..41118f3
--- /dev/null
+++ b/kexts/XnuDrm/XnuDrm.cpp
@@ -0,0 +1,227 @@
+// SPDX-License-Identifier: BSD-2-Clause
+// XnuDrm: the hosted macOS's door to the Linux host's GPU (the DRM bridge, gpu/xnu-drm). A process opens a user client
+// (libxnudrm, inside Mesa's Venus driver); each of its requests is one host call (linux64_hostcall: upcall 830, xnu.ko,
+// 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.
+//
+// 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
+// 1 map(gem_handle, size) -> (user address, map id) XNUDRM_MAP, then the pages mapped into the task
+// 2 unmap(map id)
+#include <IOKit/IOService.h>
+#include <IOKit/IOUserClient.h>
+#include <IOKit/IOMemoryDescriptor.h>
+#include <IOKit/IOLib.h>
+#include <IOKit/IOLocks.h>
+#include <mach/kmod.h>
+#include <sys/errno.h>
+#include <libkern/copyio.h>
+#include "../../gpu/xnu-drm/xnudrm_proto.h"
+
+extern "C" long linux64_hostcall(const void *req, unsigned long len, void *reply, unsigned long max);
+
+static IOLock *gCallLock; // one host call at a time (the bounce buffers are shared)
+static uint8_t *gIn, *gOut; // XNUDRM_MAX_MSG + header each
+
+// A message to xnudrmd and its reply (both in gIn/gOut, under gCallLock). Returns the reply's length or -errno.
+static long hostcall(unsigned long len)
+{
+ long r = linux64_hostcall(gIn, len, gOut, sizeof(xnudrm_hdr) + XNUDRM_MAX_MSG);
+ if (r >= 0 && ((size_t)r < sizeof(xnudrm_hdr) || ((xnudrm_hdr *)gOut)->magic != XNUDRM_MAGIC)) r = -EPROTO;
+ return r;
+}
+
+class XnuDrm : public IOService {
+ OSDeclareDefaultStructors(XnuDrm)
+public:
+ bool start(IOService *provider) override;
+};
+
+class XnuDrmClient : public IOUserClient {
+ OSDeclareDefaultStructors(XnuDrmClient)
+ task_t fTask = nullptr;
+ uint32_t fClient = 0; // xnudrmd's client id (0: not open)
+ struct Slot { uint64_t id; IOMemoryMap *map; IOMemoryDescriptor *md; };
+ Slot *fSlots = nullptr;
+ unsigned fNSlots = 0;
+ long simple(uint32_t op, uint64_t a0, uint64_t a1, xnudrm_hdr *reply);
+ IOReturn doCall(IOExternalMethodArguments *a);
+ IOReturn doMap(IOExternalMethodArguments *a);
+ IOReturn doUnmap(IOExternalMethodArguments *a);
+public:
+ bool initWithTask(task_t owningTask, void *securityID, UInt32 type) override;
+ IOReturn clientClose() override;
+ void free() override;
+ IOReturn externalMethod(uint32_t selector, IOExternalMethodArguments *arguments, IOExternalMethodDispatch *dispatch,
+ OSObject *target, void *reference) override;
+};
+
+OSDefineMetaClassAndStructors(XnuDrm, IOService)
+OSDefineMetaClassAndStructors(XnuDrmClient, IOUserClient)
+
+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;
+ }
+ setProperty("IOUserClientClass", "XnuDrmClient");
+ registerService();
+ IOLog("XnuDrm: GPU bridge ready\n");
+ return true;
+}
+
+bool XnuDrmClient::initWithTask(task_t owningTask, void *securityID, UInt32 type)
+{
+ if (!IOUserClient::initWithTask(owningTask, securityID, type)) return false;
+ fTask = owningTask;
+ xnudrm_hdr r;
+ long n = simple(XNUDRM_OPEN, XNUDRM_VERSION, 0, &r);
+ if (n < 0 || r.status) {
+ IOLog("XnuDrm: xnudrmd did not open a client (%ld, %d)\n", n, n < 0 ? 0 : r.status);
+ return false;
+ }
+ fClient = r.client;
+ return true;
+}
+
+// A message without payload; the reply's header into *reply.
+long XnuDrmClient::simple(uint32_t op, uint64_t a0, uint64_t a1, xnudrm_hdr *reply)
+{
+ IOLockLock(gCallLock);
+ xnudrm_hdr *h = (xnudrm_hdr *)gIn;
+ *h = (xnudrm_hdr){ .magic = XNUDRM_MAGIC, .op = op, .client = fClient, .arg0 = a0, .arg1 = a1 };
+ long n = hostcall(sizeof(*h));
+ if (n >= 0) *reply = *(xnudrm_hdr *)gOut;
+ IOLockUnlock(gCallLock);
+ return n;
+}
+
+IOReturn XnuDrmClient::doCall(IOExternalMethodArguments *a)
+{
+ user_addr_t in = a->scalarInput[0], out = a->scalarInput[2];
+ uint64_t inlen = a->scalarInput[1], outmax = a->scalarInput[3];
+ if (inlen < sizeof(xnudrm_hdr) || inlen > sizeof(xnudrm_hdr) + XNUDRM_MAX_MSG) return kIOReturnBadArgument;
+ IOLockLock(gCallLock);
+ IOReturn ret = kIOReturnSuccess;
+ xnudrm_hdr *h = (xnudrm_hdr *)gIn;
+ long n = -1;
+ if (copyin(in, gIn, inlen)) { ret = kIOReturnVMError; goto out; }
+ h->magic = XNUDRM_MAGIC;
+ h->client = fClient;
+ h->payload_len = (uint32_t)(inlen - sizeof(*h));
+ if (h->op != XNUDRM_IOCTL && h->op != XNUDRM_FENCE_WAIT && h->op != XNUDRM_FENCE_CLOSE) { ret = kIOReturnUnsupported; goto out; }
+ n = hostcall(inlen);
+ if (n < 0) { IOLog("XnuDrm: host call failed (%ld)\n", n); ret = kIOReturnNotResponding; goto out; }
+ if ((uint64_t)n > outmax) { ret = kIOReturnNoSpace; goto out; }
+ if (copyout(gOut, out, n)) { ret = kIOReturnVMError; goto out; }
+ a->scalarOutput[0] = n;
+out:
+ IOLockUnlock(gCallLock);
+ return ret;
+}
+
+IOReturn XnuDrmClient::doMap(IOExternalMethodArguments *a)
+{
+ uint64_t handle = a->scalarInput[0], size = a->scalarInput[1];
+ IOLockLock(gCallLock);
+ xnudrm_hdr *h = (xnudrm_hdr *)gIn;
+ *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) {
+ IOLockUnlock(gCallLock);
+ IOLog("XnuDrm: map of handle %llu failed (%ld, %d)\n", handle, n, n < 0 ? 0 : r->status);
+ return kIOReturnNoMemory;
+ }
+ uint64_t id = r->arg0;
+ uint32_t nr = r->payload_len / sizeof(xnudrm_range);
+ IOAddressRange *ranges = (IOAddressRange *)IOMallocData(nr * sizeof(IOAddressRange));
+ if (!ranges) { IOLockUnlock(gCallLock); 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);
+
+ // Linux's pages, outside of XNU's own memory: normal cacheable memory, as Linux maps them (the host keeps blob memory
+ // coherent with the GPU)
+ IOOptionBits opts = kIODirectionInOut;
+ opts |= kIOMemoryTypePhysical64;
+ opts |= kIOMemoryMapperNone;
+ IOMemoryDescriptor *md = IOMemoryDescriptor::withAddressRanges(ranges, nr, opts, nullptr);
+ IOFreeData(ranges, nr * sizeof(IOAddressRange));
+ IOMemoryMap *map = md ? md->createMappingInTask(fTask, 0, kIOMapAnywhere | kIOMapCopybackCache) : nullptr;
+ if (!map) {
+ if (md) md->release();
+ xnudrm_hdr ur;
+ simple(XNUDRM_UNMAP, id, 0, &ur);
+ return kIOReturnNoMemory;
+ }
+ unsigned i;
+ for (i = 0; i < fNSlots && fSlots[i].map; i++) ;
+ 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 (fSlots) { memcpy(s, fSlots, fNSlots * sizeof(Slot)); IOFreeData(fSlots, fNSlots * sizeof(Slot)); }
+ fSlots = s; fNSlots = nn;
+ }
+ fSlots[i] = (Slot){ id, map, md };
+ a->scalarOutput[0] = map->getAddress();
+ a->scalarOutput[1] = id;
+ return kIOReturnSuccess;
+}
+
+IOReturn XnuDrmClient::doUnmap(IOExternalMethodArguments *a)
+{
+ uint64_t id = a->scalarInput[0];
+ for (unsigned i = 0; i < fNSlots; i++) {
+ if (fSlots[i].map && fSlots[i].id == id) {
+ fSlots[i].map->release(); // unmaps from the task before Linux lets go of the pages
+ fSlots[i].md->release();
+ fSlots[i] = (Slot){};
+ xnudrm_hdr r;
+ simple(XNUDRM_UNMAP, id, 0, &r);
+ return kIOReturnSuccess;
+ }
+ }
+ return kIOReturnBadArgument;
+}
+
+IOReturn XnuDrmClient::externalMethod(uint32_t selector, IOExternalMethodArguments *a, IOExternalMethodDispatch *,
+ OSObject *, void *)
+{
+ switch (selector) {
+ case 0: if (a->scalarInputCount != 4 || a->scalarOutputCount != 1) return kIOReturnBadArgument; return doCall(a);
+ case 1: if (a->scalarInputCount != 2 || a->scalarOutputCount != 2) return kIOReturnBadArgument; return doMap(a);
+ case 2: if (a->scalarInputCount != 1) return kIOReturnBadArgument; return doUnmap(a);
+ }
+ return kIOReturnUnsupported;
+}
+
+IOReturn XnuDrmClient::clientClose()
+{
+ for (unsigned i = 0; i < fNSlots; i++) {
+ if (fSlots[i].map) { fSlots[i].map->release(); fSlots[i].md->release(); fSlots[i] = (Slot){}; }
+ }
+ if (fClient) {
+ xnudrm_hdr r;
+ simple(XNUDRM_CLOSE, 0, 0, &r); // xnudrmd drops the client's mappings, fences and DRM file
+ fClient = 0;
+ }
+ terminate();
+ return kIOReturnSuccess;
+}
+
+void XnuDrmClient::free()
+{
+ if (fSlots) IOFreeData(fSlots, fNSlots * sizeof(Slot));
+ IOUserClient::free();
+}
+
+extern "C" {
+kern_return_t native_kext_start(kmod_info_t *, void *) { return KERN_SUCCESS; }
+kern_return_t native_kext_stop(kmod_info_t *, void *) { return KERN_SUCCESS; }
+}
diff --git a/kexts/XnuDrm/XnuDrm.json b/kexts/XnuDrm/XnuDrm.json
new file mode 100644
index 0000000..a97816d
--- /dev/null
+++ b/kexts/XnuDrm/XnuDrm.json
@@ -0,0 +1,25 @@
+{
+ "name": "XnuDrm",
+ "bundle": "org.xnulinux.driver.XnuDrm",
+ "version": "1.0.0",
+ "objects": "out/x12377/native-kexts/XnuDrm/objects.json",
+ "start": "_native_kext_start",
+ "stop": "_native_kext_stop",
+ "libraries": {
+ "com.apple.kpi.bsd": "18.0.0",
+ "com.apple.kpi.iokit": "18.0.0",
+ "com.apple.kpi.libkern": "18.0.0",
+ "com.apple.kpi.mach": "18.0.0",
+ "com.apple.kpi.private": "18.0.0",
+ "com.apple.kpi.unsupported": "18.0.0"
+ },
+ "personalities": {
+ "XnuDrm": {
+ "CFBundleIdentifier": "org.xnulinux.driver.XnuDrm",
+ "IOClass": "XnuDrm",
+ "IOProviderClass": "IOResources",
+ "IOResourceMatch": "IOKit",
+ "IOMatchCategory": "XnuDrm"
+ }
+ }
+}
diff --git a/xnu-ko/xnu_main.c b/xnu-ko/xnu_main.c
index 95e7556..a1e4bc7 100644
--- a/xnu-ko/xnu_main.c
+++ b/xnu-ko/xnu_main.c
@@ -124,6 +124,8 @@ static char root_matching[256];
static void *in_file; static fki_u64 in_off;
/* hook returns must be 0 (nonzero ends the run): results come back through the request */
struct xnu_hostdisk_req { u64_t write, off, len; void *buf; long result; };
+/* A host call (upcall 830, kexts/XnuDrm): request and reply buffers in XNU memory, through fki to a Linux service */
+struct xnu_hostcall_req { const void *req; u64_t len; void *reply; u64_t max; long result; };
struct xnu_net_req { void *buf; u64_t len; long result; };
struct xnu_world xnu_W;
@@ -383,6 +385,11 @@ static long xnu_hook_body(unsigned long stage, unsigned long a1, unsigned long a
if (a1) fki_realtime(&((fki_u64 *)a1)[0], &((fki_u64 *)a1)[1]);
return 0;
}
+ if (stage == 830) { /* host call: q->result = the reply's length or -errno */
+ struct xnu_hostcall_req *q = (struct xnu_hostcall_req *)a1;
+ if (q) q->result = fki_hostcall(q->req, (unsigned long)q->len, q->reply, (unsigned long)q->max);
+ return 0;
+ }
if (stage == 821) { /* the block disk's size in bytes into *a1, 0 when there is none */
if (a1) *(u64_t *)a1 = dk_file ? dk_size : 0;
return 0;
diff --git a/xnu-patches/0001-linux64-stage-hook.patch b/xnu-patches/0001-linux64-stage-hook.patch
index c27805f..2fe435c 100644
--- a/xnu-patches/0001-linux64-stage-hook.patch
+++ b/xnu-patches/0001-linux64-stage-hook.patch
@@ -794,7 +794,7 @@ new file mode 100644
index 0000000..29cf3df
--- /dev/null
+++ b/bsd/net/if_linux64.c
-@@ -0,0 +1,307 @@
+@@ -0,0 +1,331 @@
+/*
+ * LINUX64 (xnulinux): the hosted kernel's Ethernet interface en0.
+ *
@@ -1028,6 +1028,30 @@ index 0000000..29cf3df
+ return q.result;
+}
+
++/*
++ * A host call (kexts/XnuDrm): len bytes at req to a Linux service through xnu.ko and fki (upcall 830), its reply into
++ * reply (at most max bytes). Returns the reply's length or a negative errno. The CPU waits in the call.
++ */
++struct linux64_hostcall_req {
++ const void *req;
++ uint64_t len;
++ void *reply;
++ uint64_t max;
++ long result;
++};
++long linux64_hostcall(const void *req, unsigned long len, void *reply, unsigned long max);
++long
++linux64_hostcall(const void *req, unsigned long len, void *reply, unsigned long max)
++{
++ struct linux64_hostcall_req q = { .req = req, .len = len, .reply = reply, .max = max, .result = -6 };
++
++ if (linux64_hook == 0) {
++ return -6;
++ }
++ linux64_stage_arg(830, (unsigned long)&q);
++ return q.result;
++}
++
+/* From the hosted idle loop, after the host let it sleep: wake the receive thread when Linux queued frames. */
+void linux64_net_idle_poll(void);
+void