Skip to content

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

C

fki.ko: builds on Ubuntu 24.04's kernels; host-call device without the XLATE deadlock, the lost request or the late reply; cpu_list wakeup, carve-out and read-only file checks; real-kernel tests

Fred Nix172c62e26288
diff --git a/.github/workflows/modules-kernels.yml b/.github/workflows/modules-kernels.yml
new file mode 100644
index 0000000..480f481
--- /dev/null
+++ b/.github/workflows/modules-kernels.yml
@@ -0,0 +1,34 @@
+# SPDX-License-Identifier: GPL-2.0-only
+# fki.ko and xnu.ko build against every kernel series Ubuntu 24.04 has for arm64: the one its images boot (6.8) and each
+# HWE kernel since. modules.yml builds against the newest only, and the kernel calls fki uses changed between them.
+name: modules on Ubuntu 24.04's kernels
+on:
+ push:
+ pull_request:
+jobs:
+ build:
+ runs-on: ubuntu-24.04-arm
+ steps:
+ - uses: actions/checkout@v4
+ - name: The newest headers of each series
+ run: |
+ sudo apt-get update -qq
+ apt-cache search --names-only '^linux-headers-[0-9.]+-[0-9]+-generic$' | awk '{print $1}' | sort -V > all
+ sed -E 's/^linux-headers-([0-9]+\.[0-9]+)\..*/\1/' all | sort -uV > series
+ for s in $(cat series); do grep -E "^linux-headers-${s/./\\.}\.[0-9]+-" all | tail -1; done > pkgs
+ echo "series: $(tr '\n' ' ' < series)"; cat pkgs
+ [ "$(wc -l < pkgs)" -ge 2 ] # 6.8 and at least one HWE kernel: fewer means the list is not what this job is for
+ sudo apt-get install -y -qq $(cat pkgs) >/dev/null
+ - name: fki.ko and xnu.ko against each
+ run: |
+ bad=""
+ for p in $(cat pkgs); do
+ v=${p#linux-headers-}; k=/usr/src/$p; b=$RUNNER_TEMP/$v; mkdir -p "$b"; cp -r fki-ko xnu-ko xnu-patches "$b/"
+ echo "::group::$v"
+ if make -C "$k" M="$b/fki-ko" modules &&
+ make -C "$k" M="$b/xnu-ko" KBUILD_EXTRA_SYMBOLS="$b/fki-ko/Module.symvers" modules &&
+ [ -e "$b/fki-ko/fki.ko" ] && [ -e "$b/xnu-ko/xnu.ko" ]; then r=built; else r=FAILED; bad="$bad $v"; fi
+ echo "::endgroup::"
+ echo "$v: $r"
+ done
+ [ -z "$bad" ] || { echo "did not build against:$bad"; exit 1; }
diff --git a/fki-ko/fki_arm64.c b/fki-ko/fki_arm64.c
index 5bc3722..c5bb994 100644
--- a/fki-ko/fki_arm64.c
+++ b/fki-ko/fki_arm64.c
@@ -22,6 +22,7 @@
#include <asm/barrier.h>
#include <asm/cpufeature.h>
#include <asm/neon.h>
+#include <asm/simd.h>
#include <asm/stacktrace.h>
#include <asm/sysreg.h>
#include <asm/tlbflush.h>
@@ -147,10 +148,15 @@ static __always_inline void keys_write(const struct fki_pac_keys *k)
void fki_fpsimd_forget(void)
{
+#ifdef scoped_ksimd /* 6.19 on: kernel_neon_begin() takes the caller's buffer (the change that brought scoped_ksimd()) */
struct user_fpsimd_state scratch; /* where Linux would save a kernel-mode state over a context switch: none here */
kernel_neon_begin(&scratch);
kernel_neon_end(&scratch);
+#else
+ kernel_neon_begin();
+ kernel_neon_end();
+#endif
}
__attribute__((target("branch-protection=none"))) unsigned long fki_enter(const struct fki_pac_keys *foreign, struct fki_pac_keys *saved)
@@ -334,7 +340,8 @@ static int fki_carve_check(unsigned long base, unsigned long len)
pr_err("fki: carve-out [%#lx, %#lx) overflows physical address space\n", base, end);
return -EINVAL;
}
- if (p_efi_mem_type && p_efi_mem_type(base) >= 0) {
+ /* (-ENOTSUPP: there is no firmware map to ask. An address the map does not have is no memory at all.) */
+ if (p_efi_mem_type && p_efi_mem_type(base) != -ENOTSUPP) {
unsigned long a;
for (a = base; a < end; a += SZ_2M) {
diff --git a/fki-ko/fki_common.c b/fki-ko/fki_common.c
index 3598b19..625ba49 100644
--- a/fki-ko/fki_common.c
+++ b/fki-ko/fki_common.c
@@ -302,6 +302,7 @@ static struct sk_buff_head fki_net_rxq; /* Linux -> foreign */
static netdev_tx_t fki_net_xmit(struct sk_buff *skb, struct net_device *dev)
{
+ int first = fki_cpu_map(0); /* the foreign kernel's first CPU: Linux's CPU 0, or the first of cpu_list */
struct task_struct *t;
if (skb_queue_len(&fki_net_rxq) >= FKI_NET_QLEN) {
@@ -312,7 +313,7 @@ static netdev_tx_t fki_net_xmit(struct sk_buff *skb, struct net_device *dev)
dev->stats.tx_packets++;
dev->stats.tx_bytes += skb->len;
skb_queue_tail(&fki_net_rxq, skb);
- t = READ_ONCE(fki_idle_task[0]);
+ t = first >= 0 && first < nr_cpu_ids ? READ_ONCE(fki_idle_task[first]) : NULL;
if (t)
wake_up_process(t); /* the foreign kernel's first CPU is idle: let it see the frame now */
return NETDEV_TX_OK;
@@ -426,8 +427,8 @@ long fki_file_rw(void *file, int write, void *buf, unsigned long len, fki_u64 of
{
struct fki_file_args a = { file, write, buf, len, off, -EIO };
- if (!file)
- return -EBADF;
+ if (!file || (write && !(((struct file *)file)->f_mode & FMODE_WRITE)))
+ return -EBADF; /* (a file opened to read: kernel_write() says so with a WARN) */
fki_linux_runs(fki_file_rw_thunk, &a);
return a.ret;
}
@@ -481,7 +482,7 @@ long fki_file_pwrite(void *file, const void *buf, unsigned long len, fki_u64 off
{
loff_t pos = off;
- if (!file)
+ if (!file || !(((struct file *)file)->f_mode & FMODE_WRITE))
return -EBADF;
return kernel_write(file, buf, len, &pos);
}
diff --git a/fki-ko/fki_hostcall.c b/fki-ko/fki_hostcall.c
index ee9e4d2..301a6e0 100644
--- a/fki-ko/fki_hostcall.c
+++ b/fki-ko/fki_hostcall.c
@@ -22,10 +22,11 @@
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/uaccess.h>
+#include <linux/version.h>
#include <linux/vmalloc.h>
#include <linux/wait.h>
-#define HC_MAX (8UL << 20) /* largest request or reply */
+#define HC_MAX ((8UL << 20) + 4096) /* largest request or reply: the DRM bridge's 8 MiB of payload and its header */
#define HC_TIMEOUT (120 * HZ) /* a service that does not answer: the call fails */
struct xnu_hostcall_xlate {
@@ -53,6 +54,7 @@ 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;
static int hc_open; /* the service's opens of /dev/xnu-hostcall (0: no service, calls fail at once) */
+static int hc_copying; /* a read() or write() is copying out of or into hc_buf: the call does not end under it */
struct hc_call { const void *req; unsigned long len; void *reply; unsigned long max; long result; };
static DEFINE_MUTEX(hc_mutex); /* one call at a time through the single slot (several CPUs may call) */
@@ -89,6 +91,11 @@ static void hc_call_body(void *p)
/* until the reply, or the service closing its device with the call unanswered */
wait_event_timeout(hc_done_wait, READ_ONCE(hc_state) == 3 || !READ_ONCE(hc_open), HC_TIMEOUT);
spin_lock(&hc_lock);
+ while (hc_copying) { /* the next call would fill hc_buf under the service's copy, or its late reply would land on it */
+ spin_unlock(&hc_lock);
+ wait_event(hc_done_wait, !READ_ONCE(hc_copying));
+ spin_lock(&hc_lock);
+ }
if (hc_state != 3) {
r = hc_open ? -ETIMEDOUT : -ENODEV;
hc_state = 0; hc_seq = 0;
@@ -130,6 +137,7 @@ 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)
{
+ unsigned long len;
u64 seq;
int err;
@@ -137,42 +145,79 @@ static ssize_t hc_read(struct file *f, char __user *buf, size_t n, loff_t *off)
if (err)
return err;
spin_lock(&hc_lock);
- if (hc_state != 1) {
+ if (hc_state != 1 || n < 8 + hc_len) {
+ err = hc_state != 1 ? -EAGAIN : -EMSGSIZE; /* too small a buffer: the request stays, for a read() with room */
spin_unlock(&hc_lock);
- return -EAGAIN;
+ return err;
}
hc_state = 2;
seq = hc_seq;
+ len = hc_len;
+ hc_copying = 1;
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;
+ if (copy_to_user(buf, &seq, 8) || copy_to_user(buf + 8, hc_buf, len))
+ err = -EFAULT;
+ spin_lock(&hc_lock);
+ hc_copying = 0;
+ if (err)
+ hc_state = 1; /* not delivered: the next read() gets it */
+ spin_unlock(&hc_lock);
+ wake_up(&hc_done_wait);
+ if (err)
+ wake_up_interruptible(&hc_req_wait);
+ return err ? err : 8 + 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;
+ int err = 0;
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) {
+ if (hc_state != 2 || seq != hc_seq || hc_copying) {
spin_unlock(&hc_lock);
return -ESTALE; /* the call timed out meanwhile */
}
+ hc_copying = 1;
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);
+ err = -EFAULT; /* no reply yet: the service may write it again */
+ spin_lock(&hc_lock);
+ hc_copying = 0;
+ if (!err) {
+ hc_len = n - 8;
+ hc_result = 0;
+ hc_state = 3;
+ }
+ spin_unlock(&hc_lock);
wake_up(&hc_done_wait);
- return n;
+ return err ? err : n;
+}
+
+/*
+ * The page frame behind va in a device mapping (VM_IO, VM_PFNMAP), with mmap_lock held. The kernel's call for it changed
+ * within the kernels of one Ubuntu release (24.04: 6.8, then 6.11, 6.14, 6.17 and 7.0 as HWE kernels): follow_pfn() up
+ * to 6.11, follow_pfnmap_start() from 6.12 (6.14 has no follow_pfn() any more).
+ */
+static int hc_device_pfn(struct vm_area_struct *vma, unsigned long va, unsigned long *pfn)
+{
+#if LINUX_VERSION_CODE >= KERNEL_VERSION(6, 12, 0)
+ struct follow_pfnmap_args args = { .vma = vma, .address = va };
+ int err = follow_pfnmap_start(&args);
+
+ if (err)
+ return err;
+ *pfn = args.pfn;
+ follow_pfnmap_end(&args);
+ return 0;
+#else
+ return follow_pfn(vma, va, pfn);
+#endif
}
static long hc_xlate_one(struct mm_struct *mm, unsigned long va, u64 *pa)
@@ -183,12 +228,12 @@ static long hc_xlate_one(struct mm_struct *mm, unsigned long va, u64 *pa)
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);
+ unsigned long pfn;
+ int err = hc_device_pfn(vma, va, &pfn);
+
if (err)
return err;
- *pa = (u64)args.pfn << PAGE_SHIFT;
- follow_pfnmap_end(&args);
+ *pa = (u64)pfn << PAGE_SHIFT;
return 0;
}
if (get_user_pages_remote(mm, va, 1, FOLL_WRITE, &pg, NULL) != 1)
@@ -202,7 +247,8 @@ 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;
+ unsigned long i, k, n;
+ u64 pa[64];
long err = 0;
if (copy_from_user(&a, ua, sizeof(a)))
@@ -212,14 +258,18 @@ static long hc_xlate(struct xnu_hostcall_xlate __user *ua)
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))
+ /*
+ * The answers leave with mmap_lock released: writing one may fault (an output array not in memory yet), the fault
+ * takes mmap_lock again, and behind another thread that waits to write-lock it (an mmap()) that never returns.
+ */
+ for (i = 0; i < n && !err; i += k) {
+ mmap_read_lock(mm);
+ for (k = 0; k < ARRAY_SIZE(pa) && i + k < n && !err; k++)
+ err = hc_xlate_one(mm, a.va + ((i + k) << PAGE_SHIFT), &pa[k]);
+ mmap_read_unlock(mm);
+ if (!err && copy_to_user((u64 __user *)a.out + i, pa, k * sizeof(*pa)))
err = -EFAULT;
}
- mmap_read_unlock(mm);
return err;
}
diff --git a/fki-ko/test/hostcall/Makefile b/fki-ko/test/hostcall/Makefile
new file mode 100644
index 0000000..44d2870
--- /dev/null
+++ b/fki-ko/test/hostcall/Makefile
@@ -0,0 +1,4 @@
+# SPDX-License-Identifier: GPL-2.0-only
+# Built by run.sh (the module against the running kernel and ../../fki.h; hcserve with the host's compiler).
+obj-m += hctest.o
+ccflags-y += -I$(src)/fki-ko
diff --git a/fki-ko/test/hostcall/hcserve.c b/fki-ko/test/hostcall/hcserve.c
new file mode 100644
index 0000000..509d28e
--- /dev/null
+++ b/fki-ko/test/hostcall/hcserve.c
@@ -0,0 +1,126 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * A service on /dev/xnu-hostcall for the tests (run.sh): what gpu/xnu-drm/xnudrmd is to the hosted kernel, with one way
+ * of going wrong per mode. Its reply to a request is the request's first 8 bytes (the caller's tag) and the rest with
+ * every byte inverted, so the caller (hctest.c) can tell the reply to its own request from any other.
+ * echo read, reply
+ * smallbuf the first read() of a request has a buffer too small for it; then as echo
+ * readfault the first read() of a request faults in the middle of the buffer; then as echo
+ * writefault the first write() of a reply faults in the middle of the reply; then the reply again, whole
+ * close read one request and exit without a reply
+ * bigreply LEN answer with LEN bytes whatever the request
+ * noreply SECS read one request, write its reply SECS later (the call has timed out: -ESTALE), then as echo
+ * slowwrite SECS the first reply's bytes are in memory that is not there until SECS have passed (userfaultfd): the
+ * write() is inside the kernel all that time; then as echo
+ * Prints "ready" once the device is open, then one line per system call that matters.
+ */
+#define _GNU_SOURCE
+#include <errno.h>
+#include <fcntl.h>
+#include <linux/userfaultfd.h>
+#include <pthread.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/ioctl.h>
+#include <sys/mman.h>
+#include <sys/syscall.h>
+#include <unistd.h>
+
+#define MAX ((8u << 20) + 4096) /* more than any request: sizeof(struct xnudrm_hdr) + XNUDRM_MAX_MSG is the bridge's */
+
+static int hc, uffd;
+static unsigned secs;
+static uint8_t *two; /* two pages; the second is taken away or not there yet, as the mode wants */
+static uint8_t later[4096]; /* slowwrite: what the second page will hold */
+
+static void say(const char *what, ssize_t r)
+{
+ if (r < 0) printf("%s = -1 (%s)\n", what, strerror(errno)); else printf("%s = %zd\n", what, r);
+ fflush(stdout);
+}
+
+static void *resolve(void *arg)
+{
+ struct uffd_msg m;
+ struct uffdio_copy c = { .dst = (uintptr_t)two + 4096, .src = (uintptr_t)later, .len = 4096 };
+
+ if (read(uffd, &m, sizeof(m)) != sizeof(m)) { perror("userfaultfd read"); exit(2); }
+ printf("slowwrite: write() is in the kernel and waits for the reply's memory; it gets it in %u s\n", secs); fflush(stdout);
+ sleep(secs);
+ if (ioctl(uffd, UFFDIO_COPY, &c)) { perror("UFFDIO_COPY"); exit(2); }
+ return arg;
+}
+
+int main(int argc, char **argv)
+{
+ const char *mode = argc > 1 ? argv[1] : "echo";
+ size_t biglen = argc > 2 ? strtoul(argv[2], NULL, 0) : 0;
+ uint8_t *msg = malloc(8 + MAX), *rep = malloc(8 + MAX);
+ int first = 1;
+
+ secs = (unsigned)biglen;
+ two = mmap(NULL, 8192, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
+ if (!msg || !rep || two == MAP_FAILED) return 2;
+ hc = open("/dev/xnu-hostcall", O_RDWR | O_CLOEXEC);
+ if (hc < 0) { perror("/dev/xnu-hostcall (is fki.ko loaded, are you root?)"); return 2; }
+ if (!strcmp(mode, "slowwrite")) {
+ struct uffdio_api api = { .api = UFFD_API };
+ struct uffdio_register reg = { .range = { (uintptr_t)two + 4096, 4096 }, .mode = UFFDIO_REGISTER_MODE_MISSING };
+ pthread_t th;
+
+ uffd = syscall(SYS_userfaultfd, O_CLOEXEC);
+ if (uffd < 0 || ioctl(uffd, UFFDIO_API, &api) || ioctl(uffd, UFFDIO_REGISTER, &reg)) { perror("userfaultfd"); return 2; }
+ if (pthread_create(&th, NULL, resolve, NULL)) return 2;
+ } else if (!strcmp(mode, "readfault") || !strcmp(mode, "writefault")) {
+ two[0] = 0;
+ if (mprotect(two + 4096, 4096, PROT_NONE)) return 2;
+ }
+ puts("ready"); fflush(stdout);
+ for (;;) {
+ ssize_t n, w;
+ size_t i, rn;
+
+ if (first && !strcmp(mode, "smallbuf")) {
+ n = read(hc, msg, 8);
+ say("read() with room for 8 bytes", n);
+ }
+ if (first && !strcmp(mode, "readfault")) {
+ n = read(hc, two + 4096 - 16, 8 + MAX);
+ say("read() into a buffer whose 17th byte is not mapped", n);
+ }
+ n = read(hc, msg, 8 + MAX);
+ if (n < 0 && errno == EINTR) continue;
+ say("read()", n);
+ if (n < 16) return 1;
+ if (first && !strcmp(mode, "close")) { puts("exit without a reply"); return 0; }
+ rn = !strcmp(mode, "bigreply") ? 8 + biglen : (size_t)n;
+ memcpy(rep, msg, 16);
+ for (i = 16; i < rn; i++) rep[i] = i < (size_t)n ? (uint8_t)~msg[i] : (uint8_t)i;
+ if (first && !strcmp(mode, "noreply")) {
+ printf("no reply for %u s\n", secs); fflush(stdout);
+ sleep(secs);
+ w = write(hc, rep, rn);
+ say("the late write()", w);
+ first = 0;
+ continue;
+ }
+ if (first && !strcmp(mode, "writefault")) {
+ memcpy(two + 4096 - 16, rep, 16);
+ w = write(hc, two + 4096 - 16, rn);
+ say("write() of a reply whose 17th byte is not mapped", w);
+ }
+ if (first && !strcmp(mode, "slowwrite")) {
+ memcpy(two + 4096 - 8, rep, 8); /* the sequence number; the reply itself is on the page to come */
+ memcpy(later, rep + 8, rn - 8);
+ w = write(hc, two + 4096 - 8, rn);
+ say("the slow write()", w);
+ first = 0;
+ continue;
+ }
+ w = write(hc, rep, rn);
+ say("write()", w);
+ first = 0;
+ }
+}
diff --git a/fki-ko/test/hostcall/hctest.c b/fki-ko/test/hostcall/hctest.c
new file mode 100644
index 0000000..9586799
--- /dev/null
+++ b/fki-ko/test/hostcall/hctest.c
@@ -0,0 +1,151 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * fki_hostcall() called the way xnu.ko calls it for the hosted kernel (LINUX64_CALL_HOSTCALL in xnu-ko/xnu_main.c):
+ * from inside fki_enter(), no preemption and no interrupts, Linux's own keys loaded again for the host code as
+ * xnu_world_upcall does. What each call returns and how long it took goes to the kernel log; hcserve.c is the service
+ * at the other end of /dev/xnu-hostcall and run.sh pairs each test here (t=) with the way the service behaves.
+ * Loading the module is the test; it never stays loaded.
+ */
+#include <linux/ktime.h>
+#include <linux/module.h>
+#include <linux/string.h>
+#include <linux/vmalloc.h>
+#include "fki.h"
+
+/* the DRM bridge's largest message: sizeof(struct xnudrm_hdr) + XNUDRM_MAX_MSG (gpu/xnu-drm/xnudrm_proto.h) */
+#define BRIDGE_MAX ((8UL << 20) + 40)
+
+static char *t = "";
+module_param(t, charp, 0);
+
+#define NO_PAC __attribute__((target("branch-protection=none")))
+static struct fki_pac_keys foreign = { .sctlr_en = ~0ULL };
+struct call { const void *req; unsigned long len; void *reply; unsigned long max; };
+
+static NO_PAC long hostcall(struct call *c)
+{
+ struct fki_pac_keys saved, mine, tmp;
+ unsigned long cookie;
+ long r;
+
+ cookie = fki_enter(&foreign, &saved);
+ fki_pac_swap(&saved, &mine); /* Linux's keys while host code runs */
+ r = fki_hostcall(c->req, c->len, c->reply, c->max);
+ fki_pac_swap(&mine, &tmp);
+ fki_leave(cookie, &saved);
+ return r;
+}
+
+static unsigned char *req, *reply;
+static int bad;
+
+/* hcserve's reply to a request: its first 8 bytes (the tag), then every byte inverted */
+static int is_reply_to(u64 tag, unsigned long len, long r)
+{
+ unsigned long i;
+
+ if (r != (long)len || memcmp(reply, &tag, 8))
+ return 0;
+ for (i = 8; i < len; i++)
+ if (reply[i] != (unsigned char)~req[i])
+ return 0;
+ return 1;
+}
+
+/* one call: len bytes with this tag, room for max bytes of reply. Returns fki_hostcall()'s result; *ms: how long it took */
+static long call(u64 tag, unsigned long len, unsigned long max, s64 *ms)
+{
+ struct call c = { req, len, reply, max };
+ unsigned long i;
+ ktime_t t0;
+ long r;
+
+ memcpy(req, &tag, 8);
+ for (i = 8; i < len; i++)
+ req[i] = (unsigned char)(tag + i * 7);
+ memset(reply, 0, 16);
+ t0 = ktime_get();
+ r = hostcall(&c);
+ *ms = ktime_ms_delta(ktime_get(), t0);
+ return r;
+}
+
+/* a call that must come back with its own reply within limit_ms */
+static void answered(const char *what, u64 tag, unsigned long len, s64 limit_ms)
+{
+ s64 ms;
+ long r = call(tag, len, BRIDGE_MAX, &ms);
+ int ok = is_reply_to(tag, len, r) && ms <= limit_ms;
+
+ pr_info("hctest: %s: %s: a request of %lu bytes: fki_hostcall() = %ld after %lld ms%s\n", ok ? "ok" : "FAIL", what, len, r, ms,
+ r < 0 ? "" : is_reply_to(tag, len, r) ? ", the reply to this request" : ", NOT the reply to this request");
+ bad |= !ok;
+}
+
+/* a call that must fail with this error, after at least min_ms and at most max_ms */
+static void fails(const char *what, u64 tag, unsigned long len, unsigned long max, long want, s64 min_ms, s64 max_ms)
+{
+ s64 ms;
+ long r = call(tag, len, max, &ms);
+ int ok = r == want && ms >= min_ms && ms <= max_ms;
+
+ pr_info("hctest: %s: %s: a request of %lu bytes: fki_hostcall() = %ld after %lld ms (to be %ld)\n", ok ? "ok" : "FAIL", what, len, r, ms, want);
+ bad |= !ok;
+}
+
+static int __init hctest_init(void)
+{
+ s64 ms;
+ long r;
+
+ req = vmalloc(BRIDGE_MAX);
+ reply = vmalloc(BRIDGE_MAX);
+ if (!req || !reply) {
+ vfree(req); vfree(reply);
+ return -ENOMEM;
+ }
+ if (!strcmp(t, "nosvc")) {
+ fails("no service has the device open", 0x1001, 64, 64, -ENODEV, 0, 1000);
+ } else if (!strcmp(t, "echo")) {
+ answered("the service answers", 0x2001, 8, 2000);
+ answered("the service answers", 0x2002, 4096, 2000);
+ answered("the service answers", 0x2003, 1UL << 20, 2000);
+ fails("a reply longer than the caller's buffer", 0x2004, 4096, 100, -EMSGSIZE, 0, 2000);
+ answered("the call after it", 0x2005, 64, 2000);
+ } else if (!strcmp(t, "one")) {
+ answered("the service's first try fails, its second is right", 0x3001, 4096, 2000);
+ answered("the call after it", 0x3002, 64, 2000);
+ } else if (!strcmp(t, "close")) {
+ fails("the service closes the device with the call unanswered", 0x4001, 64, 64, -ENODEV, 0, 2000);
+ } else if (!strcmp(t, "bigreq")) {
+ answered("the DRM bridge's largest message (8 MiB and its 40-byte header), both ways", 0x5001, BRIDGE_MAX, 5000);
+ } else if (!strcmp(t, "bigreply")) {
+ r = call(0x6001, 64, BRIDGE_MAX, &ms);
+ pr_info("hctest: %s: a reply of the DRM bridge's largest size (%lu bytes): fki_hostcall() = %ld after %lld ms\n",
+ r == BRIDGE_MAX && ms <= 5000 ? "ok" : "FAIL", BRIDGE_MAX, r, ms);
+ bad |= !(r == BRIDGE_MAX && ms <= 5000);
+ } else if (!strcmp(t, "timeout")) {
+ /* 120 s, and what the kernel's timers add to a wait that long (up to an eighth) */
+ fails("the service reads the request and does not answer", 0x7001, 64, 64, -ETIMEDOUT, 119000, 136000);
+ answered("the call after it (the service looks again 125 s after the first)", 0x7002, 64, 10000);
+ } else if (!strcmp(t, "slowwrite")) {
+ /* the service's write() of the reply to A is still inside the kernel when A's time is up */
+ r = call(0xA00A, 64, 64, &ms);
+ pr_info("hctest: %s: call A, whose reply the service is still writing after 120 s: fki_hostcall() = %ld after %lld ms%s\n",
+ r == -ETIMEDOUT || is_reply_to(0xA00A, 64, r) ? "ok" : "FAIL", r, ms,
+ r < 0 ? "" : is_reply_to(0xA00A, 64, r) ? ", the reply to A" : ", NOT the reply to A");
+ bad |= !(r == -ETIMEDOUT || is_reply_to(0xA00A, 64, r));
+ r = call(0xB00B, 64, 64, &ms);
+ pr_info("hctest: %s: call B, made next: fki_hostcall() = %ld after %lld ms%s\n", is_reply_to(0xB00B, 64, r) ? "ok" : "FAIL", r, ms,
+ r < 0 ? "" : is_reply_to(0xB00B, 64, r) ? ", the reply to B" : !memcmp(reply, (u64[]){ 0xA00A }, 8) ? ", the reply to A" : ", not the reply to B");
+ bad |= !is_reply_to(0xB00B, 64, r);
+ } else {
+ pr_info("hctest: no such test: t=%s\n", t);
+ bad = 1;
+ }
+ pr_info("hctest: %s: %s\n", t, bad ? "FAIL" : "ok");
+ vfree(req); vfree(reply);
+ return -EAGAIN;
+}
+module_init(hctest_init);
+MODULE_LICENSE("GPL");
diff --git a/fki-ko/test/hostcall/hcxlate.c b/fki-ko/test/hostcall/hcxlate.c
new file mode 100644
index 0000000..3aa8b27
--- /dev/null
+++ b/fki-ko/test/hostcall/hcxlate.c
@@ -0,0 +1,174 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * The ioctls of /dev/xnu-hostcall (fki_hostcall.c), as a service uses them for memory it shares with the hosted kernel:
+ * XNU_HOSTCALL_XLATE over many pages against the kernel's own answers (/proc/self/pagemap), the errors it states, and
+ * XNU_HOSTCALL_PIN / UNPIN. One check is about what else the process does meanwhile: XLATE writing into an output array
+ * that is not in memory yet while another thread maps and unmaps memory, which is what a service with more than one
+ * thread does (xnudrmd has the virglrenderer's threads beside it).
+ * Needs root and fki.ko loaded; no hosted system. Exit status 0: all as stated; 1: not; 2: could not run.
+ */
+#define _GNU_SOURCE
+#include <errno.h>
+#include <fcntl.h>
+#include <pthread.h>
+#include <signal.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/ioctl.h>
+#include <sys/mman.h>
+#include <sys/wait.h>
+#include <unistd.h>
+
+struct xnu_hostcall_xlate { uint64_t va, len, out, max; };
+#define XNU_HOSTCALL_XLATE _IOWR('X', 1, struct xnu_hostcall_xlate)
+struct xnu_hostcall_range { uint64_t va, len; };
+#define XNU_HOSTCALL_PIN _IOW('X', 2, struct xnu_hostcall_range)
+#define XNU_HOSTCALL_UNPIN _IOW('X', 3, struct xnu_hostcall_range)
+
+static int hc, bad;
+
+static int xlate(void *va, uint64_t len, uint64_t *out, uint64_t max)
+{
+ struct xnu_hostcall_xlate x = { (uintptr_t)va, len, (uintptr_t)out, max };
+ return ioctl(hc, XNU_HOSTCALL_XLATE, &x) ? -errno : 0;
+}
+
+static int range(unsigned long cmd, void *va, uint64_t len)
+{
+ struct xnu_hostcall_range r = { (uintptr_t)va, len };
+ return ioctl(hc, cmd, &r) ? -errno : 0;
+}
+
+static void is(const char *what, int got, int want)
+{
+ printf("%s: %s: %s", got == want ? "ok" : "FAIL", what, got ? strerror(-got) : "0");
+ if (got != want) { printf(" (to be %s)", want ? strerror(-want) : "0"); bad = 1; }
+ putchar('\n');
+}
+
+static void *anon(size_t len, int prot)
+{
+ void *p = mmap(NULL, len, prot, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
+ if (p == MAP_FAILED) { perror("mmap"); exit(2); }
+ return p;
+}
+
+/* the first mapping of /proc/self/maps with this name ([vvar]: a mapping without pages of its own, as a device's is) */
+static void *named(const char *name)
+{
+ char line[512];
+ unsigned long a = 0;
+ FILE *f = fopen("/proc/self/maps", "r");
+
+ while (f && fgets(line, sizeof(line), f))
+ if (strstr(line, name)) { sscanf(line, "%lx", &a); break; }
+ if (f) fclose(f);
+ return (void *)a;
+}
+
+static volatile int stop;
+static void *mapper(void *arg)
+{
+ while (!stop) {
+ void *p = mmap(NULL, 4096, PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
+ if (p != MAP_FAILED) munmap(p, 4096);
+ }
+ return arg;
+}
+
+/* In a child (a call that never returns can only be killed): rounds of XLATE into an output array that is not in memory. */
+static void while_mapping(uint8_t *mem, size_t pages)
+{
+ enum { ROUNDS = 200 };
+ int pfd[2], st, done = 0;
+ pid_t pid;
+ char c;
+
+ if (pipe(pfd)) { perror("pipe"); exit(2); }
+ pid = fork();
+ if (pid < 0) { perror("fork"); exit(2); }
+ if (!pid) {
+ uint64_t *out = anon(pages * 8, PROT_READ | PROT_WRITE);
+ pthread_t th;
+ int i;
+
+ close(pfd[0]);
+ if (pthread_create(&th, NULL, mapper, NULL)) _exit(2);
+ for (i = 0; i < ROUNDS; i++) {
+ madvise(out, pages * 8, MADV_DONTNEED); /* not in memory: the kernel's write faults it in */
+ if (xlate(mem, pages * 4096, out, pages)) _exit(3);
+ if (write(pfd[1], "", 1) != 1) _exit(2);
+ }
+ _exit(0);
+ }
+ close(pfd[1]);
+ alarm(20); /* a round takes milliseconds; SIGALRM ends the read below */
+ while (read(pfd[0], &c, 1) == 1) done++;
+ alarm(0);
+ if (done < ROUNDS) kill(pid, SIGKILL);
+ waitpid(pid, &st, 0);
+ if (done == ROUNDS && WIFEXITED(st) && !WEXITSTATUS(st)) {
+ printf("ok: XLATE into an output array not in memory, another thread mapping and unmapping: %d calls returned\n", done);
+ } else if (WIFSIGNALED(st)) {
+ printf("FAIL: XLATE into an output array not in memory, another thread mapping and unmapping: call %d and the other thread's mmap() did not return in 20 s (the process had to be killed)\n", done + 1);
+ bad = 1;
+ } else {
+ printf("FAIL: XLATE into an output array not in memory: call %d failed\n", done + 1);
+ bad = 1;
+ }
+}
+
+static void on_alarm(int sig) { (void)sig; }
+
+int main(void)
+{
+ enum { PAGES = 4096 }; /* 16 MiB: an output array of 8 pages */
+ struct sigaction sa = { .sa_handler = on_alarm };
+ uint64_t *out, e;
+ uint8_t *mem, *vvar;
+ size_t i, wrong = 0;
+ int pm;
+
+ sigaction(SIGALRM, &sa, NULL); /* no SA_RESTART: the alarm ends a read() */
+ hc = open("/dev/xnu-hostcall", O_RDWR | O_CLOEXEC);
+ if (hc < 0) { perror("/dev/xnu-hostcall (is fki.ko loaded, are you root?)"); return 2; }
+ pm = open("/proc/self/pagemap", O_RDONLY);
+ if (pm < 0) { perror("/proc/self/pagemap"); return 2; }
+ mem = anon(PAGES * 4096, PROT_READ | PROT_WRITE);
+ out = anon(PAGES * 8, PROT_READ | PROT_WRITE);
+ if (mlock(mem, PAGES * 4096)) { perror("mlock"); return 2; } /* in memory, and not moved while we compare */
+
+ is("XLATE of 4096 pages", xlate(mem, PAGES * 4096, out, PAGES), 0);
+ for (i = 0; i < PAGES; i++) {
+ if (pread(pm, &e, 8, ((uintptr_t)mem + i * 4096) / 4096 * 8) != 8 || !(e >> 63)) { fprintf(stderr, "pagemap has no entry for page %zu\n", i); return 2; }
+ if (out[i] != (e & ((1ULL << 55) - 1)) * 4096) wrong++;
+ }
+ printf("%s: its answers against /proc/self/pagemap: %zu of %d differ\n", wrong ? "FAIL" : "ok", wrong, PAGES);
+ if (wrong) bad = 1;
+
+ is("XLATE of an address that is not page aligned", xlate(mem + 8, 4096, out, 1), -EINVAL);
+ is("XLATE of a length that is not whole pages", xlate(mem, 100, out, 1), -EINVAL);
+ is("XLATE of 2 pages with room for 1 answer", xlate(mem, 8192, out, 1), -E2BIG);
+ munmap(mem + 4096, 4096);
+ is("XLATE of 3 pages, the second not mapped", xlate(mem, 3 * 4096, out, 3), -EFAULT);
+ is("XLATE with no output array", xlate(mem, 4096, NULL, 1), -EFAULT);
+
+ is("PIN of 16 pages", range(XNU_HOSTCALL_PIN, mem + 8192, 16 * 4096), 0);
+ is("UNPIN of them", range(XNU_HOSTCALL_UNPIN, mem + 8192, 0), 0);
+ is("UNPIN again", range(XNU_HOSTCALL_UNPIN, mem + 8192, 0), -ENOENT);
+ is("PIN of no pages", range(XNU_HOSTCALL_PIN, mem + 8192, 0), -EINVAL);
+ is("PIN of an address that is not page aligned", range(XNU_HOSTCALL_PIN, mem + 8192 + 8, 4096), -EINVAL);
+ is("PIN of a range with a page not mapped", range(XNU_HOSTCALL_PIN, mem, 3 * 4096), -EFAULT);
+ vvar = named("[vvar");
+ if (vvar)
+ is("PIN of a mapping without pages of its own ([vvar])", range(XNU_HOSTCALL_PIN, vvar, 4096), -EOPNOTSUPP);
+ else
+ puts("skipped: PIN of a mapping without pages of its own (this process has no [vvar])");
+ is("PIN of 4 pages, left to the close", range(XNU_HOSTCALL_PIN, mem + 8192, 4 * 4096), 0);
+
+ while_mapping(mem + 8192, PAGES - 2);
+ close(hc);
+ return bad;
+}
diff --git a/fki-ko/test/hostcall/run.sh b/fki-ko/test/hostcall/run.sh
new file mode 100755
index 0000000..57598de
--- /dev/null
+++ b/fki-ko/test/hostcall/run.sh
@@ -0,0 +1,68 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0-only
+# fki's host-call device on a real kernel: a small module (hctest.c) makes host calls the way xnu.ko makes them for the
+# hosted kernel, a small service (hcserve.c) answers them on /dev/xnu-hostcall the way xnudrmd does, and goes wrong in one
+# way per test; hcxlate.c checks the device's ioctls. What every call returned, and after how long, is printed.
+# On an arm64 Linux host of the project: root (sudo), fki.ko loaded and built in ../.. (its Module.symvers), the
+# kernel's headers, cc. No hosted system is needed, and one must not be running, nor xnudrmd (one service at a time).
+# run.sh the tests that take seconds
+# run.sh --slow also the two that wait for the 120 s a call may take (about 4.5 minutes)
+# run.sh NAME... only these (the names are in the list below)
+# Exit status 0: every call ended as it should; 1: not; 2: could not run.
+set -u
+D=$(cd "$(dirname "$0")" && pwd); P=$(cd "$D/../../.." && pwd); K=${KDIR:-/lib/modules/$(uname -r)/build}
+S=sudo; [ "$(id -u)" = 0 ] && S=
+[ -d /sys/module/fki ] || { echo "fki.ko is not loaded (sudo insmod fki-ko/fki.ko)" >&2; exit 2; }
+[ ! -d /sys/module/xnu ] || { echo "a hosted system is running: not beside it" >&2; exit 2; }
+[ -f "$P/fki-ko/Module.symvers" ] || { echo "no fki-ko/Module.symvers: build fki-ko first (make -C $K M=$P/fki-ko modules)" >&2; exit 2; }
+if $S fuser -s /dev/xnu-hostcall 2>/dev/null; then echo "/dev/xnu-hostcall is open (xnudrmd?): stop its service first" >&2; exit 2; fi
+
+# test: the service's mode and argument (- for no service), the module's test
+quick="nosvc:-::nosvc echo:echo::echo smallbuf:smallbuf::one readfault:readfault::one writefault:writefault::one close:close::close
+bigreq:echo::bigreq bigreply:bigreply:$(( (8 << 20) + 40 )):bigreply xlate"
+slow="timeout:noreply:125:timeout slowwrite:slowwrite:125:slowwrite"
+want=; all="$quick"
+for a; do case "$a" in --slow) all="$quick $slow";; *) want="$want $a";; esac; done
+[ -z "$want" ] || all=$(for w in $want; do for e in $quick $slow; do [ "${e%%:*}" = "$w" ] && echo "$e"; done; done)
+[ -n "$all" ] || { echo "no such test (the names: $(for e in $quick $slow; do printf '%s ' "${e%%:*}"; done))" >&2; exit 2; }
+
+W=$(mktemp -d) || exit 2
+svc=
+cleanup() { [ -z "$svc" ] || $S kill "$svc" 2>/dev/null; rm -rf "$W"; }
+trap cleanup EXIT
+cp "$D/hctest.c" "$D/Makefile" "$W/"; mkdir "$W/fki-ko"; cp "$P/fki-ko/fki.h" "$W/fki-ko/"
+log=$(make -s -C "$K" M="$W" KBUILD_EXTRA_SYMBOLS="$P/fki-ko/Module.symvers" modules 2>&1) && [ -e "$W/hctest.ko" ] ||
+ { echo "$log" | grep -iE "error|\*\*\*" | head -10 >&2; echo "the test module did not build" >&2; exit 2; }
+cc -O2 -Wall -o "$W/hcserve" "$D/hcserve.c" -lpthread && cc -O2 -Wall -o "$W/hcxlate" "$D/hcxlate.c" -lpthread ||
+ { echo "the service did not build" >&2; exit 2; }
+
+status=0
+for e in $all; do
+ IFS=: read -r name mode arg t <<EOF
+$e
+EOF
+ echo "== $name"
+ if [ "$name" = xlate ]; then
+ $S "$W/hcxlate"; r=$?
+ [ $r = 0 ] || { [ $r = 1 ] || { echo "hcxlate could not run" >&2; exit 2; }; status=1; }
+ continue
+ fi
+ svc=
+ if [ "$mode" != - ]; then
+ $S "$W/hcserve" "$mode" $arg > "$W/svc.out" 2>&1 &
+ svc=$!
+ for _ in $(seq 1 50); do grep -q '^ready$' "$W/svc.out" 2>/dev/null && break; sleep 0.1; done
+ grep -q '^ready$' "$W/svc.out" || { cat "$W/svc.out" >&2; echo "the service did not start" >&2; exit 2; }
+ fi
+ mark="hctest: run $$ $name"
+ echo "$mark" | $S tee /dev/kmsg > /dev/null
+ $S insmod "$W/hctest.ko" t="$t" 2>/dev/null # (its init reports and returns an error: it never stays loaded)
+ [ -z "$svc" ] || { sleep 0.3; $S pkill -P "$svc" 2>/dev/null; $S kill "$svc" 2>/dev/null; wait "$svc" 2>/dev/null; svc=; }
+ [ "$mode" = - ] || grep -v '^ready$' "$W/svc.out" | sed 's/^/ service: /'
+ out=$($S dmesg | awk -v m="$mark" 'f && /hctest: / { sub(/^\[[^]]*\] */, ""); print } index($0, m) { f = 1 }')
+ [ -n "$out" ] || { echo "the test module did not run (the kernel log has no line of it)" >&2; exit 2; }
+ echo "$out" | sed 's/^hctest: / /'
+ echo "$out" | grep -q "^hctest: $t: ok\$" || status=1
+done
+[ $status = 0 ] && echo "all as it should be" || echo "NOT all as it should be"
+exit $status
diff --git a/fki-ko/test/iface/Makefile b/fki-ko/test/iface/Makefile
new file mode 100644
index 0000000..c623f85
--- /dev/null
+++ b/fki-ko/test/iface/Makefile
@@ -0,0 +1,5 @@
+# SPDX-License-Identifier: GPL-2.0-only
+# Built by run.sh (the module against the running kernel and ../../fki.h; the helpers with the host's compiler).
+obj-m += ifacetest.o
+ifacetest-y := main.o asm.o
+ccflags-y += -I$(src)/fki-ko
diff --git a/fki-ko/test/iface/asm.S b/fki-ko/test/iface/asm.S
new file mode 100644
index 0000000..5ade3b5
--- /dev/null
+++ b/fki-ko/test/iface/asm.S
@@ -0,0 +1,62 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+/* What the foreign side of ifacetest (main.c) does that C cannot say: run on its own stack, use the FP/SIMD registers,
+ * fault at a known pc. */
+ .text
+
+/* long ifacetest_on_stack(long (*fn)(void *), void *arg, void *top): fn(arg) on the stack that ends at top */
+ .globl ifacetest_on_stack
+ .type ifacetest_on_stack, %function
+ifacetest_on_stack:
+ hint #34
+ stp x29, x30, [sp, #-16]!
+ mov x29, sp
+ mov x9, sp
+ mov sp, x2
+ stp x9, xzr, [sp, #-16]!
+ mov x9, x0
+ mov x0, x1
+ blr x9
+ ldp x9, xzr, [sp], #16
+ mov sp, x9
+ ldp x29, x30, [sp], #16
+ ret
+ .size ifacetest_on_stack, . - ifacetest_on_stack
+
+/* void ifacetest_simd(unsigned char b): every FP/SIMD register full of b, FPSR and FPCR cleared */
+ .globl ifacetest_simd
+ .type ifacetest_simd, %function
+ifacetest_simd:
+ hint #34
+ .irp n,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31
+ dup v\n\().16b, w0
+ .endr
+ msr fpsr, xzr
+ msr fpcr, xzr
+ ret
+ .size ifacetest_simd, . - ifacetest_simd
+
+/* unsigned long ifacetest_peek(unsigned long addr): loads from addr; when that faults, what the fault's handler left in x1 */
+ .globl ifacetest_peek
+ .type ifacetest_peek, %function
+ifacetest_peek:
+ hint #34
+ mov x1, #0
+ .globl ifacetest_peek_insn
+ifacetest_peek_insn:
+ ldr x1, [x0]
+ mov x0, x1
+ ret
+ .size ifacetest_peek, . - ifacetest_peek
+
+/* unsigned long ifacetest_undef(void): an undefined instruction; what its handler left in x1 */
+ .globl ifacetest_undef
+ .type ifacetest_undef, %function
+ifacetest_undef:
+ hint #34
+ mov x1, #0
+ .globl ifacetest_undef_insn
+ifacetest_undef_insn:
+ .inst 0x00000000
+ mov x0, x1
+ ret
+ .size ifacetest_undef, . - ifacetest_undef
diff --git a/fki-ko/test/iface/fpload.c b/fki-ko/test/iface/fpload.c
new file mode 100644
index 0000000..11dd22e
--- /dev/null
+++ b/fki-ko/test/iface/fpload.c
@@ -0,0 +1,54 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * fki_enter() gives the CPU's FP/SIMD registers to the foreign kernel, "the current task's state saved first" (fki.h).
+ * This is the current task: it loads ifacetest.ko (t=fp, whose init writes every FP/SIMD register inside fki_enter())
+ * with all 32 registers, FPSR and FPCR holding known values, and looks at them when the system call is back.
+ * fpload ifacetest.ko exit status 0: all as they were; 1: not; 2: could not run
+ */
+#define _GNU_SOURCE
+#include <errno.h>
+#include <fcntl.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <string.h>
+#include <sys/syscall.h>
+#include <unistd.h>
+
+static uint8_t in[32][16], out[32][16];
+
+int main(int argc, char **argv)
+{
+ int fd = open(argc > 1 ? argv[1] : "ifacetest.ko", O_RDONLY | O_CLOEXEC), i, j, changed = 0;
+ uint64_t fpsr = 0x1f, fpcr = 0xc00000, fpsr2 = 0, fpcr2 = 0; /* every cumulative flag; round towards zero */
+ register long x0 __asm__("x0") = fd;
+ register const char *x1 __asm__("x1") = "t=fp";
+ register long x2 __asm__("x2") = 0;
+ register long x8 __asm__("x8") = SYS_finit_module;
+
+ if (fd < 0) { perror(argc > 1 ? argv[1] : "ifacetest.ko"); return 2; }
+ for (i = 0; i < 32; i++) memset(in[i], 0x40 + i, 16);
+ __asm__ volatile(
+ "msr fpsr, %[fpsr]\n msr fpcr, %[fpcr]\n"
+ "ldp q0, q1, [%[in], #0]\n ldp q2, q3, [%[in], #32]\n ldp q4, q5, [%[in], #64]\n ldp q6, q7, [%[in], #96]\n"
+ "ldp q8, q9, [%[in], #128]\n ldp q10, q11, [%[in], #160]\n ldp q12, q13, [%[in], #192]\n ldp q14, q15, [%[in], #224]\n"
+ "ldp q16, q17, [%[in], #256]\n ldp q18, q19, [%[in], #288]\n ldp q20, q21, [%[in], #320]\n ldp q22, q23, [%[in], #352]\n"
+ "ldp q24, q25, [%[in], #384]\n ldp q26, q27, [%[in], #416]\n ldp q28, q29, [%[in], #448]\n ldp q30, q31, [%[in], #480]\n"
+ "svc #0\n"
+ "stp q0, q1, [%[out], #0]\n stp q2, q3, [%[out], #32]\n stp q4, q5, [%[out], #64]\n stp q6, q7, [%[out], #96]\n"
+ "stp q8, q9, [%[out], #128]\n stp q10, q11, [%[out], #160]\n stp q12, q13, [%[out], #192]\n stp q14, q15, [%[out], #224]\n"
+ "stp q16, q17, [%[out], #256]\n stp q18, q19, [%[out], #288]\n stp q20, q21, [%[out], #320]\n stp q22, q23, [%[out], #352]\n"
+ "stp q24, q25, [%[out], #384]\n stp q26, q27, [%[out], #416]\n stp q28, q29, [%[out], #448]\n stp q30, q31, [%[out], #480]\n"
+ "mrs %[fpsr2], fpsr\n mrs %[fpcr2], fpcr\n msr fpcr, xzr\n"
+ : "+r"(x0), [fpsr2] "=&r"(fpsr2), [fpcr2] "=&r"(fpcr2)
+ : "r"(x1), "r"(x2), "r"(x8), [in] "r"(in), [out] "r"(out), [fpsr] "r"(fpsr), [fpcr] "r"(fpcr)
+ : "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16",
+ "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31");
+ if (x0 != -EAGAIN) { fprintf(stderr, "finit_module: %s (the module's init answers EAGAIN when it ran)\n", strerror((int)-x0)); return 2; }
+ for (i = 0; i < 32; i++) {
+ for (j = 0; j < 16 && out[i][j] == 0x40 + i; j++) ;
+ if (j < 16) changed++;
+ }
+ printf("%s: this process's registers after the foreign kernel used the CPU's: %d of 32 FP/SIMD registers changed (v0 = %02x..., v31 = %02x...; set to 40, 5f), FPSR %#llx (set to 0x1f), FPCR %#llx (set to 0xc00000)\n",
+ changed || fpsr2 != fpsr || fpcr2 != fpcr ? "FAIL" : "ok", changed, out[0][0], out[31][0], (unsigned long long)fpsr2, (unsigned long long)fpcr2);
+ return changed || fpsr2 != fpsr || fpcr2 != fpcr;
+}
diff --git a/fki-ko/test/iface/main.c b/fki-ko/test/iface/main.c
new file mode 100644
index 0000000..0e9c517
--- /dev/null
+++ b/fki-ko/test/iface/main.c
@@ -0,0 +1,876 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * What fki exports and xnu.ko relies on, called on a real kernel the way xnu.ko calls it and held against what fki.h
+ * says of each call, and against the kernel's own answer where it has one. One group of calls per load (t=); every
+ * check is one line in the kernel log, "ok" or "FAIL". run.sh loads fki.ko with the parameters a group needs, makes
+ * the file, the firmware blob and the frames a group uses, and reads the verdict. Loading the module is the test; it
+ * never stays loaded.
+ */
+#include <linux/delay.h>
+#include <linux/etherdevice.h>
+#include <linux/fs.h>
+#include <linux/ktime.h>
+#include <linux/math64.h>
+#include <linux/mm.h>
+#include <linux/module.h>
+#include <linux/netdevice.h>
+#include <linux/skbuff.h>
+#include <linux/string.h>
+#include <linux/vmalloc.h>
+#include <asm/cpufeature.h>
+#include <asm/cputype.h>
+#include <asm/esr.h>
+#include <asm/ptrace.h>
+#include <asm/sysreg.h>
+#include "fki.h"
+
+static char *t = "", *path = "", *dev = "", *blob = "";
+static unsigned long n, devn, pending, send, resv, rounds = 20000;
+static long want;
+static int cpus[NR_CPUS], cpus_n; /* fki's cpu_list, when it was loaded with one */
+module_param(t, charp, 0);
+module_param(path, charp, 0);
+module_param(dev, charp, 0);
+module_param(blob, charp, 0);
+module_param(n, ulong, 0);
+module_param(devn, ulong, 0);
+module_param(pending, ulong, 0);
+module_param(send, ulong, 0);
+module_param(resv, ulong, 0);
+module_param(rounds, ulong, 0);
+module_param(want, long, 0);
+module_param_array(cpus, int, &cpus_n, 0);
+
+static int bad;
+#define CHECK(cond, fmt, ...) do { \
+ int ok_ = !!(cond); \
+ pr_info("ifacetest: %s: " fmt "\n", ok_ ? "ok" : "FAIL", ##__VA_ARGS__); \
+ bad |= !ok_; \
+} while (0)
+
+long ifacetest_on_stack(long (*fn)(void *), void *arg, void *top);
+void ifacetest_simd(unsigned char b);
+unsigned long ifacetest_peek(unsigned long addr);
+unsigned long ifacetest_undef(void);
+extern char ifacetest_peek_insn[], ifacetest_undef_insn[];
+
+/*
+ * fn(arg) as host code inside a foreign context, the way xnu.ko runs what XNU asks of it: fki_enter() (no preemption, no
+ * interrupts, the foreign keys), then Linux's own keys again for the host code (xnu_world_upcall in xnu-ko/world.S), on
+ * a stack that is not the task's, as XNU's are not: where fki lets Linux run it has to find it a stack of Linux's.
+ */
+#define NO_PAC __attribute__((target("branch-protection=none")))
+static const struct fki_pac_keys foreign = { { 0x11, 0x12 }, { 0x21, 0x22 }, { 0x31, 0x32 }, { 0x41, 0x42 }, { 0x51, 0x52 }, ~0ULL };
+static void *stack_mem, *stack_top;
+
+static NO_PAC long in_foreign(long (*fn)(void *), void *arg, struct fki_pac_keys *seen)
+{
+ struct fki_pac_keys saved, mine, tmp;
+ unsigned long cookie;
+ long r;
+
+ cookie = fki_enter(&foreign, &saved);
+ fki_pac_swap(&saved, &mine);
+ r = ifacetest_on_stack(fn, arg, stack_top);
+ fki_pac_swap(&mine, &tmp);
+ fki_leave(cookie, &saved);
+ if (seen)
+ *seen = mine;
+ return r;
+}
+
+static int map(int c) /* the Linux CPU of the foreign kernel's CPU c */
+{
+ if (!cpus_n)
+ return c;
+ return c >= 0 && c < cpus_n ? cpus[c] : -1;
+}
+
+static int is_cpu(int c)
+{
+ return c >= 0 && c < nr_cpu_ids && cpu_online(c);
+}
+
+/* ---- entering and leaving ---- */
+
+struct inside { int irqs_off, preempt, cpu, fki_cpu, own_stack; };
+
+static long inside_fn(void *p)
+{
+ struct inside *s = p;
+
+ s->own_stack = (void *)&s >= stack_top - THREAD_SIZE && (void *)&s < stack_top;
+ s->irqs_off = irqs_disabled();
+ s->preempt = preempt_count();
+ s->cpu = smp_processor_id();
+ s->fki_cpu = fki_cpu_id();
+ return 0;
+}
+
+static void t_enter(void)
+{
+ unsigned long caps = fki_caps();
+ int pac = system_supports_address_auth(), pre = preempt_count();
+ struct fki_pac_keys seen = {};
+ struct inside s = {};
+ u64 k0[2] = {}, k1[2] = {};
+
+ CHECK(fki_version() == FKI_VERSION, "fki_version() = %d, fki.h is version %d", fki_version(), FKI_VERSION);
+ CHECK(!(caps & (FKI_CAP_EL0 | FKI_CAP_HIGH_WINDOW)) && !!(caps & FKI_CAP_PAC) == pac,
+ "fki_caps() = %#lx: a host at EL1, per-context pointer authentication keys %s (this CPU has %s)",
+ caps, caps & FKI_CAP_PAC ? "offered" : "not offered", pac ? "them" : "none");
+ if (pac) {
+ k0[0] = read_sysreg_s(SYS_APIAKEYLO_EL1);
+ k0[1] = read_sysreg_s(SYS_APIAKEYHI_EL1);
+ }
+ in_foreign(inside_fn, &s, &seen);
+ if (pac) {
+ k1[0] = read_sysreg_s(SYS_APIAKEYLO_EL1);
+ k1[1] = read_sysreg_s(SYS_APIAKEYHI_EL1);
+ }
+ CHECK(s.irqs_off && s.preempt != pre && s.own_stack, "inside fki_enter(): interrupts %s, preempt count %#x (%#x outside), on %s stack",
+ s.irqs_off ? "off" : "ON", s.preempt, pre, s.own_stack ? "the test's own" : "the TASK's");
+ CHECK(s.fki_cpu == s.cpu, "fki_cpu_id() = %d on Linux's CPU %d", s.fki_cpu, s.cpu);
+ if (pac) {
+ CHECK(!memcmp(&seen, &foreign, offsetof(struct fki_pac_keys, sctlr_en)) && seen.sctlr_en,
+ "the keys loaded inside are the foreign ones (APIA %#llx:%#llx, given %#llx:%#llx)",
+ seen.ia[1], seen.ia[0], foreign.ia[1], foreign.ia[0]);
+ CHECK(k0[0] == k1[0] && k0[1] == k1[1], "after fki_leave(): Linux's own key again");
+ }
+ CHECK(!irqs_disabled() && preempt_count() == pre, "after fki_leave(): interrupts %s, preempt count %#x",
+ irqs_disabled() ? "OFF" : "on", preempt_count());
+}
+
+/* ---- the counter and the wall clock ---- */
+
+static void t_clock(void)
+{
+ u64 f = fki_counter_frequency(), c0, c1, c, prev, sec, nsec;
+ struct timespec64 ts;
+ int i, back = 0;
+ ktime_t k0, k1;
+ s64 kns, cns;
+
+ CHECK(f, "fki_counter_frequency() = %llu Hz", f);
+ if (!f)
+ return;
+ preempt_disable(); c0 = fki_counter(); k0 = ktime_get(); preempt_enable();
+ msleep(250);
+ preempt_disable(); c1 = fki_counter(); k1 = ktime_get(); preempt_enable();
+ kns = ktime_to_ns(ktime_sub(k1, k0));
+ cns = div64_u64((c1 - c0) * NSEC_PER_SEC, f);
+ CHECK(abs(cns - kns) * 100 < kns, "%lld ns by Linux's clock are %lld ns by fki_counter() at that frequency", kns, cns);
+ for (i = 0, prev = fki_counter(); i < 100000; i++, prev = c) {
+ c = fki_counter();
+ if (c < prev)
+ back++;
+ }
+ CHECK(!back, "100000 readings of fki_counter(): %d went backwards", back);
+ fki_realtime(&sec, &nsec);
+ ktime_get_real_ts64(&ts);
+ CHECK(abs((s64)sec - ts.tv_sec) <= 1 && nsec < NSEC_PER_SEC, "fki_realtime() = %llu.%09llu, Linux's wall clock %lld.%09ld",
+ sec, nsec, (s64)ts.tv_sec, ts.tv_nsec);
+}
+
+/* ---- fki_idle_until() and fki_kick_cpu() ---- */
+
+struct idle { u64 ns, max_ns; const volatile unsigned int *wake; int past; s64 us; int atomic; };
+
+static long idle_fn(void *p)
+{
+ struct idle *i = p;
+ u64 f = fki_counter_frequency();
+ ktime_t t0 = ktime_get();
+
+ fki_idle_until(i->past ? fki_counter() - 1 : fki_counter() + div64_u64(i->ns * f, NSEC_PER_SEC), i->max_ns, i->wake);
+ i->us = ktime_us_delta(ktime_get(), t0);
+ i->atomic = irqs_disabled() && preempt_count();
+ return 0;
+}
+
+static struct kick { unsigned long go; unsigned int wake, ms; int cpu, set_wake; } kick;
+
+static int kick_fn(void *arg)
+{
+ fki_thread_wait(&kick.go);
+ if (!READ_ONCE(kick.go))
+ return 0;
+ fki_msleep(kick.ms);
+ if (kick.set_wake)
+ WRITE_ONCE(kick.wake, 1);
+ fki_kick_cpu(kick.cpu);
+ return 0;
+}
+
+/* the idle call of the foreign kernel's CPU 0 (this task) with a kick from its CPU `from` after ms */
+static s64 kicked(int from, unsigned int ms, int set_wake, const volatile unsigned int *wake)
+{
+ struct idle i = { .ns = 5 * NSEC_PER_SEC, .max_ns = 5 * NSEC_PER_SEC, .wake = wake };
+ void *th;
+
+ kick = (struct kick){ .ms = ms, .cpu = 0, .set_wake = set_wake };
+ th = fki_thread_start(kick_fn, NULL, from, "ifacetest-kick");
+ if (!th)
+ return -1;
+ WRITE_ONCE(kick.go, 1);
+ fki_thread_wake(th);
+ in_foreign(idle_fn, &i, NULL);
+ fki_thread_stop(th);
+ return i.us;
+}
+
+static struct hammer { unsigned long round; unsigned int wake; } hammer;
+
+static int hammer_fn(void *arg)
+{
+ unsigned long seen = 0, r, i;
+
+ while (!fki_thread_should_stop()) {
+ r = READ_ONCE(hammer.round);
+ if (r == seen) {
+ cond_resched();
+ continue;
+ }
+ seen = r;
+ for (i = (r * 7919) % 300; i; i--) /* the kick comes before, at and after the other CPU's going to sleep */
+ cpu_relax();
+ WRITE_ONCE(hammer.wake, 1);
+ fki_kick_cpu(0);
+ }
+ return 0;
+}
+
+struct hammered { unsigned long late; s64 worst_us; };
+
+static long hammer_idle_fn(void *p)
+{
+ struct hammered *h = p;
+ u64 f = fki_counter_frequency();
+ unsigned long r;
+
+ for (r = 1; r <= rounds; r++) {
+ ktime_t t0;
+ s64 us;
+
+ WRITE_ONCE(hammer.wake, 0);
+ t0 = ktime_get();
+ WRITE_ONCE(hammer.round, r);
+ fki_idle_until(fki_counter() + f / 2, 500 * NSEC_PER_MSEC, &hammer.wake);
+ us = ktime_us_delta(ktime_get(), t0);
+ if (us > h->worst_us)
+ h->worst_us = us;
+ if (us > 250000)
+ h->late++;
+ while (!READ_ONCE(hammer.wake)) /* (a kick that woke the call before its word was set) */
+ fki_yield();
+ }
+ return 0;
+}
+
+static void t_idle(void)
+{
+ struct idle i;
+ struct hammered h = {};
+ unsigned int one = 1;
+ int ncpu = fki_num_cpus(), from = ncpu > 1 ? 1 : 0, err;
+ void *th;
+ s64 us;
+
+ err = fki_bind_cpu(0);
+ CHECK(!err && raw_smp_processor_id() == map(0), "fki_bind_cpu(0) = %d: this task is on Linux's CPU %d (the foreign kernel's CPU 0 is %d)",
+ err, raw_smp_processor_id(), map(0));
+ if (err)
+ return;
+ i = (struct idle){ .ns = 50 * NSEC_PER_MSEC, .max_ns = NSEC_PER_SEC };
+ in_foreign(idle_fn, &i, NULL);
+ CHECK(i.us >= 49000 && i.us < 150000 && i.atomic, "fki_idle_until(a deadline in 50 ms, at most 1 s): back after %lld us, interrupts and preemption %s",
+ i.us, i.atomic ? "off again" : "NOT off again");
+ i = (struct idle){ .ns = 5 * NSEC_PER_SEC, .max_ns = 30 * NSEC_PER_MSEC };
+ in_foreign(idle_fn, &i, NULL);
+ CHECK(i.us >= 29000 && i.us < 130000, "fki_idle_until(a deadline in 5 s, at most 30 ms): back after %lld us", i.us);
+ i = (struct idle){ .past = 1, .max_ns = NSEC_PER_SEC };
+ in_foreign(idle_fn, &i, NULL);
+ CHECK(i.us < 20000 && i.atomic, "fki_idle_until(a deadline that has passed): back after %lld us", i.us);
+ i = (struct idle){ .ns = 5 * NSEC_PER_SEC, .max_ns = 5 * NSEC_PER_SEC, .wake = &one };
+ in_foreign(idle_fn, &i, NULL);
+ CHECK(i.us < 20000, "fki_idle_until(a deadline in 5 s, a wake word already set): back after %lld us", i.us);
+
+ us = kicked(from, 40, 1, &kick.wake);
+ CHECK(us >= 0 && us < 1000000, "fki_idle_until(5 s) and, 40 ms later, fki_kick_cpu(0) with the wake word set, from the foreign CPU %d: back after %lld us", from, us);
+ us = kicked(from, 40, 0, NULL);
+ CHECK(us >= 0 && us < 1000000, "the same without a wake word: back after %lld us", us);
+
+ th = fki_thread_start(hammer_fn, NULL, from, "ifacetest-kick");
+ if (th) {
+ in_foreign(hammer_idle_fn, &h, NULL);
+ fki_thread_stop(th);
+ }
+ CHECK(th && !h.late, "%lu times fki_idle_until(500 ms) with the kick (word set first) arriving around the moment it goes to sleep: %lu slept on past the kick, the longest call %lld us",
+ rounds, h.late, h.worst_us);
+}
+
+/* ---- CPUs and helper threads ---- */
+
+struct where { int cpu; u64 mpidr; unsigned long done; };
+
+static int where_fn(void *arg)
+{
+ struct where *w = arg;
+
+ w->cpu = smp_processor_id();
+ w->mpidr = read_cpuid_mpidr();
+ WRITE_ONCE(w->done, 1);
+ return 0;
+}
+
+static int until(const unsigned long *flag, int ms)
+{
+ while (!READ_ONCE(*flag) && ms-- > 0)
+ msleep(1);
+ return READ_ONCE(*flag) != 0;
+}
+
+static struct waiter { unsigned long flag, woke, stopped; } waiter;
+
+static int waiter_fn(void *arg)
+{
+ fki_thread_wait(&waiter.flag);
+ WRITE_ONCE(waiter.woke, READ_ONCE(waiter.flag) ? 1 : 2); /* 2: told to stop while it waited */
+ while (!fki_thread_should_stop())
+ fki_msleep(1);
+ WRITE_ONCE(waiter.stopped, 1);
+ return 0;
+}
+
+static void t_cpus(void)
+{
+ int ncpu = fki_num_cpus(), c, err;
+ struct where w;
+ fki_u64 m;
+ void *th;
+
+ CHECK(ncpu == (cpus_n ? cpus_n : num_online_cpus()), "fki_num_cpus() = %d (%s)", ncpu, cpus_n ? "the length of cpu_list" : "the CPUs online");
+ for (c = -1; c <= ncpu; c++) {
+ w = (struct where){ .cpu = -1 };
+ m = ~0ULL;
+ th = fki_thread_start(where_fn, &w, c, "ifacetest");
+ err = fki_cpu_mpidr(c, &m);
+ if (is_cpu(map(c))) {
+ until(&w.done, 1000);
+ CHECK(th && w.cpu == map(c) && !err && m == w.mpidr,
+ "the foreign kernel's CPU %d: fki_thread_start() ran its thread on Linux's CPU %d (to be %d); fki_cpu_mpidr() = %d, %#llx (that CPU reads %#llx)",
+ c, w.cpu, map(c), err, m, w.mpidr);
+ } else {
+ CHECK(!th && err == -EINVAL, "the foreign kernel's CPU %d, which is no CPU (Linux's %d): fki_thread_start() gave %s, fki_cpu_mpidr() = %d",
+ c, map(c), th ? "a thread" : "none", err);
+ fki_kick_cpu(c); /* nothing to kick, and nothing must happen */
+ }
+ fki_thread_stop(th); /* (it has returned by itself: allowed) */
+ }
+ err = fki_bind_cpu(ncpu);
+ CHECK(err == -EINVAL, "fki_bind_cpu(%d) = %d", ncpu, err);
+ for (c = 0; c < ncpu && !is_cpu(map(c)); c++)
+ ;
+ if (c == ncpu)
+ return;
+ err = fki_bind_cpu(c);
+ CHECK(!err && raw_smp_processor_id() == map(c) && current->nr_cpus_allowed == 1, "fki_bind_cpu(%d) = %d: this task is on Linux's CPU %d and stays there", c, err, raw_smp_processor_id());
+
+ waiter = (struct waiter){ };
+ th = fki_thread_start(waiter_fn, NULL, c, "ifacetest");
+ msleep(30);
+ CHECK(th && !READ_ONCE(waiter.woke), "a thread in fki_thread_wait() with its flag clear: %s", READ_ONCE(waiter.woke) ? "did NOT wait" : "waits");
+ WRITE_ONCE(waiter.flag, 1);
+ fki_thread_wake(th);
+ CHECK(until(&waiter.woke, 1000) && waiter.woke == 1, "the flag set and fki_thread_wake(): %s", waiter.woke ? "it goes on" : "it still WAITS");
+ fki_thread_stop(th);
+ CHECK(READ_ONCE(waiter.stopped), "fki_thread_stop(): the thread saw fki_thread_should_stop() and %s", waiter.stopped ? "returned" : "did NOT return");
+ waiter = (struct waiter){ };
+ th = fki_thread_start(waiter_fn, NULL, c, "ifacetest");
+ msleep(30);
+ fki_thread_stop(th);
+ CHECK(waiter.woke == 2 && waiter.stopped, "fki_thread_stop() of a thread in fki_thread_wait(): %s", waiter.stopped ? "it returned" : "it did NOT return");
+}
+
+/* ---- the Ethernet link ---- */
+
+#define TEST_PROTO 0x88b5 /* an ethertype for local experiments: the frames of this test (netpeer.c has the same) */
+static const unsigned short lens[4] = { 60, 61, 590, 1514 };
+static unsigned char *fbuf;
+
+static void frame_fill(unsigned char *f, unsigned int proto, unsigned int seq, unsigned int len)
+{
+ unsigned int i;
+
+ memset(f, 0xff, 6);
+ memcpy(f + 6, "\x02xnut", 6);
+ f[12] = proto >> 8; f[13] = proto;
+ for (i = 14; i < len; i++)
+ f[i] = i < 18 ? seq >> (8 * (17 - i)) : seq * 13 + i;
+}
+
+static int frame_ok(const unsigned char *f, long len, unsigned int seq)
+{
+ unsigned int i;
+
+ if (len != lens[seq % 4])
+ return 0;
+ for (i = 14; i < len; i++)
+ if (f[i] != (unsigned char)(i < 18 ? seq >> (8 * (17 - i)) : seq * 13 + i))
+ return 0;
+ return 1;
+}
+
+struct link { long pending0, good, wrong, other, errs, empty, pending1, sent, short_r, long_r, min_r, max_r; };
+
+static long net_fn(void *p)
+{
+ struct link *s = p;
+ unsigned int i;
+ long r;
+
+ s->pending0 = fki_net_pending();
+ for (i = 0; i < 8192; i++) {
+ r = fki_net_recv(fbuf, 2048);
+ if (!r)
+ break;
+ if (r < 0)
+ s->errs++;
+ else if (r < 18 || fbuf[12] != TEST_PROTO >> 8 || fbuf[13] != (TEST_PROTO & 0xff))
+ s->other++;
+ else if (frame_ok(fbuf, r, s->good)) /* in the order they were sent */
+ s->good++;
+ else
+ s->wrong++;
+ }
+ s->empty = fki_net_recv(fbuf, 2048);
+ s->pending1 = fki_net_pending();
+ for (i = 0; i < send; i++) {
+ frame_fill(fbuf, TEST_PROTO, i, lens[i % 4]);
+ if (fki_net_send(fbuf, lens[i % 4]) == lens[i % 4])
+ s->sent++;
+ }
+ frame_fill(fbuf, TEST_PROTO + 1, 0, 1519);
+ s->short_r = fki_net_send(fbuf, 13);
+ s->long_r = fki_net_send(fbuf, 1519);
+ s->min_r = fki_net_send(fbuf, 14);
+ s->max_r = fki_net_send(fbuf, 1518);
+ return 0;
+}
+
+static void t_net(void)
+{
+ struct link s = {};
+
+ in_foreign(net_fn, &s, NULL);
+ CHECK(s.good == pending && !s.wrong && !s.errs, "fki_net_recv(): %ld of the %lu frames Linux sent on xnu0, in order and whole; %ld damaged, %ld errors (and %ld frames of other kinds)",
+ s.good, pending, s.wrong, s.errs, s.other);
+ CHECK(s.pending0 == s.good + s.wrong + s.errs + s.other, "fki_net_pending() before them = %ld", s.pending0);
+ CHECK(!s.empty && !s.pending1, "with none left: fki_net_recv() = %ld, fki_net_pending() = %ld", s.empty, s.pending1);
+ CHECK(s.sent == send, "fki_net_send() took %ld of %lu frames (60 to 1514 bytes)", s.sent, send);
+ CHECK(s.short_r < 0 && s.long_r < 0 && s.min_r == 14 && s.max_r == 1518,
+ "fki_net_send() of 13, 14, 1518 and 1519 bytes = %ld, %ld, %ld, %ld", s.short_r, s.min_r, s.max_r, s.long_r);
+}
+
+static struct net_device *xnu0;
+static int xmit_err;
+
+static int xmit_fn(void *arg)
+{
+ struct sk_buff *skb;
+
+ fki_msleep(100);
+ skb = alloc_skb(LL_RESERVED_SPACE(xnu0) + 60, GFP_KERNEL);
+ if (!skb) {
+ xmit_err = -ENOMEM;
+ return 0;
+ }
+ skb_reserve(skb, LL_RESERVED_SPACE(xnu0));
+ skb_reset_mac_header(skb);
+ frame_fill(skb_put(skb, 60), TEST_PROTO, 0, 60);
+ skb_set_network_header(skb, ETH_HLEN);
+ skb->dev = xnu0;
+ skb->protocol = htons(TEST_PROTO);
+ xmit_err = dev_queue_xmit(skb);
+ return 0;
+}
+
+/* Linux sends a frame while the foreign kernel's first CPU idles: the idle call ends for it (fki_net_xmit) */
+static void t_netwake(void)
+{
+ struct idle i = { .ns = 2 * NSEC_PER_SEC, .max_ns = 2 * NSEC_PER_SEC };
+ struct link s = {};
+ int ncpu = fki_num_cpus(), err;
+ void *th;
+
+ xnu0 = dev_get_by_name(&init_net, "xnu0");
+ if (!xnu0 || !netif_running(xnu0)) {
+ CHECK(0, "xnu0 is %s", xnu0 ? "not up" : "not there");
+ goto out;
+ }
+ err = fki_bind_cpu(0);
+ if (err) {
+ CHECK(0, "fki_bind_cpu(0) = %d", err);
+ goto out;
+ }
+ th = fki_thread_start(xmit_fn, NULL, ncpu - 1, "ifacetest-xmit");
+ in_foreign(idle_fn, &i, NULL);
+ fki_thread_stop(th);
+ send = 0;
+ in_foreign(net_fn, &s, NULL);
+ CHECK(th && !xmit_err && i.us < 1000000 && s.good == 1,
+ "the foreign kernel's CPU 0 (Linux's %d) in fki_idle_until(2 s), Linux sends a frame on xnu0 100 ms later: the call is back after %lld us; the frame %s",
+ raw_smp_processor_id(), i.us, s.good == 1 ? "waits" : "is NOT there");
+out:
+ if (xnu0)
+ dev_put(xnu0);
+}
+
+/* ---- files ---- */
+
+static long kread(const char *name, void *buf, unsigned long len, loff_t off, loff_t *size)
+{
+ struct file *f = filp_open(name, O_RDONLY | O_LARGEFILE, 0);
+ long r;
+
+ if (IS_ERR(f))
+ return PTR_ERR(f);
+ r = kernel_read(f, buf, len, &off);
+ if (size)
+ *size = i_size_read(f->f_mapping->host);
+ filp_close(f, NULL);
+ return r;
+}
+
+struct io { void *file; int write; void *buf; unsigned long len; fki_u64 off; long r; int atomic; };
+
+static long io_fn(void *p)
+{
+ struct io *o;
+
+ for (o = p; o->buf; o++) {
+ o->r = fki_file_rw(o->file, o->write, o->buf, o->len, o->off);
+ o->atomic = irqs_disabled() && preempt_count();
+ }
+ return 0;
+}
+
+static void t_file(void)
+{
+ unsigned char *a = vmalloc(n + 4096), *b = vmalloc(n + 8192);
+ unsigned long big = 300000, i;
+ fki_u64 size = ~0ULL;
+ loff_t ksize = 0;
+ void *f, *fw;
+ long kr;
+
+ if (!a || !b || n < big + 4096)
+ goto out;
+ f = fki_file_open(path, 0, &size);
+ CHECK(f && size == n, "fki_file_open(a file of %lu bytes, to read): %s, size %llu", n, f ? "a handle" : "NO handle", size);
+ if (!f)
+ goto out;
+ {
+ struct io o[] = {
+ { f, 0, a, n, 0 }, { f, 0, b, 4096, n - 100 }, { f, 0, b, 4096, n }, { f, 0, b, 4096, n + (1 << 20) },
+ { f, 1, a, 4096, 0 }, { NULL, 0, b, 4096, 0 }, { }
+ };
+
+ in_foreign(io_fn, o, NULL);
+ kr = kread(path, b, n, 0, NULL);
+ CHECK(o[0].r == n && kr == n && !memcmp(a, b, n) && o[0].atomic,
+ "fki_file_rw(read all of it) = %ld: %s the kernel's own read of the file; interrupts and preemption %s after it",
+ o[0].r, kr == n && !memcmp(a, b, n) ? "the same bytes as" : "NOT the bytes of", o[0].atomic ? "off again" : "NOT off again");
+ CHECK(o[1].r == 100, "fki_file_rw(read 4096 bytes, 100 before the end) = %ld", o[1].r);
+ CHECK(o[2].r == 0 && o[3].r == 0, "fki_file_rw(read at the end, and 1 MiB past it) = %ld, %ld", o[2].r, o[3].r);
+ CHECK(o[4].r < 0, "fki_file_rw(write) on a file opened to read = %ld", o[4].r);
+ CHECK(o[5].r == -EBADF, "fki_file_rw() without a file = %ld", o[5].r);
+ }
+ fki_file_close(f);
+
+ fw = fki_file_open(path, 1, NULL);
+ CHECK(fw, "fki_file_open(the file, to write): %s", fw ? "a handle" : "NO handle");
+ if (!fw)
+ goto out;
+ for (i = 0; i < big; i++)
+ a[i] = i * 37 + (i >> 9);
+ {
+ struct io o[] = { { fw, 1, a, big, 5 }, { fw, 1, a, 100, n + 4096 }, { fw, 0, b, big, 5 }, { } };
+
+ in_foreign(io_fn, o, NULL);
+ CHECK(o[0].r == big && o[2].r == big && !memcmp(a, b, big), "fki_file_rw(write %lu bytes at 5) = %ld, read back = %ld: %s", big, o[0].r, o[2].r,
+ !memcmp(a, b, big) ? "the same bytes" : "NOT the same bytes");
+ kr = kread(path, b, n + 8192, 0, &ksize);
+ CHECK(o[1].r == 100 && ksize == n + 4196 && kr == ksize && !memcmp(b + 5, a, big) && !memcmp(b + n + 4096, a, 100) && !memchr_inv(b + n, 0, 4096),
+ "fki_file_rw(write 100 bytes 4096 past the end) = %ld: the kernel's own read finds %lld bytes (to be %lu), both writes in place, zeros between", o[1].r, ksize, n + 4196);
+ }
+ kr = fki_file_pwrite(fw, "pwrite", 6, 1);
+ kread(path, b, 16, 0, NULL);
+ CHECK(kr == 6 && !memcmp(b + 1, "pwrite", 6), "fki_file_pwrite(6 bytes at 1) = %ld: %s", kr, !memcmp(b + 1, "pwrite", 6) ? "in the file" : "NOT in the file");
+ kr = fki_file_pwrite(NULL, "x", 1, 0);
+ CHECK(kr == -EBADF, "fki_file_pwrite() without a file = %ld", kr);
+ fki_file_close(fw);
+ f = fki_file_open(path, 0, NULL);
+ kr = fki_file_pwrite(f, "x", 1, 0);
+ CHECK(f && kr == -EBADF, "fki_file_pwrite() on a file opened to read = %ld", kr);
+ fki_file_close(f);
+ fki_file_close(NULL);
+ f = fki_file_open("/nonexistent/ifacetest", 0, &size);
+ CHECK(!f, "fki_file_open(a path that is not there): %s", f ? "a handle" : "no handle");
+ if (*dev) {
+ size = ~0ULL;
+ f = fki_file_open(dev, 0, &size);
+ CHECK(f && size == devn, "fki_file_open(%s, a block device of %lu bytes): %s, size %llu", dev, devn, f ? "a handle" : "NO handle", size);
+ if (f) {
+ struct io o[] = { { f, 0, a, 4096, devn - 4096 }, { f, 0, b, 4096, devn }, { } };
+
+ in_foreign(io_fn, o, NULL);
+ kr = kread(dev, b, 4096, devn - 4096, NULL);
+ CHECK(o[0].r == 4096 && kr == 4096 && !memcmp(a, b, 4096) && o[1].r == 0, "fki_file_rw(read its last 4096 bytes, and at its end) = %ld, %ld", o[0].r, o[1].r);
+ fki_file_close(f);
+ }
+ }
+out:
+ vfree(a); vfree(b);
+}
+
+/* ---- firmware blobs ---- */
+
+static void t_blob(void)
+{
+ unsigned char *b = vmalloc(n + 4096);
+ char name[128], none[128];
+ const void *data = NULL;
+ unsigned long size = 0;
+ void *handle = NULL;
+ long kr;
+ int err;
+
+ if (!b)
+ return;
+ snprintf(name, sizeof(name), "/lib/firmware/%s", blob);
+ snprintf(none, sizeof(none), "%s.none", blob);
+ kr = kread(name, b, n + 4096, 0, NULL);
+ err = fki_blob_get(blob, &data, &size, &handle);
+ CHECK(!err && size == n && kr == n && data && !memcmp(data, b, n), "fki_blob_get(\"%s\") = %d: %lu bytes, %s the kernel's own read of %s (%ld bytes)",
+ blob, err, size, !err && kr == n && size == n && !memcmp(data, b, n) ? "the same as" : "NOT", name, kr);
+ if (!err)
+ fki_blob_put(handle);
+ err = fki_blob_get(none, &data, &size, &handle);
+ CHECK(err < 0, "fki_blob_get(a name that is not there) = %d", err);
+ vfree(b);
+}
+
+/* ---- memory ---- */
+
+static unsigned long free_mb(void)
+{
+ struct sysinfo si;
+
+ si_meminfo(&si);
+ return si.freeram >> (20 - PAGE_SHIFT);
+}
+
+static void t_mem(void)
+{
+ static const u32 code[] = { 0xd503245f /* bti c */, 0x52800540 /* mov w0, #42 */, 0xd65f03c0 /* ret */ };
+ struct fki_region r = {}, c = {}, d = {};
+ unsigned long before, after;
+ fki_u64 first;
+ int err, i, v = 0, zero;
+
+ err = fki_region_alloc(3 * PAGE_SIZE + 1, &r);
+ zero = !err && !memchr_inv(r.va, 0, r.size);
+ CHECK(!err && r.va && r.size == 4 * PAGE_SIZE && zero && r.pa == page_to_phys(vmalloc_to_page(r.va)),
+ "fki_region_alloc(3 pages and a byte) = %d: %llu bytes, %s, pa %#llx (its first page is at %#llx)", err, r.size, zero ? "zeroed" : "NOT zeroed",
+ r.pa, err ? 0 : (u64)page_to_phys(vmalloc_to_page(r.va)));
+ if (!err) {
+ memcpy((char *)r.va + 3 * PAGE_SIZE, code, sizeof(code));
+ fki_icache_flush((unsigned long)r.va, r.size);
+ v = ((int (*)(void))((char *)r.va + 3 * PAGE_SIZE))();
+ CHECK(v == 42, "code written into its last page and called: returned %d (to be 42)", v);
+ fki_region_free(&r);
+ }
+ before = free_mb();
+ for (i = 0; i < 200 && !err; i++) {
+ err = fki_region_alloc(1 << 20, &r);
+ if (!err)
+ fki_region_free(&r);
+ }
+ after = free_mb();
+ CHECK(!err && after + 64 > before, "200 times fki_region_alloc(1 MiB) and fki_region_free(): free memory %lu MiB before, %lu MiB after", before, after);
+
+ err = fki_contig_alloc(3 << 20, &c);
+ zero = !err && !memchr_inv(c.va, 0, c.size);
+ CHECK(!err && c.size == 4 << 20 && virt_to_phys(c.va) == c.pa && !(c.pa & ((2 << 20) - 1)) && zero,
+ "fki_contig_alloc(3 MiB) = %d: %llu bytes (a power of two) at pa %#llx, %s, va %s its address in Linux's map of memory", err, c.size, c.pa,
+ zero ? "zeroed" : "NOT zeroed", !err && virt_to_phys(c.va) == c.pa ? "is" : "is NOT");
+ if (!err) {
+ memset(c.va, 0xa5, c.size);
+ fki_contig_free(&c);
+ }
+ before = free_mb();
+ for (i = 0; i < 50 && !err; i++) {
+ err = fki_contig_alloc(4 << 20, &c);
+ if (!err) {
+ memset(c.va, 0xa5, c.size);
+ fki_contig_free(&c);
+ }
+ }
+ after = free_mb();
+ CHECK(!err && after + 64 > before, "50 times fki_contig_alloc(4 MiB), written, and fki_contig_free(): free memory %lu MiB before, %lu MiB after (the last result %d)", before, after, err);
+ if (!resv)
+ return;
+ /* fki.ko was loaded with reserve_mb=resv: the reservation is what the first call of its size gets, and gets again */
+ err = fki_contig_alloc(resv << 20, &c);
+ first = c.pa;
+ i = fki_contig_alloc(resv << 20, &d);
+ CHECK(!err && c.size == resv << 20 && !memchr_inv(c.va, 0, c.size) && (i || d.pa != c.pa),
+ "fki_contig_alloc(%lu MiB, what reserve_mb set aside) = %d at pa %#llx; a second one while it is held = %d%s", resv, err, c.pa, i, !i && d.pa == c.pa ? " at the SAME address" : "");
+ if (!i)
+ fki_contig_free(&d);
+ if (err)
+ return;
+ memset(c.va, 0xa5, c.size);
+ fki_contig_free(&c);
+ err = fki_contig_alloc(resv << 20, &c);
+ CHECK(!err && c.pa == first && !memchr_inv(c.va, 0, c.size), "freed and asked for again = %d: at pa %#llx (the reservation is at %#llx), %s", err, c.pa, first,
+ !err && !memchr_inv(c.va, 0, c.size) ? "zeroed" : "NOT zeroed");
+ if (!err)
+ fki_contig_free(&c);
+}
+
+/* fki.ko was loaded with a carve-out (carve_base=, carve_mb=) that run.sh chose to be refused: want is the error */
+static void t_carve(void)
+{
+ struct fki_region c = {};
+ int err = fki_contig_alloc(2 << 20, &c);
+
+ CHECK(err == want, "fki_contig_alloc(2 MiB) with that carve-out = %d (to be %ld)", err, want);
+ if (!err)
+ fki_contig_free(&c);
+}
+
+/* ---- kernel faults of the foreign kernel ---- */
+
+static struct fault { unsigned long calls, far, esr, pc, pstate, x0; } flt;
+
+static int fault_handler(unsigned long far, unsigned long esr, void *regs)
+{
+ flt.calls++;
+ flt.far = far;
+ flt.esr = esr;
+ flt.pc = fki_regs_pc(regs);
+ flt.pstate = fki_regs_pstate(regs);
+ flt.x0 = fki_regs_reg(regs, 0);
+ fki_regs_set_reg(regs, 1, 0x600d);
+ fki_regs_set_pc(regs, flt.pc + 4); /* go on after the instruction */
+ return 0;
+}
+
+static long peek_fn(void *p)
+{
+ return ifacetest_peek((unsigned long)p);
+}
+
+static long undef_fn(void *p)
+{
+ return ifacetest_undef();
+}
+
+static void t_fault(void)
+{
+ unsigned long r;
+ int err, again;
+
+ err = fki_fault_register(0, PAGE_SIZE, fault_handler);
+ again = fki_fault_register(0, PAGE_SIZE, fault_handler);
+ CHECK(!err && again == -EBUSY, "fki_fault_register() = %d, a second one = %d", err, again);
+ if (err)
+ return;
+ flt = (struct fault){ };
+ r = in_foreign(peek_fn, (void *)0x10, NULL);
+ CHECK(flt.calls == 1 && flt.far == 0x10 && flt.pc == (unsigned long)ifacetest_peek_insn && flt.x0 == 0x10 && ESR_ELx_EC(flt.esr) == ESR_ELx_EC_DABT_CUR,
+ "a load from address 0x10 in the registered range, inside fki_enter(): the handler was called %lu time(s) with far %#lx, esr %#lx, pc %s the load, x0 %#lx",
+ flt.calls, flt.far, flt.esr, flt.pc == (unsigned long)ifacetest_peek_insn ? "at" : "NOT at", flt.x0);
+ CHECK((flt.pstate & (PSR_MODE_MASK | PSR_I_BIT)) == (PSR_MODE_EL1h | PSR_I_BIT), "fki_regs_pstate() = %#lx: EL1 with its interrupts off", flt.pstate);
+ CHECK(r == 0x600d, "after it the code went on where fki_regs_set_pc() said, with the register fki_regs_set_reg() wrote: %#lx (to be 0x600d)", r);
+ fki_fault_unregister();
+
+ err = fki_fault_register((unsigned long)ifacetest_peek, (unsigned long)ifacetest_peek + 32, fault_handler);
+ CHECK(!err, "fki_fault_unregister(), then fki_fault_register() for the range of the code = %d", err);
+ if (err)
+ return;
+ flt = (struct fault){ };
+ r = in_foreign(peek_fn, (void *)0x18, NULL);
+ CHECK(flt.calls == 1 && flt.far == 0x18 && r == 0x600d, "a fault at an address outside the range, from code inside it: the handler was called %lu time(s), far %#lx", flt.calls, flt.far);
+ fki_fault_unregister();
+}
+
+/* an exception that is not an abort, in the registered range (fki's probe of die(); run.sh checks that fki has it) */
+static void t_undef(void)
+{
+ unsigned long r;
+ int err;
+
+ err = fki_fault_register((unsigned long)ifacetest_undef, (unsigned long)ifacetest_undef + 32, fault_handler);
+ if (err) {
+ CHECK(0, "fki_fault_register() = %d", err);
+ return;
+ }
+ flt = (struct fault){ };
+ r = in_foreign(undef_fn, NULL, NULL);
+ CHECK(flt.calls == 1 && flt.far == 0 && flt.pc == (unsigned long)ifacetest_undef_insn && r == 0x600d,
+ "an undefined instruction in the registered range, inside fki_enter(): the handler was called %lu time(s) with far %#lx, esr %#lx, pc %s the instruction; the code went on with %#lx",
+ flt.calls, flt.far, flt.esr, flt.pc == (unsigned long)ifacetest_undef_insn ? "at" : "NOT at", r);
+ fki_fault_unregister();
+}
+
+/* ---- the FP/SIMD registers (fpload.c loads this module with its own registers set, and looks at them after) ---- */
+
+static long fp_fn(void *p)
+{
+ ifacetest_simd(0xee);
+ fki_yield(); /* Linux runs, and the registers are the foreign kernel's again after */
+ ifacetest_simd(0xdd);
+ fki_idle_until(fki_counter() + div64_u64(fki_counter_frequency(), 500), 2 * NSEC_PER_MSEC, NULL);
+ ifacetest_simd(0xcc);
+ return 0;
+}
+
+static void t_fp(void)
+{
+ in_foreign(fp_fn, NULL, NULL);
+ pr_info("ifacetest: inside fki_enter() every FP/SIMD register, FPSR and FPCR were written three times, with fki_yield() and fki_idle_until() between\n");
+}
+
+static const struct { const char *name; void (*fn)(void); } tests[] = {
+ { "enter", t_enter }, { "clock", t_clock }, { "idle", t_idle }, { "cpus", t_cpus }, { "net", t_net }, { "netwake", t_netwake },
+ { "file", t_file }, { "blob", t_blob }, { "mem", t_mem }, { "carve", t_carve }, { "fault", t_fault }, { "undef", t_undef }, { "fp", t_fp },
+};
+
+static int __init ifacetest_init(void)
+{
+ int i;
+
+ fbuf = kmalloc(2048, GFP_KERNEL);
+ stack_mem = vzalloc(4 * THREAD_SIZE);
+ if (!fbuf || !stack_mem) {
+ kfree(fbuf); vfree(stack_mem);
+ return -ENOMEM;
+ }
+ /* (as Linux's stacks and XNU's lie: the exception entry takes a set bit THREAD_SHIFT of sp for an overflow) */
+ stack_top = PTR_ALIGN(stack_mem, 2 * THREAD_SIZE) + THREAD_SIZE;
+ for (i = 0; i < ARRAY_SIZE(tests); i++)
+ if (!strcmp(t, tests[i].name))
+ break;
+ if (i < ARRAY_SIZE(tests))
+ tests[i].fn();
+ else
+ CHECK(0, "no such test: t=%s", t);
+ pr_info("ifacetest: %s: %s\n", t, bad ? "FAIL" : "ok");
+ kfree(fbuf); vfree(stack_mem);
+ return -EAGAIN;
+}
+module_init(ifacetest_init);
+MODULE_LICENSE("GPL");
diff --git a/fki-ko/test/iface/netpeer.c b/fki-ko/test/iface/netpeer.c
new file mode 100644
index 0000000..ae76716
--- /dev/null
+++ b/fki-ko/test/iface/netpeer.c
@@ -0,0 +1,98 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * Linux's end of the link xnu0 for run.sh: a raw socket on the device, as any Linux program has one.
+ * netpeer IF send COUNT send COUNT frames of the test (60, 61, 590 and 1514 bytes in turn, numbered)
+ * netpeer IF recv COUNT SECS wait for COUNT frames of the test (at most SECS seconds) and check each one
+ * netpeer IF hold COUNT SECS send COUNT frames, then watch what the kernel still charges this socket for them
+ * (frames nobody has taken or freed) until that is nothing, at most SECS seconds
+ * recv prints "listening" when it is; exit status 0 when all COUNT frames came, in order and whole. hold prints
+ * "holding" when the frames are sent; exit status 0 when nothing is charged any more.
+ * The frames are those of ifacetest's main.c: an ethertype for local experiments, a number, bytes that follow from it.
+ */
+#include <arpa/inet.h>
+#include <errno.h>
+#include <linux/if_packet.h>
+#include <linux/sockios.h>
+#include <net/if.h>
+#include <poll.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/ioctl.h>
+#include <sys/socket.h>
+#include <time.h>
+#include <unistd.h>
+
+#define TEST_PROTO 0x88b5
+static const unsigned short lens[4] = { 60, 61, 590, 1514 };
+
+static void frame_fill(unsigned char *f, unsigned seq, unsigned len)
+{
+ unsigned i;
+
+ memset(f, 0xff, 6);
+ memcpy(f + 6, "\x02xnut", 6);
+ f[12] = TEST_PROTO >> 8; f[13] = TEST_PROTO & 0xff;
+ for (i = 14; i < len; i++) f[i] = i < 18 ? seq >> (8 * (17 - i)) : seq * 13 + i;
+}
+
+static int frame_ok(const unsigned char *f, long len, unsigned seq)
+{
+ unsigned i;
+
+ if (len != lens[seq % 4]) return 0;
+ for (i = 14; i < len; i++) if (f[i] != (unsigned char)(i < 18 ? seq >> (8 * (17 - i)) : seq * 13 + i)) return 0;
+ return 1;
+}
+
+int main(int argc, char **argv)
+{
+ struct sockaddr_ll ll = { .sll_family = AF_PACKET, .sll_protocol = htons(TEST_PROTO) };
+ unsigned char f[2048];
+ unsigned count, i, good = 0, got = 0, refused = 0;
+ int s, big = 64 << 20;
+
+ if (argc < 4 || (strcmp(argv[2], "send") && ((strcmp(argv[2], "recv") && strcmp(argv[2], "hold")) || argc < 5))) {
+ fprintf(stderr, "usage: netpeer IF send COUNT | netpeer IF recv COUNT SECS | netpeer IF hold COUNT SECS\n");
+ return 2;
+ }
+ count = strtoul(argv[3], NULL, 0);
+ ll.sll_ifindex = if_nametoindex(argv[1]);
+ s = socket(AF_PACKET, SOCK_RAW, htons(TEST_PROTO));
+ if (s < 0 || !ll.sll_ifindex || bind(s, (struct sockaddr *)&ll, sizeof(ll))) { perror(argv[1]); return 2; }
+ if (strcmp(argv[2], "recv")) {
+ int charged = 0, ms;
+
+ setsockopt(s, SOL_SOCKET, SO_SNDBUFFORCE, &big, sizeof(big)); /* frames nobody takes stay charged to the socket */
+ for (i = 0; i < count; i++) {
+ frame_fill(f, i, lens[i % 4]);
+ if (send(s, f, lens[i % 4], MSG_DONTWAIT) != lens[i % 4]) refused++;
+ }
+ if (!strcmp(argv[2], "send")) {
+ printf("sent %u frames on %s (%u refused)\n", count - refused, argv[1], refused);
+ return refused ? 1 : 0;
+ }
+ ioctl(s, SIOCOUTQ, &charged);
+ printf("holding: %u frames sent on %s, %d bytes charged to the socket for them\n", count - refused, argv[1], charged); fflush(stdout);
+ for (ms = 0; charged && ms < atoi(argv[4]) * 1000; ms += 50) {
+ usleep(50000);
+ ioctl(s, SIOCOUTQ, &charged);
+ }
+ printf("%d ms later: %d bytes charged\n", ms, charged);
+ return charged || refused ? 1 : 0;
+ }
+ time_t end = time(NULL) + atoi(argv[4]);
+ puts("listening"); fflush(stdout);
+ while (got < count && time(NULL) < end) {
+ struct pollfd p = { s, POLLIN, 0 };
+ long r;
+
+ if (poll(&p, 1, 200) <= 0) continue;
+ r = recv(s, f, sizeof(f), 0);
+ if (r < 0) continue;
+ if (frame_ok(f, r, got)) good++;
+ got++;
+ }
+ printf("received %u of %u frames on %s, %u of them in order and whole\n", got, count, argv[1], good);
+ return got == count && good == count ? 0 : 1;
+}
diff --git a/fki-ko/test/iface/run.sh b/fki-ko/test/iface/run.sh
new file mode 100755
index 0000000..09b5d84
--- /dev/null
+++ b/fki-ko/test/iface/run.sh
@@ -0,0 +1,170 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0-only
+# fki's interface on a real kernel: a small module (main.c, asm.S) calls what fki exports the way xnu.ko calls it, from
+# inside fki_enter() where xnu.ko does, and holds every answer against fki.h and against the kernel's own; netpeer.c is
+# Linux's end of the link xnu0 and fpload.c the process whose FP/SIMD registers a foreign entry must not touch.
+# On an arm64 Linux host of the project: root (sudo), fki.ko built in ../.. and not in use (no hosted system: the test
+# loads and unloads fki.ko itself, with the parameters each group of checks needs, and at the end loads it again with
+# those it found), the kernel's headers, cc, ip, losetup.
+# run.sh every group but the last
+# run.sh NAME... only these: enter clock idle cpus mem fault fp file blob net netq netwake unload reload cpulist
+# cpulist-bad reserve carve carve-hole
+# carve-hole loads fki.ko with a carve-out where the machine has no memory at all. An fki.ko that does not refuse that
+# one maps it, and the machine stops at the first access: ask for it by name, where that can be afforded.
+# Exit status 0: all as fki.h says; 1: not; 2: could not run.
+set -u
+D=$(cd "$(dirname "$0")" && pwd); P=$(cd "$D/../../.." && pwd); K=${KDIR:-/lib/modules/$(uname -r)/build}
+S=sudo; [ "$(id -u)" = 0 ] && S=
+all="enter clock idle cpus mem fault fp file blob net netq netwake unload reload cpulist cpulist-bad reserve carve"
+[ $# = 0 ] || all="$*"
+[ ! -d /sys/module/xnu ] || { echo "a hosted system is running: not beside it" >&2; exit 2; }
+[ -f "$P/fki-ko/fki.ko" ] && [ -f "$P/fki-ko/Module.symvers" ] || { echo "no fki-ko/fki.ko: build fki-ko first (make -C $K M=$P/fki-ko modules)" >&2; exit 2; }
+was=no
+if [ -d /sys/module/fki ]; then # as it was loaded: put back at the end
+ was=
+ for f in /sys/module/fki/parameters/*; do v=$(tr -d '\n' < "$f"); [ -z "$v" ] || [ "$v" = 0 ] || was="$was ${f##*/}=$v"; done
+fi
+
+W=$(mktemp -d) || exit 2
+loop=; peer=
+cleanup() {
+ [ -z "$peer" ] || $S kill "$peer" 2>/dev/null
+ [ -z "$loop" ] || $S losetup -d "$loop" 2>/dev/null
+ $S rm -f /lib/firmware/fki-ifacetest.bin
+ $S rmmod fki 2>/dev/null
+ [ "$was" = no ] || $S insmod "$P/fki-ko/fki.ko" $was
+ rm -rf "$W"
+}
+trap cleanup EXIT
+cp "$D/main.c" "$D/asm.S" "$D/Makefile" "$W/"; mkdir "$W/fki-ko"; cp "$P/fki-ko/fki.h" "$W/fki-ko/"
+log=$(make -s -C "$K" M="$W" KBUILD_EXTRA_SYMBOLS="$P/fki-ko/Module.symvers" modules 2>&1) && [ -e "$W/ifacetest.ko" ] ||
+ { echo "$log" | grep -iE "error|\*\*\*" | head -10 >&2; echo "the test module did not build" >&2; exit 2; }
+cc -O2 -Wall -o "$W/netpeer" "$D/netpeer.c" && cc -O2 -Wall -o "$W/fpload" "$D/fpload.c" || { echo "the helpers did not build" >&2; exit 2; }
+
+status=0; cur=none
+fail() { [ $status = 2 ] || status=1; }
+since() { $S dmesg | awk -v m="$mark" 'f { sub(/^\[[^]]*\] */, ""); print } index($0, m) { f = 1 }'; } # the kernel log after the mark
+mark() { mark="ifacetest: run $$ $RANDOM $*"; echo "$mark" | $S tee /dev/kmsg > /dev/null; }
+load() { # fki.ko with these parameters (as it is, when it is loaded with them already)
+ [ "$cur" = "$*" ] && return
+ $S rmmod fki 2>/dev/null
+ [ ! -d /sys/module/fki ] || { echo "fki.ko is in use: cannot load it again" >&2; exit 2; }
+ $S insmod "$P/fki-ko/fki.ko" "$@" || { echo "fki.ko did not load ($*)" >&2; exit 2; }
+ cur="$*"
+}
+mod() { # the test module once: mod TEST [parameter=value...]; prints its lines
+ mark "$1"
+ $S insmod "$W/ifacetest.ko" t="$@" 2>/dev/null # (its init reports and returns an error: it never stays loaded)
+ out=$(since | grep '^ifacetest: ')
+ [ -n "$out" ] || { echo "the test module did not run (the kernel log has no line of it)" >&2; exit 2; }
+ echo "$out" | sed 's/^ifacetest: / /'
+ echo "$out" | grep -q "^ifacetest: $1: ok\$" || fail
+}
+line() { if [ "$1" = 0 ]; then echo " ok: $2"; else echo " FAIL: $2"; fail; fi; }
+up() { $S sysctl -qw net.ipv6.conf.xnu0.disable_ipv6=1; $S ip link set xnu0 up || { echo "xnu0 did not come up" >&2; exit 2; }; } # (no frames of Linux's own on it)
+cma() { awk '/^CmaFree:/ { print $2 }' /proc/meminfo; }
+# (CmaFree is printed beside the checks and not judged: right after an unload it reads 6 to 10 MiB low for a while and
+# is back later, with upstream's fki.ko as with any other. What tells a reservation that was not given back is the next
+# load: with half of the CMA area reserved each time, the third could not get its own and fki.ko says "NOT reserved".)
+online=$(for c in /sys/devices/system/cpu/cpu[0-9]*; do [ ! -e "$c/online" ] || [ "$(cat "$c/online")" = 1 ] && echo "${c##*cpu}"; done | sort -n | tr '\n' ' ')
+last=$(echo $online | awk '{ print $NF }'); prev=$(echo $online | awk '{ if (NF > 1) print $(NF - 1) }')
+
+for t in $all; do
+ echo "== $t"
+ case $t in
+ enter|clock|idle|cpus|mem)
+ load; mod $t;;
+ fault)
+ load; mod fault
+ if since | grep -q 'no die() probe'; then echo " skipped: an exception that is not an abort (this kernel gave fki no probe of die())"; else mod undef; fi;;
+ fp)
+ load; mark fp
+ $S "$W/fpload" "$W/ifacetest.ko" | sed 's/^/ /'; r=${PIPESTATUS[0]}
+ since | grep '^ifacetest: ' | sed 's/^ifacetest: / (the module: /; s/$/)/'
+ [ "$r" = 0 ] || { fail; [ "$r" = 1 ] || status=2; };;
+ file)
+ load
+ head -c 1048581 /dev/urandom > "$W/file"; truncate -s 8M "$W/disk"
+ loop=$($S losetup --find --show "$W/disk" 2>/dev/null) || loop=
+ [ -n "$loop" ] || echo " skipped: a block device's size (no loop device to be had)"
+ mod file path="$W/file" n=1048581 ${loop:+dev=$loop devn=8388608}
+ ! since | grep -q 'WARNING:'; line $? "the kernel log of those calls: $(since | grep -c 'WARNING:') warning(s)$(since | grep -m1 'WARNING:' | sed 's/^/ (/; s/$/)/')"
+ [ -z "$loop" ] || $S losetup -d "$loop"; loop=;;
+ blob)
+ load
+ head -c 300001 /dev/urandom | $S tee /lib/firmware/fki-ifacetest.bin > /dev/null
+ mod blob blob=fki-ifacetest.bin n=300001
+ $S rm -f /lib/firmware/fki-ifacetest.bin;;
+ net) # 8 frames from Linux's raw socket to the foreign side, 12 back
+ cur=none; load; up
+ $S "$W/netpeer" xnu0 send 8 | sed 's/^/ Linux: /'
+ $S "$W/netpeer" xnu0 recv 12 10 > "$W/peer.out" 2>&1 &
+ peer=$!
+ for _ in $(seq 1 50); do grep -q '^listening$' "$W/peer.out" 2>/dev/null && break; sleep 0.1; done
+ mod net pending=8 send=12
+ wait "$peer" || fail; peer=
+ grep -v '^listening$' "$W/peer.out" | sed 's/^/ Linux: /';;
+ netq) # more frames than the link's queue holds (1024)
+ cur=none; load; up
+ $S "$W/netpeer" xnu0 send 1100 | sed 's/^/ Linux: /'
+ mod net pending=1024 send=0
+ d=$(cat /sys/class/net/xnu0/statistics/tx_dropped); p=$(cat /sys/class/net/xnu0/statistics/tx_packets)
+ [ "$d" = 76 ] && [ "$p" = 1024 ]; line $? "xnu0's counters after 1100 frames nobody took: $p sent, $d dropped (the queue holds 1024)";;
+ netwake)
+ load; up; mod netwake;;
+ unload) # frames still in the link's queue when fki.ko is unloaded: freed (no longer charged to the socket that sent them)
+ cur=none; load; up
+ $S "$W/netpeer" xnu0 hold 500 15 > "$W/peer.out" 2>&1 &
+ peer=$!
+ for _ in $(seq 1 50); do grep -q '^holding' "$W/peer.out" 2>/dev/null && break; sleep 0.1; done
+ $S rmmod fki; r=$?; cur=none
+ wait "$peer"; pr=$?; peer=
+ sed 's/^/ Linux: /' "$W/peer.out"
+ [ $r = 0 ] && [ $pr = 0 ]; line $? "fki.ko unloaded with 500 frames in the link's queue (rmmod: exit $r)";;
+ reload) # loaded and unloaded ten times, with a reservation where there is CMA: nothing is left behind
+ $S rmmod fki 2>/dev/null; cur=none; mark reload
+ t=$(awk '/^CmaTotal:/ { print $2 }' /proc/meminfo); r=; [ "${t:-0}" -ge 32768 ] 2>/dev/null && r=reserve_mb=$((t / 2048)) # half of it
+ c0=$(cma); bad=0
+ for _ in 1 2 3 4 5 6 7 8 9 10; do $S insmod "$P/fki-ko/fki.ko" $r && $S rmmod fki || bad=1; done
+ c2=$(cma); got=$(since | grep -c "^fki: .* DRAM reserved\$"); not=$(since | grep -c '^fki: .* NOT reserved')
+ [ $bad = 0 ] && { [ -z "$r" ] || [ "$got" = 10 ]; } && [ "$not" = 0 ] && ! since | grep -qiE 'WARNING|BUG|Oops|Call trace'
+ line $? "fki.ko ${r:+with $r }loaded and unloaded 10 times${r:+: $got of the 10 loads got their reservation} (CmaFree $c0 kB before, $c2 kB after), the kernel log $(since | grep -ciE 'WARNING|BUG|Oops|Call trace') warnings";;
+ cpulist) # the foreign kernel's CPUs are not Linux's first ones
+ [ -n "$prev" ] && [ "$prev" != 0 ] || { echo " skipped: needs two CPUs online besides CPU 0"; continue; }
+ load cpu_list=$prev,$last
+ mod cpus cpus=$prev,$last; mod idle cpus=$prev,$last; up; mod netwake cpus=$prev,$last;;
+ cpulist-bad) # a CPU that is not there, and one named twice
+ none=$(( $(cat /sys/devices/system/cpu/kernel_max) + 1 ))
+ load cpu_list=$last,$none,$last
+ mod cpus cpus=$last,$none,$last;;
+ reserve)
+ [ "$(awk '/^CmaTotal:/ { print $2 }' /proc/meminfo)" -ge 32768 ] 2>/dev/null || { echo " skipped: this kernel has no CMA area of 32 MiB or more (cma=)"; continue; }
+ $S rmmod fki 2>/dev/null; cur=none; c0=$(cma); mark reserve
+ load reserve_mb=16; c1=$(cma)
+ since | grep '^fki: .*reserved' | sed 's/^/ /'
+ since | grep -q "^fki: 16 MiB for the foreign kernel's DRAM reserved\$"; said=$?
+ mod mem resv=16 # (it asks for the 16 MiB and must get them at the reservation's address)
+ $S rmmod fki; cur=none; c2=$(cma)
+ line $said "reserve_mb=16: fki.ko says it has them (CmaFree $c0 kB before the load, $c1 kB with fki.ko loaded, $c2 kB after its unload)"
+ mark reserve; load reserve_mb=1048576
+ since | grep '^fki: .*reserved' | sed 's/^/ /'
+ since | grep -q 'NOT reserved'; line $? "reserve_mb=1048576 (more than there is): fki.ko loads and says so";;
+ carve) # a carve-out that is Linux's own memory: refused, not mapped
+ ram=$($S awk -F'[- ]' '/System RAM/ { print $1; exit }' /proc/iomem)
+ base=$(printf '%#x' $(( (0x$ram + 0x4000000) & ~0x1fffff )))
+ mark carve; load carve_base=$base carve_mb=64
+ mod carve want=-16
+ since | grep '^fki: carve-out' | cut -c1-150 | sed 's/^/ /';;
+ carve-hole) # a carve-out that is no memory at all: refused by the firmware's map, not mapped
+ [ -d /sys/firmware/efi ] || { echo " skipped: this kernel has no firmware memory map to ask (not an EFI boot)"; continue; }
+ ! grep -qw 'mem=[^ ]*' /proc/cmdline || { echo " skipped: this kernel was booted with mem=: memory may lie above what Linux uses"; continue; }
+ top=$($S awk -F'[- ]' '/System RAM/ { e = $2 } END { print e }' /proc/iomem)
+ base=$(printf '%#x' $(( ((0x$top >> 30) + 5) << 30 ))) # 4 to 5 GiB past the end of the machine's memory
+ mark carve-hole; load carve_base=$base carve_mb=64
+ mod carve want=-22
+ since | grep '^fki: carve-out' | cut -c1-170 | sed 's/^/ /';;
+ *) echo "no such group: $t" >&2; status=2;;
+ esac
+done
+[ $status = 0 ] && echo "all as fki.h says" || echo "NOT all as fki.h says"
+exit $status
diff --git a/tests/host/xlate.c b/tests/host/xlate.c
new file mode 100644
index 0000000..64a232e
--- /dev/null
+++ b/tests/host/xlate.c
@@ -0,0 +1,110 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * fki's /dev/xnu-hostcall translates a service's mappings into physical addresses (XNU_HOSTCALL_XLATE: what the DRM
+ * bridge hands the hosted kernel to map). This checks the answers against the kernel's own, for both kinds of mapping:
+ * - ordinary memory (one page, locked): against /proc/self/pagemap
+ * - a device mapping (VM_IO | VM_PFNMAP): a PCI memory BAR mapped through sysfs, against the BAR's address in the
+ * device's `resource` file. The lookup for these is the one that differs by kernel version (fki_hostcall.c).
+ * Needs root, fki.ko loaded and no other user of /dev/xnu-hostcall (xnudrmd). No hosted system is needed.
+ * cc -O2 -o xlate xlate.c && sudo ./xlate [/sys/bus/pci/devices/0000:BB:DD.F/resourceN]
+ * Without an argument it takes the first PCI memory BAR that can be mapped (one no driver has claimed); with none the
+ * device half is skipped and says so. Exit status 0: every answer right; 1: a wrong answer; 2: could not run.
+ */
+#include <dirent.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/ioctl.h>
+#include <sys/mman.h>
+#include <unistd.h>
+
+struct xnu_hostcall_xlate { uint64_t va, len, out, max; };
+#define XNU_HOSTCALL_XLATE _IOWR('X', 1, struct xnu_hostcall_xlate)
+
+static int hc, bad;
+
+static int xlate(void *va, uint64_t *pa)
+{
+ struct xnu_hostcall_xlate x = { (uintptr_t)va, 4096, (uintptr_t)pa, 1 };
+ return ioctl(hc, XNU_HOSTCALL_XLATE, &x) ? -errno : 0;
+}
+
+static void check(const char *what, void *va, uint64_t want)
+{
+ uint64_t pa = 0;
+ int r = xlate(va, &pa);
+ int ok = r == 0 && pa == want;
+
+ printf("%s: %s: XLATE %s %#llx, the kernel says %#llx\n", ok ? "ok" : "FAIL", what, r ? strerror(-r) : "gives",
+ (unsigned long long)pa, (unsigned long long)want);
+ if (!ok) bad = 1;
+}
+
+/* map the first page of a sysfs PCI resource file; *start: the BAR's address (line N of the device's `resource`) */
+static void *map_bar(const char *path, uint64_t *start)
+{
+ char res[512], line[128];
+ const char *n = strrchr(path, '/');
+ unsigned idx, i;
+ uint64_t s, e, fl;
+ void *va = MAP_FAILED;
+ FILE *f;
+ int fd;
+
+ if (!n || sscanf(n, "/resource%u", &idx) != 1 || (size_t)(n - path) + 10 > sizeof(res)) return MAP_FAILED;
+ memcpy(res, path, n - path);
+ strcpy(res + (n - path), "/resource");
+ if (!(f = fopen(res, "r"))) return MAP_FAILED;
+ for (i = 0; i <= idx; i++) if (!fgets(line, sizeof(line), f)) { fclose(f); return MAP_FAILED; }
+ fclose(f);
+ if (sscanf(line, "%llx %llx %llx", (unsigned long long *)&s, (unsigned long long *)&e, (unsigned long long *)&fl) != 3) return MAP_FAILED;
+ if (!s || !(fl & 0x200) || e - s + 1 < 4096) return MAP_FAILED; /* IORESOURCE_MEM, at least a page */
+ if ((fd = open(path, O_RDWR | O_SYNC)) < 0) return MAP_FAILED;
+ va = mmap(NULL, 4096, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
+ close(fd);
+ *start = s;
+ return va;
+}
+
+int main(int argc, char **argv)
+{
+ uint64_t e = 0, start = 0;
+ char path[512] = "";
+ void *va = MAP_FAILED, *page;
+ int pm;
+
+ hc = open("/dev/xnu-hostcall", O_RDWR);
+ if (hc < 0) { perror("/dev/xnu-hostcall (is fki.ko loaded, are you root?)"); return 2; }
+
+ page = mmap(NULL, 4096, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_POPULATE, -1, 0);
+ pm = open("/proc/self/pagemap", O_RDONLY);
+ if (page == MAP_FAILED || mlock(page, 4096) || pm < 0) { perror("a locked page and /proc/self/pagemap"); return 2; }
+ *(volatile char *)page = 1;
+ if (pread(pm, &e, 8, ((uintptr_t)page / 4096) * 8) != 8 || !(e >> 63) || !(e & ((1ULL << 55) - 1))) {
+ fprintf(stderr, "/proc/self/pagemap gives no page frame (not root?)\n"); return 2;
+ }
+ check("ordinary memory", page, (e & ((1ULL << 55) - 1)) << 12);
+
+ if (argc > 1) {
+ snprintf(path, sizeof(path), "%s", argv[1]);
+ va = map_bar(path, &start);
+ if (va == MAP_FAILED) { fprintf(stderr, "%s: cannot map it as a memory BAR (%s)\n", path, strerror(errno)); return 2; }
+ } else {
+ DIR *d = opendir("/sys/bus/pci/devices");
+ struct dirent *de;
+ while (d && va == MAP_FAILED && (de = readdir(d))) {
+ if (de->d_name[0] == '.') continue;
+ for (int i = 0; i < 6 && va == MAP_FAILED; i++) {
+ snprintf(path, sizeof(path), "/sys/bus/pci/devices/%s/resource%d", de->d_name, i);
+ va = map_bar(path, &start);
+ }
+ }
+ if (d) closedir(d);
+ }
+ if (va == MAP_FAILED) printf("skipped: a device mapping: no PCI memory BAR here that can be mapped (name one as the argument)\n");
+ else { printf("device mapping: %s\n", path); check("a device mapping", va, start); }
+ return bad;
+}