From ff792f6121a4e466f135340e653eea1797088853 Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Sat, 21 Nov 2026 17:38:25 +0000 Subject: [PATCH] gl: guest GL in unkernel behind createKernel({ gl }): the SDK loads the wasm renderer from dist (virgl.mjs, virgl.wasm), listens on vsock port 1019 and starts the vtest forwarder shipped in the base's kw layer; a prepared Debian disk and an end-to-end check in headless Chromium (eglinfo, frame checksums, glmark2 against llvmpipe) --- .agents/gl.md | 146 +++++++++++++++++-- .agents/js.md | 37 ++++- .agents/kernel/devices.md | 4 +- .agents/kernel/guest.md | 11 ++ .agents/testing.md | 6 +- .github/workflows/release.yml | 18 ++- README.md | 15 ++ build.config.ts | 29 +++- gl/bridge/README.md | 20 ++- gl/bridge/stream.js | 135 ------------------ gl/bridge/vtest-bridge.c | 106 ++++++++++++-- gl/wasm/epoxy/include/epoxy/gl.h | 5 + gl/wasm/kw_gl.js | 17 +++ guest/base/build.sh | 5 + js/core/gl-stream.ts | 182 ++++++++++++++++++++++++ js/core/gl.ts | 203 +++++++++++++++++++++++++++ js/core/index.ts | 4 + js/core/instance.ts | 33 +++++ js/core/worker-host.ts | 14 ++ js/virgl.mjs | 1 + js/virgl.wasm | 1 + js/web.ts | 10 +- js/web/platform.ts | 7 +- package.json | 2 + test/gl/build-guest-state.sh | 32 +++++ test/gl/debian-disk.mjs | 98 +++++++++++++ test/gl/stream-check.sh | 5 +- test/gl/stream-relay.js | 6 +- test/gl/unkernel-check.mjs | 231 +++++++++++++++++++++++++++++++ test/gl/unkernel-page.js | 98 +++++++++++++ test/gl/unkernel.html | 7 + 31 files changed, 1304 insertions(+), 184 deletions(-) delete mode 100644 gl/bridge/stream.js create mode 100644 js/core/gl-stream.ts create mode 100644 js/core/gl.ts create mode 120000 js/virgl.mjs create mode 120000 js/virgl.wasm create mode 100755 test/gl/build-guest-state.sh create mode 100755 test/gl/debian-disk.mjs create mode 100755 test/gl/unkernel-check.mjs create mode 100644 test/gl/unkernel-page.js create mode 100644 test/gl/unkernel.html diff --git a/.agents/gl.md b/.agents/gl.md index 9f91b7e..4ed2b36 100644 --- a/.agents/gl.md +++ b/.agents/gl.md @@ -1,9 +1,9 @@ -# Guest GL through virgl on WebGL2: handover +# Guest GL through virgl on WebGL2 -For an agent starting this work. Nothing here is integrated into unkernel -yet; this file is the plan, what was measured, and how to test. All work -happens on the `webgl` branch (this worktree). Do not change `main`, and do -not commit until asked. +The design, what was measured, how to test, and what is open. It is in +unkernel: `createKernel({ gl: true })` in a browser (unkernel, below). All +work happens on the `webgl` branch (this worktree). Do not change `main`, +and do not commit until asked. ## Goal @@ -12,8 +12,10 @@ kwemu. The guest runs stock Mesa with the `virgl` driver; the host runs virglrenderer compiled to wasm against one WebGL2 context. ``` -guest: app -> Mesa virgl -> vtest protocol -> (socket) ... -host: ... -> virglrenderer (wasm) -> WebGL2 (one context, OffscreenCanvas) +guest: app -> Mesa virgl (virpipe) -> /tmp/.virgl_test -> /usr/lib/kw/vtest-bridge + -> kwvsock, host CID 2, port 1019 ... +host: ... -> VsockHost -> StreamHost -> virglrenderer (wasm) -> WebGL2 + (one context, OffscreenCanvas, on the thread that owns the VM) ``` Decided, do not reopen without new facts: @@ -43,8 +45,13 @@ The guest sees GL 2.1 compatibility (GLSL 1.20) and GLES 3.0 (GLSL ES | `test/gl/vtest-check.sh` | the check suite on this host; see Testing | | `test/gl/bridge-check.sh` | the same suite with every byte through the page in headless Chromium; `--wasm` against the wasm renderer | | `test/gl/kwgl-state.c` | the stale-state check run by `vtest-check.sh state` (surfaceless EGL clients taking turns) | +| `js/core/gl.ts`, `gl-stream.ts` | the SDK's host side: `createKernel({ gl })`, `GlHost` (`vm.gl`), `StreamHost`; see unkernel | +| `test/gl/debian-disk.mjs` | makes the prepared data disk once (Mesa and the test programs installed in Debian's upper layer) | +| `test/gl/unkernel-check.mjs`, `unkernel.html`, `unkernel-page.js` | the whole path in unkernel in headless Chromium; see Testing | +| `test/gl/build-guest-state.sh` | `kwgl-state.c` for the Debian guest (aarch64 glibc, linked against stand-ins for libEGL and libGLESv2) | | `vendor/src/virglrenderer-wasm` (gitignored) | the source of both builds: branch `kw-wasm` = 1.3.0 + the series | | `vendor/build/gl-wasm`, `vendor/build/gl-native` | `virgl.{mjs,wasm}`; `vtest/virgl_test_server` | +| `vendor/build/gl/` | `debian-gl.img` (the prepared disk), `kwgl-state-aarch64`, `vtest-bridge` (`build-guest.sh`) | `vendor/` is not a record: commit on `kw-wasm` and re-export the series (`gl/wasm/build.sh` has the command). `build.sh` never re-applies an @@ -158,6 +165,11 @@ is made up at three levels, the shim first: base vertex is not known. - `glFramebufferTexture3D(OES)` as `framebufferTextureLayer` (3D mipmaps through the blitter), `glGetQueryObjectiv`. + - **Renderer name**: `glGetString(GL_RENDERER)` answers the unmasked name + (`WEBGL_debug_renderer_info`) where WebGL says "WebKit WebGL", so the + guest's renderer string, `virgl (...)` (vrend forwards GL_RENDERER in + the caps, 63 bytes at most), names the WebGL implementation: here + `virgl (ANGLE (Google, Vulkan 1.3.0 (SwiftShader Device (Sub...)`. - `epoxy/gl.h`: aliases (`glGetQueryObjecti64v`, `glQueryCounter` and others to emscripten's EXT names). - vrend patches: the sized probe format (8), texture swizzles in the @@ -267,6 +279,43 @@ eventfd. vtest forks one server process per client unless given `--no-fork`, also with `--multi-clients`; only `--no-fork` puts several clients on one renderer, as the page does. +### unkernel (2026-11-21, `unkernel-check.mjs`, headless Chromium 157) + +The guest is Debian 13 on the UP kernel (inline; worker mode passes (a) +and (b) the same), 1024 MiB, the prepared disk. The WebGL2 is ANGLE on +SwiftShader (software: every virgl number is a floor for a page with a +GPU). One run each, on the shared host: + +- `vm.gl.ready` 0.6 s after the page started (boot, module, forwarder + linked); `eglinfo -B -p surfaceless` on virgl 1.5 s: `virgl (ANGLE + (Google, Vulkan 1.3.0 (SwiftShader Device (Sub...)`, GLES 3.0 and GL 2.1 + (Mesa 25.0.7). +- `kwgl-state` (7 clients, 8 turns, 64x64): all 60 checksums of the + interleaved run equal each client's alone in the guest, and equal the + host's own run of the same clients through `bridge-check.sh --wasm + state` (x86 Mesa 26.2.7, the same renderer): the pixels are the + renderer's, whatever carried them. On llvmpipe in the guest 52 of 60 + differ (rounding, as against the native renderer). 3.2 s on virgl, 32.4 s + on llvmpipe. +- glmark2-es2 under Xvfb at 640x480, 10 s a scene, the same command with + and without `GALLIUM_DRIVER=virpipe` (FPS from glmark2's mean frame time): + + | Scene | virgl (WebGL2 on SwiftShader) | llvmpipe (in the guest, under kwemu) | Ratio | + | --- | --- | --- | --- | + | build | 93.2 | 4.30 | 22x | + | texture | 98.8 | 4.08 | 24x | + | shading (phong) | 91.9 | 0.82 | 112x | + | jellyfish | 69.8 | 0.32 | 218x | + | desktop | 38.2 | 0.16 | 239x | + + virgl here is as fast as Mesa on this host through the bridge's + WebSocket to the same renderer (Measured, above: build 90, texture 107, + jellyfish 84, desktop 37, also 640x480, 2 s a scene): the browser's + renderer bounds it, not the emulated guest or kwvsock. Each frame comes back to the guest + by readback and goes to Xvfb by XPutImage, for virgl and llvmpipe alike. +- The prepared disk: 290 MiB used of a 4 GiB sparse image; made in 55 s + (boot, apt over the direct network, power-off). + ## Work packages 1. **Single context, hardened (native).** Done: Single GL context. Check: @@ -278,12 +327,44 @@ clients on one renderer, as the page does. (below) would find the rest. 4. **Bridge and browser harness.** Done: `gl/bridge`, `bridge-check.sh` (relay or `--wasm`). -5. **unkernel.** Carry the vtest socket from the guest over kwvsock (the - bridge's stream link and its guest build, `gl/bridge/README.md`) to the - renderer in the page; confirm that the Debian image's Mesa has the virgl - driver with vtest (`GALLIUM_DRIVER=virpipe`); decide where the renderer - runs (it needs an OffscreenCanvas; the kernel runs in a worker). Frames - by readback at first; kwshm can carry them later. +5. **unkernel.** Done: unkernel, below. Check: `node test/gl/unkernel-check.mjs`. + Next: frames to the page (kwshm, or wland), the page's own `gl` + option (web/: it needs the module served and `glModule` passed), and + the busy wait (Open questions). + +## unkernel + +`createKernel({ gl: true })` (js.md, Guest GL; README.md): + +- **Host** (`js/core/gl.ts`): on the thread that owns the VM, in both + modes (vsock is served there: in worker mode the kernel's worker only + passes packets), the module is imported from `new URL("./virgl.mjs", + import.meta.url)` of the web entry (dist/virgl.mjs and virgl.wasm, + copied by `pnpm build`; never fetched without `gl`), the renderer is + `Module.virgl.Renderer` on a 1x1 OffscreenCanvas's WebGL2, and + `StreamHost` (`js/core/gl-stream.ts`) serves every connection to vsock + port 1019. Node: ignored with a log line (no OffscreenCanvas), unless + `gl.renderer` gives a renderer object (the relay works there). +- **Guest** (`/usr/lib/kw/vtest-bridge`, kernel/guest.md): the bridge + built stream-only, in the base's kw layer (in the bundle, so it always + matches the SDK that speaks its link; 67 KB of RAM-resident layer for + every distro, Alpine included, which cannot use it). The SDK starts it + through kwtty as root once the renderer is up (`bridge --link + vsock:2:1019 --daemon`); it makes `/tmp/.virgl_test` mode 0666 when the + host sends READY, and `vm.gl.ready` resolves on its LOG line saying so. +- **Mesa**: not in the image; `apt-get install mesa-utils libegl-mesa0 + libgles2` (surfaceless, about 45 MB download), plus `libgl1-mesa-dri + libglx-mesa0 xvfb xauth glmark2-es2-x11 glmark2-x11` for X11 (all of it: + 72 packages, 60 MB download, 238 MB installed). Debian trixie's Mesa + 25.0.7 has virpipe. Clients run with `GALLIUM_DRIVER=virpipe + LIBGL_ALWAYS_SOFTWARE=1`, surfaceless or under Xvfb; without + `GALLIUM_DRIVER` the same programs run on llvmpipe in the guest. +- **Snapshots**: renderer state is not saved. A restore resets the link + (GL clients in the guest end); the restored guest's forwarder + reconnects within a second and the new host's start of it exits 0. + Verified on Node with the relay renderer (2026-11-21): eglinfo on virgl + before the snapshot and after the restore, the same forwarder process. +- Alpine's Mesa has no virgl driver: Debian only. ## Testing @@ -296,8 +377,32 @@ test/gl/bridge-check.sh --single # the suite through the page to the test/gl/vtest-check.sh --single # the native server alone, about 2 min test/gl/vtest-check.sh --fork # a server process per client test/gl/vtest-check.sh --server "$(command -v virgl_test_server)" info es2 +test/gl/stream-check.sh state # the stream link (unix socket) to the relay +test/gl/stream-check.sh --guest state # the same through the guest's build under qemu-aarch64 +node test/gl/debian-disk.mjs # the prepared disk, once (skipped when it exists) +node test/gl/unkernel-check.mjs # unkernel in headless Chromium, about 4 min +node test/gl/unkernel-check.mjs --worker --skip c # worker mode, without the benchmark ``` +`unkernel-check.mjs` builds what it needs and skips what exists: `pnpm +build` (the page imports `/dist/web.mjs`; `--no-build` skips it), the +prepared disk `vendor/build/gl/debian-gl.img` (`debian-disk.mjs`: boots +Debian on Node with the direct network, apt-installs the packages of +unkernel above as root, powers off cleanly; delete it after a new Debian +image, since its upper layer belongs to the image it was made on), and +`kwgl-state` for the guest (`build-guest-state.sh`). It serves the Debian +image and the disk read-only with Range requests (the guest's writes stay +in the page's memory), and the page boots with `gl: true` and runs: (a) +`eglinfo -B -p surfaceless` on virpipe (the renderer must be `virgl +(...)`); (b) `kwgl-state` interleaved against each client alone, as +`vtest-check.sh state` judges it, and with `--state-ref FILE` (the +`state.txt` that `bridge-check.sh --wasm --keep state` keeps) against the +host's own run, plus the same clients on llvmpipe (reported, not judged); +its frames are written as PPM; (c) glmark2-es2 under Xvfb, the same scenes +at the same size on virgl and on llvmpipe (`--size`, `--scenes`). The +steps' output, the page's log and the guest's console go to `--out` +(default a new `/tmp/kwgl.*`). + Tests: `info` (versions), `es2` and `gl` (glmark2, 16 scenes each; the `.png` has a frame of each scene), `sdl` (neverball), `weston` (GL compositor with a GL client), `multi` (six clients at once), `state` @@ -326,6 +431,9 @@ Results (2026-11-21, the series of Patches): | `vtest-check.sh --single` | all pass, log clean | | `vtest-check.sh` (multi-context, one process) | all pass, log clean | | `vtest-check.sh --fork`, `--single --fork` | all pass; in some runs a client killed mid-command leaves a `VTEST_CLIENT_ERROR_COMMAND_DISPATCH` line | +| `stream-check.sh state`, `--guest state` | pass | +| `stream-check.sh info state` | state times out (its clients wait 120 s for replies the relay never brings), also at the commit before unkernel; `state` alone passes. Not examined | +| `unkernel-check.mjs` (inline; `--worker --skip c`) | all pass; Measured | Workloads that need no window system of ours (so nothing waits on wland): @@ -339,8 +447,16 @@ Workloads that need no window system of ours (so nothing waits on wland): ## Open questions -- Which worker hosts the renderer, and how its replies reach kwvsock. -- Readback cost per frame over kwvsock, and when to move it to kwshm. +- Readback cost per frame over kwvsock, and when to move it to kwshm: at + 640x480 the guest gets as many frames as a host client through the + bridge (unkernel, Measured), so kwvsock is not the limit on SwiftShader; + not measured with a GPU-backed WebGL2, where it may be. +- The page (web/) does not offer `gl` yet: it would need virgl.mjs served + with the page's assets and `glModule` passed to `webPlatform()`, and a + way to get Mesa (apt over Wisp works there; routes for deb.debian.org). +- Not tried in unkernel: the SMP kernel (`cpus` > 1; vsock and so GL stay + on the owner's thread, as on one CPU), Firefox and Safari (WebGL2 and + OffscreenCanvas in a page's main thread exist there), and a GPU. - The busy wait costs about 5 ms a frame (fence latency across tasks). Through the inline dialect a readback's data travels with its `TRANSFER_GET2` reply, which `glReadPixels` fills synchronously, so a diff --git a/.agents/js.md b/.agents/js.md index 2ca67a8..c5724ee 100644 --- a/.agents/js.md +++ b/.agents/js.md @@ -37,12 +37,20 @@ parts that are easy to get wrong. `vendor/build/bundle/unkernel.wasm` (the base bundle) goes along as `dist/unkernel.wasm` (export `unkernel/unkernel.wasm`), and the build fails if the bundle is missing. `js/unkernel.wasm` is a symlink to that - bundle. No distro image is in the package (Distro images, below). + bundle. No distro image is in the package (Distro images, below). The + guest GL renderer, `vendor/build/gl-wasm/virgl.mjs` and `virgl.wasm` + (`gl/wasm/build.sh`; `UNKERNEL_GL=dir` takes another build), goes along + the same way as `dist/virgl.mjs` and `dist/virgl.wasm` (exports + `unkernel/virgl.mjs`, `unkernel/virgl.wasm`; `js/virgl.mjs` and + `js/virgl.wasm` are symlinks), and the build fails without it. - The build checks that `dist/web.mjs` reaches no Node built-in, that each entry (not a shared chunk) computes `new URL("./unkernel.wasm", import.meta.url)`, and that `dist/node.mjs` and `dist/cli.mjs` compute the package root (`new URL("..", - import.meta.url)`, for `fetchDistro()`) themselves. + import.meta.url)`, for `fetchDistro()`) themselves. `dist/web.mjs` (not a + chunk) computes `new URL("./virgl.mjs", import.meta.url)`, no entry + imports `virgl.mjs` statically (only `createKernel({ gl })` imports it, + by that URL), and `dist/virgl.mjs` finds `virgl.wasm` next to itself. - It inlines the kernel workers (Packaging, below) and the CPU workers (`js/node/cpu-entry.ts`, started by `js/node/cpu.ts`, and `js/web/web-cpu-entry.ts`, started by `js/web/cpu.ts`; CPU threads, @@ -813,6 +821,31 @@ parts that are easy to get wrong. under test has no `wasm_driver_vsock_init` import; `UNKERNEL_TEST_KERNEL=path` runs the file against another bundle. +## Guest GL (`js/core/gl.ts`, `gl-stream.ts`) + +- `createKernel({ gl })` (gl.md has the whole path): `startGl()` makes a + `GlHost` (`vm.gl`) on the thread that owns the VM, in both modes, since + vsock is served there. It imports the platform's `virgl.mjs` (web entry: + `Platform.glModule`, `bundledGlUrl`; or `gl.module`), makes a WebGL2 + context on a 1x1 OffscreenCanvas and the module's `virgl.Renderer`, then + listens on vsock port 1019 (`GL_PORT`) and serves each connection with + `StreamHost`, then runs the guest's forwarder (`GL_FORWARDER`, + `--daemon`) through kwtty as root. `gl.ready` resolves once the + forwarder's LOG line "ready: vtest clients on ..." arrives (the guest's + vtest socket exists then), and rejects (logged) when the renderer or the + forwarder fails or the link does not come within 30 s. +- Where there is no OffscreenCanvas (Node) or no module (the page's + `web/src/sdk.ts` passes none), `gl` is ignored with a `[host]` log line + and `vm.gl` is undefined; `gl.renderer` (any object of the renderer + shape, `VtestRenderer`) works anywhere, which is how a Node run can + serve the guest with the relay to a native server. +- `StreamHost` (the far end of vtest-bridge's stream link; `test/gl/stream-relay.js` + uses it on Node) never holds up replies; it stops reading the link while + the renderer is busy, so vsock credit holds the guest's forwarder. + Renderer state is not in snapshots: a restore resets the link (the guest's + GL clients end), the forwarder in the restored guest reconnects by itself, + and the new host's forwarder start exits 0 (one already runs). + ## Programs on a pty or on pipes (`js/core/tty.ts`) - The host client of kwtty (`guest/src/kwtty.c`, `/usr/bin/kwtty diff --git a/.agents/kernel/devices.md b/.agents/kernel/devices.md index 2f15000..f0a06cd 100644 --- a/.agents/kernel/devices.md +++ b/.agents/kernel/devices.md @@ -153,7 +153,9 @@ lives in virtio_transport.c, so kwvsock has its own). - kw_defconfig: VSOCKETS, VSOCKETS_DIAG (`ss --vsock`), KWVSOCK, not VSOCKETS_LOOPBACK. - Guest tools (guest.md): `kwvsock`, `kwtty` (terminal sessions, programs - on pipes and TCP relays for the host, port 1022), `kw9p`. + on pipes and TCP relays for the host, port 1022), `kw9p`, and the guest + GL forwarder `/usr/lib/kw/vtest-bridge` (connects to host port 1019; + gl.md). ## kwshm (shared memory) diff --git a/.agents/kernel/guest.md b/.agents/kernel/guest.md index f83c2e7..350744a 100644 --- a/.agents/kernel/guest.md +++ b/.agents/kernel/guest.md @@ -52,6 +52,9 @@ base's busybox (`#!/run/kw-lower/bin/busybox sh`) and only gain features. SDK shipped with the kernel. `glimmer` is not in the layer: every distro build compiles it into its image (`install_common`, guest/lib/stage.sh), so the base shell has none. +- `/usr/lib/kw/vtest-bridge` (Guest tools, below): the guest GL forwarder, + in the layer for the same reason (its link protocol belongs to the SDK's + `gl` option). - `/usr/lib/kw/rc`: cgroup2, devpts, `/dev/shm`, `/run/lock`, the hostname (`/etc/hostname` unless empty or `localhost`, else `unkernel`), binfmt_misc and the WASI format (kwwasi), the console @@ -474,6 +477,14 @@ within what kwemu implements: check it with the coverage classifier NAME...` makes the links; the SDK runs it through kwtty. - `kwshm memfd SIZE [SEED]` and `kwshm export FILE` export a patterned memfd or a file and print its id. +- `/usr/lib/kw/vtest-bridge bridge --link vsock:2:1019 --daemon`: the guest + GL forwarder, `gl/bridge/vtest-bridge.c` built stream-only + (`-DVTEST_BRIDGE_STREAM_ONLY`, 67 KB; gl.md, gl/bridge/README.md): Mesa's + vtest socket `/tmp/.virgl_test` (mode 0666, made once the host's renderer + is ready) to the host's renderer on vsock port 1019, reconnecting every + second. `--daemon` returns once it holds its lock (an abstract socket + named after the vtest socket), so a second start exits 0. The SDK's `gl` + option runs it through kwtty as root. - `glimmer` is a small game for the display, keyboard and mouse at any size, with synthesised sound effects when there is a sound card (22050 Hz stereo through the raw ALSA ioctls, about 46 ms queued; M or Tab mutes, diff --git a/.agents/testing.md b/.agents/testing.md index d41d12c..4c6104b 100644 --- a/.agents/testing.md +++ b/.agents/testing.md @@ -26,6 +26,7 @@ Run the row for what you changed, and no more. | SMP code (`CONFIG_SMP` paths, per-CPU data, IPIs, CPU parking, `js/core/cpu.ts`; kernel/smp.md) | `kernel/build.sh smp` (after `kernel`, so that the bundle carries the patch); kwtest with `--cpus 2` (the SMP kernel from the bundle) and once with `--kernel vendor/build/kernel-smp/vmlinux32.wasm --initrd base-test` (one CPU); `zig build test -Dkwemu-atomics=true` after a kwemu change | | Bundle and kernel patch (`bundle.mjs`, `kwdiff.mjs`, `kpatch.ts`, `kremap.ts`) | `KPATCH_UP=vendor/build/kernel/vmlinux32.wasm KPATCH_SMP=vendor/build/kernel-smp/vmlinux32.wasm pnpm test:kpatch` | | Page (`web/`) | `pnpm typecheck:web`; `node --test web/test/open.test.ts`; `pnpm build:web` | +| Guest GL (`gl/`, `js/core/gl*.ts`, the forwarder; gl.md, Testing) | `node gl/wasm/test/check.mjs` (the module); `test/gl/stream-check.sh info state` (the stream link); `node test/gl/unkernel-check.mjs` (unkernel in headless Chromium; makes the prepared disk once) | The optional checks boot the same bundle as `pnpm test:api`, which already runs shell commands and `glimmer --test` inline and in worker mode (most of @@ -135,8 +136,9 @@ the SMP patch), then the distro images (`kernel/build.sh distro`: the Debian image boots on that bundle to make apt's cache, and the step fails if it was left out) and `distros.json`, which it checks against `include/kw_emu.h`'s ABI and the images (sha256, size, ids; exactly -alpine and debian, erofs). Network is needed only for the pinned -downloads. Then it runs kwtest with and without the JIT and on 2 CPUs, +alpine and debian, erofs), and the guest GL renderer the package carries +(`gl/wasm/build.sh`: emscripten and virglrenderer, pinned). Network is +needed only for the pinned downloads. Then it runs kwtest with and without the JIT and on 2 CPUs, and abitest on the UP kernel and on 2 CPUs (`--initrd base-test`, no distro), `pnpm typecheck` and `pnpm typecheck:web`, `pnpm test:kpatch`, the tty, http and 9p tests, `pnpm test:distro`, and kwtest and the api diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 83487e4..842cbf9 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -4,8 +4,9 @@ # Release: build everything from source (patched wasm-ld, the UP and SMP # kernels, the data disk template, the base bundle unkernel.wasm with its # SMP patch, the distro images alpine.erofs and debian.erofs and their -# index distros.json), smoke-test it, build and pack the npm package (the -# base bundle, no distro image), and for a release publish it to npm +# index distros.json) and the guest GL renderer (gl/wasm, virgl.wasm), +# smoke-test it, build and pack the npm package (the base bundle and the +# GL renderer, no distro image), and for a release publish it to npm # (trusted publishing, with provenance) and publish a GitHub release (a # normal one, marked latest, its notes a compare link from the previous # v* tag) with the npm tarball, unkernel.wasm, distros.json and the images @@ -137,7 +138,7 @@ jobs: sudo tee /etc/apt/sources.list.d/llvm-22.list >/dev/null sudo apt-get update -q sudo apt-get install -y -q --no-install-recommends \ - clang-22 lld-22 llvm-22 cmake ninja-build flex bison bc m4 e2fsprogs patch + clang-22 lld-22 llvm-22 cmake ninja-build flex bison bc m4 e2fsprogs patch meson pkg-config echo /usr/lib/llvm-22/bin >> "$GITHUB_PATH" - uses: mlugg/setup-zig@d1434d08867e3ee9daa34448df10607b98908d29 # v2.2.1 @@ -201,7 +202,7 @@ jobs: uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: vendor/downloads - key: downloads-${{ hashFiles('kernel/tools/env.sh', 'kernel/build.sh', 'guest/**/pins.sh') }} + key: downloads-${{ hashFiles('kernel/tools/env.sh', 'kernel/build.sh', 'guest/**/pins.sh', 'gl/wasm/pins.sh') }} restore-keys: downloads- # Exact key only: build.sh never re-applies the series on an existing @@ -310,6 +311,14 @@ jobs: console.log(`ok: abi ${j.abi}, ${j.base}, ${j.distros.map((d) => `${d.file} ${d.image}`).join(", ")}`); ' + # The guest GL renderer the package carries (dist/virgl.mjs and + # virgl.wasm): emscripten and virglrenderer, both pinned (gl/wasm/pins.sh; + # emscripten goes into the downloads cache). + - name: Build the GL renderer + run: | + gl/wasm/build.sh + ls -l vendor/build/gl-wasm/virgl.mjs vendor/build/gl-wasm/virgl.wasm + - name: Save downloads if: steps.downloads.outputs.cache-hit != 'true' uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 @@ -373,6 +382,7 @@ jobs: pnpm build ls -l dist/*.wasm cmp dist/unkernel.wasm vendor/build/bundle/unkernel.wasm + cmp dist/virgl.wasm vendor/build/gl-wasm/virgl.wasm # The api suite (~85 s) runs once, on the built package: the same code # as the sources, plus the packaging (its distro tests read # vendor/build/distro/alpine.erofs). diff --git a/README.md b/README.md index 96db885..b1f5ea6 100644 --- a/README.md +++ b/README.md @@ -493,6 +493,21 @@ mouse or tablet. `onInput` tells you when a program opens the keyboard and mouse; until then, send keys to the console. `readFrame()` waits for a fresh frame. +### GL in the guest (browsers) + +```js +const vm = await createKernel({ distro: "/distros/debian.erofs", gl: true }); +await vm.gl.ready; // the renderer runs and the guest is linked to it +await vm.exec("sudo", ["apt-get", "install", "-y", "mesa-utils", "libegl-mesa0", "libgles2"]); +const r = await vm.exec("sh", ["-c", "GALLIUM_DRIVER=virpipe LIBGL_ALWAYS_SOFTWARE=1 eglinfo -B -p surfaceless"]); +``` + +The guest's Mesa (Debian; its `virpipe` driver) renders through +virglrenderer compiled to wasm (`virgl.wasm`, loaded only with `gl`) on one +WebGL2 context of the page, and gets its frames back by readback: GL 2.1 +and GLES 3.0, surfaceless or under Xvfb. Node has no WebGL, so there `gl` +is ignored with a log line. + ### Run it in a worker ```js diff --git a/build.config.ts b/build.config.ts index 533b6a4..4c77de0 100644 --- a/build.config.ts +++ b/build.config.ts @@ -12,6 +12,12 @@ // no distro images (the Node entry and the CLI // download them: js/node/distro-fetch.ts, which // finds package.json with new URL("..", import.meta.url)) +// vendor/build/gl-wasm/virgl.{mjs,wasm} -> dist/virgl.{mjs,wasm} +// the guest GL renderer (gl/wasm/build.sh; UNKERNEL_GL=dir +// takes another build): the web entry finds it with +// new URL("./virgl.mjs", import.meta.url) and imports it +// only for createKernel({ gl }); virgl.mjs finds virgl.wasm +// next to itself // js/node/worker-entry.ts the kernel worker (createKernel({ worker: true })) on // js/web/web-worker-entry.ts Node and in browsers, each bundled into one minified ES // module and inlined as a string where js/node/worker.ts @@ -35,6 +41,8 @@ import { pathToFileURL } from "node:url"; import { defineBuildConfig } from "obuild/config"; const WASM = process.env.UNKERNEL_BUNDLE || "vendor/build/bundle/unkernel.wasm"; +const GL_DIR = process.env.UNKERNEL_GL || "vendor/build/gl-wasm"; +const GL_FILES = ["virgl.mjs", "virgl.wasm"]; /** * Worker entries and the module that starts each one with @@ -164,6 +172,10 @@ export default defineBuildConfig({ const st = await stat(wasm).catch(() => null); if (!st?.isFile()) throw new Error(`${WASM} is missing: build it first (kernel/build.sh all, or kernel/build.sh base once vmlinux32.wasm exists)`); + for (const f of GL_FILES) { + const gl = await stat(path.resolve(ctx.pkgDir, GL_DIR, f)).catch(() => null); + if (!gl?.isFile()) throw new Error(`${GL_DIR}/${f} is missing: build the guest GL renderer first (gl/wasm/build.sh)`); + } }, async rolldownConfig(config, ctx) { // dist/node.mjs, not dist/js/node.mjs. @@ -189,6 +201,7 @@ export default defineBuildConfig({ async end(ctx) { const dist = path.join(ctx.pkgDir, "dist"); await copyFile(path.resolve(ctx.pkgDir, WASM), path.join(dist, "unkernel.wasm")); + for (const f of GL_FILES) await copyFile(path.resolve(ctx.pkgDir, GL_DIR, f), path.join(dist, f)); // The files an entry loads (itself and its chunks) and its bare imports. const reach = async (entry: string) => { const files = new Map(), bare: Array<[string, string]> = []; @@ -238,15 +251,25 @@ export default defineBuildConfig({ const chunks = await readdir(path.join(dist, "_chunks")).catch(() => []); for (const c of chunks.filter((f) => f.endsWith(".mjs"))) { const code = await readFile(path.join(dist, "_chunks", c), "utf8"); - if (code.includes(`new URL("./unkernel.wasm"`) || code.includes(`new URL("..", import.meta.url)`)) - throw new Error(`dist/_chunks/${c} resolves unkernel.wasm or the package root itself (would resolve inside _chunks/)`); + if (code.includes(`new URL("./unkernel.wasm"`) || code.includes(`new URL("./virgl.mjs"`) || code.includes(`new URL("..", import.meta.url)`)) + throw new Error(`dist/_chunks/${c} resolves unkernel.wasm, virgl.mjs or the package root itself (would resolve inside _chunks/)`); } + // The GL renderer: located by the web entry itself, never loaded by an entry + // until createKernel({ gl }) asks for it (a dynamic import of that URL), and + // virgl.mjs finds virgl.wasm next to itself. + if (!web.files.get("web.mjs")!.includes(`new URL("./virgl.mjs", import.meta.url)`)) + throw new Error("dist/web.mjs does not locate virgl.mjs next to itself"); + for (const entry of ["node.mjs", "web.mjs", "cli.mjs"]) + for (const [file] of (await reach(entry)).files) + if (GL_FILES.includes(path.basename(file))) throw new Error(`dist/${entry} imports ${file} statically; the GL renderer must load only for createKernel({ gl })`); + if (!(await readFile(path.join(dist, "virgl.mjs"), "utf8")).includes(`new URL("virgl.wasm",import.meta.url)`)) + throw new Error("dist/virgl.mjs does not locate virgl.wasm next to itself (gl/wasm/build.sh: an ES module build)"); // Every entry links (a broken chunk split shows up as a missing export). for (const entry of ["node.mjs", "web.mjs"]) { const mod = await import(`${pathToFileURL(path.join(dist, entry)).href}?check=${Date.now()}`); if (typeof mod.createKernel !== "function") throw new Error(`dist/${entry} has no createKernel export`); } - console.log(`unkernel: dist/unkernel.wasm copied; web entry is free of Node imports; kernel, CPU and WASI program workers inlined; entries link; ${chunks.length} shared chunk(s)`); + console.log(`unkernel: dist/unkernel.wasm and the GL renderer (virgl.mjs, virgl.wasm) copied; web entry is free of Node imports; kernel, CPU and WASI program workers inlined; entries link; ${chunks.length} shared chunk(s)`); }, }, }); diff --git a/gl/bridge/README.md b/gl/bridge/README.md index 1c9c83d..e38b8cd 100644 --- a/gl/bridge/README.md +++ b/gl/bridge/README.md @@ -13,17 +13,16 @@ relay renderer (the stand-in): page -> WebSocket -> vtest-bridge helper -> unix socket -> virgl_test_server the stream link (the guest's, over kwvsock): Mesa -> unix socket -> vtest-bridge bridge --link vsock:2:PORT -> byte stream - -> StreamHost (stream.js) -> renderer + -> StreamHost (js/core/gl-stream.ts) -> renderer ``` | File | What | | --- | --- | | `vtest-bridge.c` | `bridge` mode: the vtest socket, fd termination, and the link to the far side: the page's WebSocket (and serves the page), or with `--link unix:PATH` or `vsock:CID:PORT` a byte stream it connects to; `helper` mode: the relay's far end against a real server | -| `build-guest.sh` | the guest's build: static aarch64-linux-musl, stream link only (`-DVTEST_BRIDGE_STREAM_ONLY`: no WebSocket, no helper, libc only) | +| `build-guest.sh` | the guest's build: static aarch64-linux-musl, stream link only (`-DVTEST_BRIDGE_STREAM_ONLY`: no WebSocket, no helper, libc only); the same build ships in the base's kw layer as `/usr/lib/kw/vtest-bridge` (`guest/base/build.sh`), which the SDK's `gl` option starts | | `index.html`, `main.js` | the page: connects back to the bridge, hosts one renderer: `?renderer=wasm` (the default; `./virgl.mjs` next to the page, or `?module=URL`) or `relay`; `?glcheck=1` logs every WebGL call that raises an error, `?glcount=1` the calls made most often | | `mux.js` | the WebSocket framing and a WebSocketStream wrapper | | `relay.js` | the stand-in renderer | -| `stream.js` | the stream link's far end: `StreamHost.serve(readable, writable)` drives a renderer from a bridge's stream given as web streams (a vsock connection in the SDK) | `test/gl/bridge-check.sh` builds and starts all of it and runs `test/gl/vtest-check.sh --socket` through it, with `--wasm` against the wasm @@ -31,7 +30,11 @@ renderer (the module from `vendor/build/gl-wasm` served next to the page), else against the relay. `test/gl/stream-check.sh` does the same through the stream link (a unix socket, `test/gl/stream-relay.js` with the relay renderer at its far end), with -`--guest` through the guest's build under qemu-aarch64. +`--guest` through the guest's build under qemu-aarch64. The stream link's +far end is the SDK's `StreamHost` (`js/core/gl-stream.ts`: +`StreamHost.serve(readable, writable)` drives a renderer from a bridge's +stream given as web streams, a vsock connection in the SDK), and +`test/gl/unkernel-check.mjs` runs the whole path in unkernel. ## No file descriptors: the inline dialect @@ -134,7 +137,14 @@ u32 length (little-endian, 5 + payload) | u32 client id | u8 type | payload Types, ids, chunking and READY are as on the WebSocket: the far side sends READY (id 0) when its renderer is up, and only then does the bridge create its vtest socket (default `/tmp/.virgl_test`, Mesa's default -`VTEST_SOCKET_NAME`). A length below 5 or above 512 MiB ends the link. The +`VTEST_SOCKET_NAME`; mode 0666, so that any user's clients connect). The +bridge sends its own log lines the other way as LOG messages (id 0), among +them `ready: vtest clients on PATH` once the socket exists, which the SDK +waits for. One bridge per vtest socket: it holds an abstract unix socket +named after it, and another bridge for the same path exits (with +`--daemon`, which forks into a session of its own with stdio on +/dev/null once it holds that lock, with 0, so starting it twice is +harmless). A length below 5 or above 512 MiB ends the link. The bridge connects again every second until it can, and again a second after the link closes, which takes its clients with it. Back pressure is the stream's own: the bridge stops reading Mesa clients while it has more than diff --git a/gl/bridge/stream.js b/gl/bridge/stream.js deleted file mode 100644 index ee950eb..0000000 --- a/gl/bridge/stream.js +++ /dev/null @@ -1,135 +0,0 @@ -// SPDX-License-Identifier: MIT -// Copyright (C) 2026 Pooya Parsa -// The far end of vtest-bridge's stream link (README.md, Stream framing): one -// byte stream carries every client of one bridge, each message after its u32 -// length. StreamHost.serve() takes that stream as web streams, which is what -// the unkernel SDK gives for a vsock connection (VsockConnection.readable -// and .writable), and drives one renderer of the shape in README.md, which -// may serve several streams (a bridge that reconnects). Universal: no Node -// or DOM APIs. -import { MUX, decode } from "./mux.js"; - -const MAX = 512 << 20; - -/** One message for the stream link: u32 length, u32 client id, u8 type, payload. */ -export function frame(type, id, payload) { - const n = 5 + (payload ? payload.length : 0); - const f = new Uint8Array(4 + n); - const v = new DataView(f.buffer); - v.setUint32(0, n, true); - v.setUint32(4, id, true); - f[8] = type; - if (payload) f.set(payload, 9); - return f; -} - -/** Cuts a byte stream into the link's messages (each without its length). */ -export class Deframer { - #b = new Uint8Array(1 << 16); - #r = 0; - #w = 0; - - push(chunk) { - if (this.#w + chunk.length > this.#b.length) { - this.#b.copyWithin(0, this.#r, this.#w); - this.#w -= this.#r; - this.#r = 0; - if (this.#w + chunk.length > this.#b.length) { - const b = new Uint8Array(Math.max(this.#b.length * 2, this.#w + chunk.length)); - b.set(this.#b.subarray(0, this.#w)); - this.#b = b; - } - } - this.#b.set(chunk, this.#w); - this.#w += chunk.length; - } - - /** The next whole message (a copy), or null. Throws on a length out of range. */ - next() { - if (this.#w - this.#r < 4) return null; - const n = new DataView(this.#b.buffer, this.#r, 4).getUint32(0, true); - if (n < 5 || n > MAX) throw new Error(`stream frame of ${n} bytes`); - if (this.#w - this.#r - 4 < n) return null; - const m = this.#b.slice(this.#r + 4, this.#r + 4 + n); - this.#r += 4 + n; - if (this.#r === this.#w) this.#r = this.#w = 0; - return m; - } -} - -export class StreamHost { - #renderer; - #routes = new Map(); // the renderer's client id -> { id: the stream's, send, mine } - #nextId = 1; - - /** renderer: initialized (init() settled); StreamHost takes its onreply and onclose. */ - constructor(renderer) { - this.#renderer = renderer; - renderer.onreply = (rid, bytes) => { - const r = this.#routes.get(rid); - if (r) r.send(MUX.DATA, r.id, bytes); - }; - renderer.onclose = (rid) => { - const r = this.#routes.get(rid); - if (!r) return; - this.#routes.delete(rid); - r.mine.delete(r.id); - r.send(MUX.CLOSE, r.id); - }; - } - - /** - * Serves one bridge until its stream ends; its clients are closed then. - * Tells the bridge at once that the renderer is ready (it creates its - * vtest socket on that). Rejects on a broken frame, after resetting the - * stream. log gets the bridge's LOG messages. - */ - async serve(readable, writable, { log = () => {} } = {}) { - const writer = writable.getWriter(); - const reader = readable.getReader(); - // The reply direction is never held up (README.md, back pressure). - const send = (type, id, payload) => writer.write(frame(type, id, payload)).catch(() => {}); - const mine = new Map(); // the stream's client id -> the renderer's - const deframer = new Deframer(); - send(MUX.READY, 0); - try { - for (;;) { - let m; - while ((m = deframer.next())) { - const { type, id, payload } = decode(m); - const rid = mine.get(id); - if (type === MUX.OPEN && rid === undefined) { - const r = this.#nextId++; - mine.set(id, r); - this.#routes.set(r, { id, send, mine }); - this.#renderer.open(r); - } else if (type === MUX.DATA && rid !== undefined) { - // busy: read no more from the stream, so its credit stops the bridge - const busy = this.#renderer.feed(rid, payload); - if (busy) await busy; - } else if (type === MUX.CLOSE && rid !== undefined) { - mine.delete(id); - this.#routes.delete(rid); - this.#renderer.close(rid); - } else if (type === MUX.LOG) { - log(new TextDecoder().decode(payload)); - } - } - const { value, done } = await reader.read(); - if (done) break; - deframer.push(value); - } - writer.close().catch(() => {}); - } catch (e) { - reader.cancel(e).catch(() => {}); - writer.abort(e).catch(() => {}); - throw e; - } finally { - for (const rid of mine.values()) { - this.#routes.delete(rid); - this.#renderer.close(rid); - } - mine.clear(); - } - } -} diff --git a/gl/bridge/vtest-bridge.c b/gl/bridge/vtest-bridge.c index e2ab239..cd44b8b 100644 --- a/gl/bridge/vtest-bridge.c +++ b/gl/bridge/vtest-bridge.c @@ -9,14 +9,21 @@ // connected and ready) and carries every client over one WebSocket to // the page, which connects to ws://127.0.0.1:N/. Plain GETs on the // same port serve the page from DIR. -// vtest-bridge bridge --link unix:PATH|vsock:CID:PORT [--socket PATH] +// vtest-bridge bridge --link unix:PATH|vsock:CID:PORT [--socket PATH] [--daemon] // The same with the far side on one connected byte stream in place of // the WebSocket: the guest's end of kwvsock in unkernel, a unix socket // for testing. It connects to the address (again every second while // it cannot, or after the link closes) and sends each WebSocket -// message there after its length (README.md, Stream framing). The -// vtest socket defaults to /tmp/.virgl_test, Mesa's default -// VTEST_SOCKET_NAME. +// message there after its length (README.md, Stream framing), and +// its log lines as LOG messages. The vtest socket defaults to +// /tmp/.virgl_test, Mesa's default VTEST_SOCKET_NAME. --daemon: once +// it holds the socket's lock, it goes on in the background (a new +// session, stdio on /dev/null) and the command exits 0. +// +// One bridge per vtest socket: a bridge holds an abstract unix socket named +// after its vtest socket while it runs, and another bridge for the same +// socket exits (0 with --daemon, so starting it is idempotent; else 1). +// The vtest socket is made mode 0666, so that any user's clients connect. // vtest-bridge helper --server PATH [--port N] [--port-file F] // Accepts the page's relay WebSocket and opens one connection to the // vtest server at PATH per client. @@ -47,6 +54,7 @@ #include #include #include +#include #include #include #include @@ -112,6 +120,7 @@ static bool helper_mode; static const char *sock_path, *server_path, *www_dir = ".", *port_file, *link_addr; static int tcp_port; static int verbose; +static bool daemonize; static double now(void) { @@ -120,14 +129,23 @@ static double now(void) return ts.tv_sec + ts.tv_nsec * 1e-9; } +static void link_log(const char *s, size_t n); + +// A log line to stderr and, on the stream link, to the far side as LOG (a +// daemon's stderr is /dev/null; the SDK logs what it gets). static void logf_(const char *fmt, ...) { + char line[1024]; va_list ap; - fprintf(stderr, "%s: ", helper_mode ? "helper" : "bridge"); va_start(ap, fmt); - vfprintf(stderr, fmt, ap); + int n = vsnprintf(line, sizeof(line), fmt, ap); va_end(ap); - fputc('\n', stderr); + if (n < 0) + return; + if ((size_t)n >= sizeof(line)) + n = sizeof(line) - 1; + fprintf(stderr, "%s: %s\n", helper_mode ? "helper" : "bridge", line); + link_log(line, n); } static void die(const char *what) @@ -246,6 +264,12 @@ static void link_send(uint8_t type, uint32_t id, const void *data, size_t len) #endif } +static void link_log(const char *s, size_t n) +{ + if (far && far->state == CONN_STREAM) + link_send(MUX_LOG, 0, s, n); +} + // ---- clients // What a request leaves the client waiting for, in order. @@ -780,6 +804,9 @@ static void start_unix(void) listen_unix = socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0); if (listen_unix < 0 || bind(listen_unix, (void *)&sa, sizeof(sa)) < 0 || listen(listen_unix, 64) < 0) die(sock_path); + // bind() made it with the umask; every user may connect (in the guest, + // any user's GL program, whoever started the bridge). + chmod(sock_path, 0666); logf_("ready: vtest clients on %s", sock_path); } @@ -1195,13 +1222,55 @@ static void on_signal(int sig) stop = 1; } +// The bridge's lock: an abstract unix socket named after the vtest socket, +// held until it exits. 0, 1 if another bridge holds it, -1 on an error. +static int instance_lock(void) +{ + struct sockaddr_un sa = { .sun_family = AF_UNIX }; + int n = snprintf(sa.sun_path + 1, sizeof(sa.sun_path) - 1, "vtest-bridge:%s", sock_path); + if (n < 0) + return -1; + if ((size_t)n > sizeof(sa.sun_path) - 1) + n = sizeof(sa.sun_path) - 1; + int fd = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0); + if (fd < 0) + return -1; + if (bind(fd, (void *)&sa, offsetof(struct sockaddr_un, sun_path) + 1 + n) < 0) { + int e = errno; + close(fd); + errno = e; + return e == EADDRINUSE ? 1 : -1; + } + return 0; // fd stays open: the lock +} + +// --daemon: the parent exits 0, the child goes on in a session of its own +// with stdio on /dev/null (it logs over the link). +static void go_background(void) +{ + pid_t pid = fork(); + if (pid < 0) + die("fork"); + if (pid > 0) + _exit(0); + setsid(); + if (chdir("/") < 0) + die("chdir"); + int fd = open("/dev/null", O_RDWR | O_CLOEXEC); + if (fd >= 0) { + dup2(fd, 0), dup2(fd, 1), dup2(fd, 2); + if (fd > 2) + close(fd); + } +} + static void usage(void) { #ifdef VTEST_BRIDGE_STREAM_ONLY - fprintf(stderr, "usage: vtest-bridge bridge --link unix:PATH|vsock:CID:PORT [--socket PATH] [-v]\n"); + fprintf(stderr, "usage: vtest-bridge bridge --link unix:PATH|vsock:CID:PORT [--socket PATH] [--daemon] [-v]\n"); #else fprintf(stderr, "usage: vtest-bridge bridge --socket PATH [--www DIR] [--port N] [--port-file F] [-v]\n" - " vtest-bridge bridge --link unix:PATH|vsock:CID:PORT [--socket PATH] [-v]\n" + " vtest-bridge bridge --link unix:PATH|vsock:CID:PORT [--socket PATH] [--daemon] [-v]\n" " vtest-bridge helper --server PATH [--port N] [--port-file F] [-v]\n"); #endif exit(2); @@ -1236,6 +1305,10 @@ int main(int argc, char **argv) verbose++; continue; } + if (!strcmp(o, "--daemon")) { + daemonize = true; + continue; + } if (!v) usage(); if (!strcmp(o, "--socket")) @@ -1266,6 +1339,21 @@ int main(int argc, char **argv) fprintf(stderr, "vtest-bridge: --link takes unix:PATH (under 108 bytes) or vsock:CID:PORT\n"); exit(2); } + if (daemonize && (helper_mode || !link_addr)) + usage(); + if (!helper_mode) { + int r = instance_lock(); + if (r < 0) { + fprintf(stderr, "vtest-bridge: lock: %s\n", strerror(errno)); + exit(1); + } + if (r > 0) { + fprintf(stderr, "vtest-bridge: a bridge already serves %s\n", sock_path); + exit(daemonize ? 0 : 1); + } + } + if (daemonize) + go_background(); signal(SIGPIPE, SIG_IGN); struct sigaction sa = { .sa_handler = on_signal }; diff --git a/gl/wasm/epoxy/include/epoxy/gl.h b/gl/wasm/epoxy/include/epoxy/gl.h index 4579bc9..f2cb500 100644 --- a/gl/wasm/epoxy/include/epoxy/gl.h +++ b/gl/wasm/epoxy/include/epoxy/gl.h @@ -48,6 +48,10 @@ #define glEndTransformFeedback kw_glEndTransformFeedback #define glPauseTransformFeedback kw_glPauseTransformFeedback +/* GL_RENDERER: the WebGL implementation's own name (kw_gl.js), which vrend + * forwards to the guest ("virgl (...)") in place of "WebKit WebGL". */ +#define glGetString kw_glGetString + #ifdef __cplusplus extern "C" { #endif @@ -66,6 +70,7 @@ void kw_glDrawRangeElements(GLenum mode, GLuint start, GLuint end, GLsizei count const void *indices); void kw_glEndTransformFeedback(void); void kw_glPauseTransformFeedback(void); +const GLubyte *kw_glGetString(GLenum name); bool epoxy_has_gl_extension(const char *extension); bool epoxy_is_desktop_gl(void); diff --git a/gl/wasm/kw_gl.js b/gl/wasm/kw_gl.js index 360c7d5..d175c6e 100644 --- a/gl/wasm/kw_gl.js +++ b/gl/wasm/kw_gl.js @@ -35,6 +35,10 @@ // base instance for instanced ones) and put back after. // framebuffers glFramebufferTexture3D(OES): framebufferTextureLayer. // queries glGetQueryObjectiv (WebGL2's getQueryParameter). +// renderer name glGetString(GL_RENDERER): WebGL answers "WebKit WebGL"; +// the unmasked name (WEBGL_debug_renderer_info) when the +// browser gives it, so the guest's "virgl (...)" names +// the WebGL implementation. addToLibrary({ $kwgl: { @@ -183,6 +187,19 @@ addToLibrary({ // --- buffer types --- + kw_glGetString__deps: ['$kwgl', 'glGetString', '$stringToNewUTF8'], + kw_glGetString: (name) => { + if (name === 0x1F01) { // GL_RENDERER + if (kwgl.renderer === undefined) { + const info = kwgl.ext('WEBGL_debug_renderer_info'); + const s = info && GLctx.getParameter(info.UNMASKED_RENDERER_WEBGL); + kwgl.renderer = s ? stringToNewUTF8(String(s)) : 0; + } + if (kwgl.renderer) return kwgl.renderer; + } + return _glGetString(name); + }, + kw_glBindBuffer__deps: ['$kwgl', 'glBindBuffer'], kw_glBindBuffer: (target, buffer) => { if (target !== kwgl.ELEMENT || !buffer) return _glBindBuffer(target, buffer); diff --git a/guest/base/build.sh b/guest/base/build.sh index fc7e73a..492026e 100755 --- a/guest/base/build.sh +++ b/guest/base/build.sh @@ -21,6 +21,9 @@ # usr/lib/kw/ (rc, welcome, net, udhcpc, shutdown, # data-stop: the runtime a distro's init calls; shrc: the kw-*.sh profile files for # interactive shells that are not login shells; +# vtest-bridge: gl/bridge/vtest-bridge.c, stream +# link only, the guest GL forwarder that the SDK's +# `gl` option starts; # shim and bin/: fx, claude, opencode, node, # npm, npx, bun, bunx, uv, uvx on first use), # etc/profile.d/{kw-path.sh,kw-term.sh}, the X.Org @@ -99,6 +102,8 @@ for t in kwvsock kwshm kwtty kw9p kwwasi kwcmd; do "${cc_guest[@]}" -o "$layer/usr/bin/$t" "$guest/src/$t.c" ln -s "/kw/layer/usr/bin/$t" "$stage/usr/bin/$t" # for the base shell done +# The guest GL forwarder (.agents/gl.md): vtest clients to the host's renderer over kwvsock. +"${cc_guest[@]}" -DVTEST_BRIDGE_STREAM_ONLY -o "$layer/usr/lib/kw/vtest-bridge" "$root/gl/bridge/vtest-bridge.c" install_tree "$src/rootfs" "$layer" ln -s /kw/layer/usr/sbin/kw-overlay "$stage/usr/sbin/kw-overlay" ln -s /kw/layer/usr/lib/kw "$stage/usr/lib/kw" diff --git a/js/core/gl-stream.ts b/js/core/gl-stream.ts new file mode 100644 index 0000000..c2ad5f7 --- /dev/null +++ b/js/core/gl-stream.ts @@ -0,0 +1,182 @@ +// SPDX-License-Identifier: MIT +// Copyright (C) 2026 Pooya Parsa +// The far end of vtest-bridge's stream link (gl/bridge/README.md, Stream +// framing): one byte stream carries every client of one bridge, each +// message after its u32 length. StreamHost.serve() takes that stream as web +// streams (a vsock connection's readable and writable: the SDK's `gl` +// option, gl.ts) and drives one renderer of the shape in gl/bridge/README.md +// (The renderer in the page), which may serve several streams (a bridge +// that reconnects). test/gl/stream-relay.js runs it on Node against the +// relay renderer. Universal: no Node or DOM APIs. + +/** The link's message types (gl/bridge/mux.js has the same for the WebSocket link). */ +export const MUX = { OPEN: 1, DATA: 2, CLOSE: 3, READY: 4, LOG: 5 } as const; + +const MAX = 512 << 20; + +/** + * A vtest renderer as gl/bridge/README.md describes it: the wasm module's + * `Module.virgl.Renderer` (gl/wasm/post.js), or the relay of the test pages. + */ +export interface VtestRenderer { + /** Once, before any client; resolves with a description. */ + init(): Promise; + /** A new client. */ + open(id: number): void; + /** The client's bytes, any chunking, in order; a promise: busy, feed no more until it settles. */ + feed(id: number, bytes: Uint8Array): unknown; + /** The client is gone: free its context and resources. */ + close(id: number): void; + /** Set by the host: reply bytes, in order. */ + onreply: (id: number, bytes: Uint8Array) => void; + /** Set by the host: the renderer dropped the client. */ + onclose: (id: number, why: string) => void; + /** How often and how long the client's busy waits were parked. */ + stats?(id: number): { parks: number; parkedMs: number } | undefined; +} + +/** One message for the stream link: u32 length, u32 client id, u8 type, payload. */ +export function frame(type: number, id: number, payload?: Uint8Array): Uint8Array { + const n = 5 + (payload ? payload.length : 0); + const f = new Uint8Array(4 + n); + const v = new DataView(f.buffer); + v.setUint32(0, n, true); + v.setUint32(4, id, true); + f[8] = type; + if (payload) f.set(payload, 9); + return f; +} + +/** Cuts a byte stream into the link's messages (each without its length). */ +export class Deframer { + #b = new Uint8Array(1 << 16); + #r = 0; + #w = 0; + + push(chunk: Uint8Array): void { + if (this.#w + chunk.length > this.#b.length) { + this.#b.copyWithin(0, this.#r, this.#w); + this.#w -= this.#r; + this.#r = 0; + if (this.#w + chunk.length > this.#b.length) { + const b = new Uint8Array(Math.max(this.#b.length * 2, this.#w + chunk.length)); + b.set(this.#b.subarray(0, this.#w)); + this.#b = b; + } + } + this.#b.set(chunk, this.#w); + this.#w += chunk.length; + } + + /** The next whole message (a copy), or null. Throws on a length out of range. */ + next(): Uint8Array | null { + if (this.#w - this.#r < 4) return null; + const n = new DataView(this.#b.buffer, this.#r, 4).getUint32(0, true); + if (n < 5 || n > MAX) throw new Error(`stream frame of ${n} bytes`); + if (this.#w - this.#r - 4 < n) return null; + const m = this.#b.slice(this.#r + 4, this.#r + 4 + n); + this.#r += 4 + n; + if (this.#r === this.#w) this.#r = this.#w = 0; + return m; + } +} + +type Send = (type: number, id: number, payload?: Uint8Array) => void; +interface Route { id: number; send: Send; mine: Map } + +export interface StreamHostStats { + /** Bridges being served now. */ + streams: number; + /** Clients open now, over all streams. */ + clients: number; + /** Clients opened since the start. */ + opened: number; +} + +export class StreamHost { + #renderer: VtestRenderer; + #routes = new Map(); // the renderer's client id -> the stream's + #nextId = 1; + #streams = 0; + #opened = 0; + + /** renderer: initialized (init() settled); StreamHost takes its onreply and onclose. */ + constructor(renderer: VtestRenderer) { + this.#renderer = renderer; + renderer.onreply = (rid, bytes) => { + const r = this.#routes.get(rid); + if (r) r.send(MUX.DATA, r.id, bytes); + }; + renderer.onclose = (rid) => { + const r = this.#routes.get(rid); + if (!r) return; + this.#routes.delete(rid); + r.mine.delete(r.id); + r.send(MUX.CLOSE, r.id); + }; + } + + get stats(): StreamHostStats { + return { streams: this.#streams, clients: this.#routes.size, opened: this.#opened }; + } + + /** + * Serves one bridge until its stream ends; its clients are closed then. + * Tells the bridge at once that the renderer is ready (it creates its + * vtest socket on that). Rejects on a broken frame, after resetting the + * stream. `log` gets the bridge's LOG messages. + */ + async serve(readable: ReadableStream, writable: WritableStream, { log = (_: string) => {} } = {}): Promise { + const writer = writable.getWriter(); + const reader = readable.getReader(); + // The reply direction is never held up (gl/bridge/README.md, back pressure). + const send: Send = (type, id, payload) => void writer.write(frame(type, id, payload)).catch(() => {}); + const mine = new Map(); // the stream's client id -> the renderer's + const deframer = new Deframer(); + const text = new TextDecoder(); + this.#streams++; + send(MUX.READY, 0); + try { + for (;;) { + let m: Uint8Array | null; + while ((m = deframer.next())) { + const v = new DataView(m.buffer, m.byteOffset, m.byteLength); + const id = v.getUint32(0, true), type = m[4]!, payload = m.subarray(5); + const rid = mine.get(id); + if (type === MUX.OPEN && rid === undefined) { + const r = this.#nextId++; + mine.set(id, r); + this.#routes.set(r, { id, send, mine }); + this.#opened++; + this.#renderer.open(r); + } else if (type === MUX.DATA && rid !== undefined) { + // busy: read no more from the stream, so its credit stops the bridge + const busy = this.#renderer.feed(rid, payload); + if (busy) await busy; + } else if (type === MUX.CLOSE && rid !== undefined) { + mine.delete(id); + this.#routes.delete(rid); + this.#renderer.close(rid); + } else if (type === MUX.LOG) { + log(text.decode(payload)); + } + } + const { value, done } = await reader.read(); + if (done) break; + deframer.push(value); + } + writer.close().catch(() => {}); + } catch (e) { + reader.cancel(e).catch(() => {}); + writer.abort(e).catch(() => {}); + throw e; + } finally { + this.#streams--; + for (const rid of mine.values()) { + this.#routes.delete(rid); + this.#renderer.close(rid); + } + mine.clear(); + } + } +} diff --git a/js/core/gl.ts b/js/core/gl.ts new file mode 100644 index 0000000..441a88c --- /dev/null +++ b/js/core/gl.ts @@ -0,0 +1,203 @@ +// SPDX-License-Identifier: MIT +// Copyright (C) 2026 Pooya Parsa +// Guest GL: createKernel({ gl: true }). The guest's Mesa (virgl driver over +// vtest, GALLIUM_DRIVER=virpipe) renders through virglrenderer compiled to +// wasm (gl/wasm) on one WebGL2 context of this thread, by readback: no +// window system. The pieces (.agents/gl.md): +// +// guest: GL program -> Mesa virpipe -> /tmp/.virgl_test +// -> /usr/lib/kw/vtest-bridge (the forwarder, in the base's kw layer) +// -> AF_VSOCK, host CID 2, port GL_PORT (1019) +// host: this thread's VsockHost -> StreamHost (gl-stream.ts) -> renderer +// (Module.virgl.Renderer of virgl.mjs, gl/wasm/post.js) -> WebGL2 +// +// GlHost loads the module (only now: users without `gl` never fetch it), +// makes the WebGL2 context on an OffscreenCanvas (1x1: every frame goes to +// the renderer's own framebuffers and back by readback), listens on the +// port once the renderer is up, and then starts the forwarder through kwtty +// as root (`vtest-bridge bridge --link vsock:2:1019 --daemon`, which exits +// at once when one already runs, as after a restore). The forwarder +// reconnects every second while the link is down, so a restored guest finds +// the new host by itself. Renderer state (the clients' GL contexts) is not +// in a snapshot: a restore resets the link, which ends the guest's GL +// clients. +// +// Both modes: vsock is served on the thread that owns the VM (worker mode +// too), so GL runs there, which must have OffscreenCanvas and WebGL2 (a +// page's main thread or a worker of the caller's). Where it has not (Node), +// `gl: true` is ignored with a log line, unless `renderer` gives one. + +import { PtyError } from "./tty.ts"; +import { StreamHost, type StreamHostStats, type VtestRenderer } from "./gl-stream.ts"; +import { guestRun } from "./mounts.ts"; +import type { Vsock, VsockConnection, VsockListener } from "./vsock.ts"; + +/** The vsock port the host's renderer listens on (the guest's forwarder connects to CID 2 there). */ +export const GL_PORT = 1019; +/** The guest's forwarder (gl/bridge/vtest-bridge.c, stream link only), in the base's kw layer. */ +export const GL_FORWARDER = "/usr/lib/kw/vtest-bridge"; + +const FORWARDER_TIMEOUT_MS = 120000; +const LINK_TIMEOUT_MS = 30000; + +export interface GlOptions { + /** + * The wasm renderer: the emscripten module virgl.mjs (with virgl.wasm + * next to it). Default: the one next to the SDK's web entry + * (dist/virgl.mjs, export `unkernel/virgl.mjs`). + */ + module?: string | URL; + /** + * A vtest renderer of your own (gl/bridge/README.md, The renderer in the + * page) in place of the wasm module, initialized here; works on any + * platform. + */ + renderer?: VtestRenderer; + /** + * Start the guest's forwarder (GL_FORWARDER) through kwtty once the + * renderer is up. Default true; false: start it yourself (`vtest-bridge + * bridge --link vsock:2:1019 --daemon`). + */ + forwarder?: boolean; +} + +/** createKernel's `gl`: true, or options. */ +export type GlOption = boolean | GlOptions; + +export interface GlStats extends StreamHostStats {} + +/** The host side of guest GL (KernelHandle.gl). */ +export class GlHost { + /** + * Resolves with the renderer's description once guest GL programs can + * run: the renderer is up, and (unless `forwarder: false`, which + * resolves once it listens) the guest's forwarder is linked and has made + * its vtest socket. Rejects if that cannot happen (also logged). + */ + readonly ready: Promise; + #vsock: Vsock; + #log: (msg: string) => void; + #host: StreamHost | undefined; + #listener: VsockListener | undefined; + #conns = new Set(); + #down = false; + #linked!: () => void; + + /** @internal Use createKernel({ gl }). */ + constructor(vsock: Vsock, opts: GlOptions, module: string | undefined, log: (msg: string) => void) { + this.#vsock = vsock; + this.#log = log; + this.ready = this.#start(opts, module); + this.ready.catch((e) => log(`[host] gl: ${(e as Error)?.message ?? e}; the guest gets no GL renderer`)); + } + + /** Bridges and clients being served. */ + get stats(): GlStats { + return this.#host?.stats ?? { streams: 0, clients: 0, opened: 0 }; + } + + async #start(opts: GlOptions, module: string | undefined): Promise { + const wasm = opts.renderer ? undefined : await wasmRenderer(module!, this.#log); + const renderer = opts.renderer ?? wasm!.renderer; + let what = await renderer.init(); + if (wasm) what += `; ${webglName(wasm.gl)}`; + if (this.#down) throw new Error("the kernel exited"); + this.#host = new StreamHost(renderer); + this.#listener = this.#vsock.listen(GL_PORT, (conn) => this.#serve(conn)); + this.#log(`[host] gl: ${what}, on vsock port ${GL_PORT}`); + if (opts.forwarder ?? true) { + // The forwarder logs this over the link once it has its vtest socket. + const linked = new Promise((r) => (this.#linked = r)); + await this.#startForwarder(); + let timer: ReturnType | undefined; + await Promise.race([linked, new Promise((_, rej) => (timer = setTimeout(() => + rej(new Error(`the guest's forwarder did not link within ${LINK_TIMEOUT_MS / 1000} s`)), LINK_TIMEOUT_MS)))]) + .finally(() => clearTimeout(timer)); + } + return what; + } + + #serve(conn: VsockConnection): void { + this.#conns.add(conn); + const log = (s: string) => { + this.#log(`[gl] ${s}`); + if (s.startsWith("ready: vtest clients on ")) this.#linked?.(); + }; + this.#host!.serve(conn.readable, conn.writable as WritableStream, { log }) + .catch((e) => { + if (!this.#down) this.#log(`[host] gl: the forwarder's link broke: ${(e as Error)?.message ?? e}`); + conn.reset(); + }) + .finally(() => this.#conns.delete(conn)); + } + + /** Runs the forwarder (it exits at once, in the background or because one runs); throws why it failed. */ + async #startForwarder(): Promise { + let r; + try { + r = await guestRun(this.#vsock, GL_FORWARDER, ["bridge", "--link", `vsock:2:${GL_PORT}`, "--daemon"], FORWARDER_TIMEOUT_MS); + } catch (e) { + const msg = (e as Error)?.message ?? String(e); + if (e instanceof PtyError && e.code === "EREMOTE" && /No such file/.test(msg)) + throw new Error(`the guest has no ${GL_FORWARDER} (a kernel bundle from before guest GL); start a forwarder yourself`, { cause: e }); + throw new Error(`cannot start the guest's forwarder: ${msg}`, { cause: e }); + } + if (r.exitCode !== 0) + throw new Error(`the guest's forwarder failed: ${r.stderr.trim() || `exit ${r.exitCode ?? `signal ${r.signal}`}`}`); + } + + /** @internal The kernel exited. */ + shutdown(): void { + this.#down = true; + this.#listener?.close(); + for (const c of this.#conns) c.reset(); + } +} + +/** The module's JS helpers (gl/wasm/post.js) that GlHost uses. */ +interface VirglModule { + virgl: { Renderer: new (gl: WebGL2RenderingContext) => VtestRenderer }; +} + +async function wasmRenderer(url: string, log: (msg: string) => void): Promise<{ renderer: VtestRenderer; gl: WebGL2RenderingContext }> { + if (typeof OffscreenCanvas !== "function") throw new Error("no OffscreenCanvas here, so no WebGL2"); + const mod = await import(/* @vite-ignore */ url) as { default: (o: object) => Promise }; + const say = (s: string) => log(`[gl] virgl: ${s}`); + const Module = await mod.default({ print: say, printErr: say }); + const gl = new OffscreenCanvas(1, 1).getContext("webgl2", { + alpha: false, depth: false, stencil: false, antialias: false, powerPreference: "high-performance", + }); + if (!gl) throw new Error("no WebGL2 context (OffscreenCanvas.getContext(\"webgl2\") gave none)"); + gl.canvas.addEventListener("webglcontextlost", () => log("[host] gl: the WebGL2 context was lost; GL clients will fail")); + return { renderer: new Module.virgl.Renderer(gl), gl }; +} + +/** The WebGL2 implementation's name (WEBGL_debug_renderer_info), for the log. */ +function webglName(gl: WebGL2RenderingContext): string { + const info = gl.getExtension("WEBGL_debug_renderer_info"); + return info ? String(gl.getParameter(info.UNMASKED_RENDERER_WEBGL)) : String(gl.getParameter(gl.RENDERER)); +} + +/** + * @internal createKernel's `gl` (both modes, on the thread that owns the + * VM): a GlHost, or undefined with a log line where GL cannot be had. + * `defaultModule` is the platform's virgl.mjs (web entry only). + */ +export function startGl(opt: GlOption | undefined, vsock: Vsock | undefined, defaultModule: URL | undefined, log: (msg: string) => void): GlHost | undefined { + if (!opt) return undefined; + const opts: GlOptions = opt === true ? {} : opt; + if (!vsock) { + log("[host] gl: needs the vsock device (vsock: false was given, or vsock.raw); the guest gets no GL renderer"); + return undefined; + } + const module = opts.module ?? defaultModule; + if (!opts.renderer && typeof OffscreenCanvas !== "function") { + log("[host] gl: no WebGL2 on this thread (no OffscreenCanvas; Node has none), so it is ignored; pass gl.renderer to use a renderer of your own"); + return undefined; + } + if (!opts.renderer && !module) { + log("[host] gl: no renderer module (this entry bundles none; pass gl.module, the URL of virgl.mjs), so it is ignored"); + return undefined; + } + return new GlHost(vsock, opts, module === undefined ? undefined : String(module), log); +} diff --git a/js/core/index.ts b/js/core/index.ts index a01ed5f..ce094af 100644 --- a/js/core/index.ts +++ b/js/core/index.ts @@ -47,6 +47,10 @@ export type { FsTree, FsTreeFile, MemoryFsChange } from "./memfs.ts"; export { MountError } from "./mounts.ts"; export type { FsSource, Mount, MountErrorCode, MountOptions, MountSpec, MountStats, MountsOption } from "./mounts.ts"; export { CMD_PORT, CommandError } from "./commands.ts"; +export { GL_FORWARDER, GL_PORT, GlHost } from "./gl.ts"; +export type { GlOption, GlOptions, GlStats } from "./gl.ts"; +export { Deframer, MUX, StreamHost, frame } from "./gl-stream.ts"; +export type { StreamHostStats, VtestRenderer } from "./gl-stream.ts"; export type { CommandErrorCode, CommandsOption, HostCommand, HostCommandContext, HostCommandResult } from "./commands.ts"; export { SHM_PAGE_SIZE, ShmClient, ShmDevice, ShmError, inlineShm } from "./shm.ts"; export type { InlineShmFile, Shm, ShmBackend, ShmCall, ShmCallResult, ShmCloseReason, ShmDeviceOptions, ShmDeviceStats, ShmFile, ShmInfo, ShmStats } from "./shm.ts"; diff --git a/js/core/instance.ts b/js/core/instance.ts index fd82cba..cd4cf7b 100644 --- a/js/core/instance.ts +++ b/js/core/instance.ts @@ -19,6 +19,7 @@ import { attachOn, connectOn, execOn, spawnOn, ttySessions, type AttachOptions, import { fetchOver } from "./http.ts"; import { CommandTable, parseCommands, type CommandsOption, type HostCommand } from "./commands.ts"; import { MountTable, parseMounts, snapshotMountMismatch, type FsSource, type Mount, type MountOptions, type MountsOption } from "./mounts.ts"; +import { startGl, type GlHost, type GlOption } from "./gl.ts"; import { Kernel, bundledBoot, moduleIsMemory64, type ExitResult, type KernelStats, type MemoryStage, type NetDevice } from "./kernel.ts"; import { BootError, loadBytes, loadKernelModule, type BytesSource, type DownloadProgress, type KernelSource } from "./load.ts"; import { NetStack, type NetBackend, type NetStats } from "./net.ts"; @@ -208,6 +209,19 @@ export interface CreateKernelOptions { * `restore`, the snapshot's links are replaced by these. */ commands?: CommandsOption; + /** + * Guest GL (gl.ts, .agents/gl.md): the guest's Mesa renders through + * virglrenderer compiled to wasm on one WebGL2 context of this thread + * (an OffscreenCanvas; frames come back to the guest by readback). The + * module (virgl.mjs and virgl.wasm next to the web entry) is loaded only + * then; the host listens on vsock port 1019 and starts the guest's + * forwarder (/usr/lib/kw/vtest-bridge) through kwtty, after which GL + * programs run with GALLIUM_DRIVER=virpipe LIBGL_ALWAYS_SOFTWARE=1 + * (Debian: Mesa from apt). true, or options. Needs vsock and WebGL2: + * where there is none (Node) it is ignored with a log line, unless + * `renderer` gives one. Default false. + */ + gl?: GlOption; /** Initial console size (cols x rows); resize() changes it later. */ consoleSize?: { cols: number; rows: number }; /** Console output, from the first byte. */ @@ -337,6 +351,8 @@ export interface Platform { distroSpec?: (src: string | URL) => DiskSpec; /** Start the profiler's time sampler thread (profile.ts); without it there are no time samples. */ spawnSampler?: (init: SamplerInit) => SamplerHandle; + /** The wasm GL renderer's module (virgl.mjs, the `gl` option); without it `gl` needs a module or a renderer. */ + glModule?: () => URL; } /** @@ -465,6 +481,8 @@ export interface KernelHandle { * "messages" or "shared" (worker mode; see WorkerOption.shared). */ readonly transport: KernelTransport; + /** With the gl option, where it could start: the renderer's host side (ready, stats); it runs on this thread in both modes. */ + readonly gl: GlHost | undefined; } function isBackend(n: NetDevice | NetBackend): n is NetBackend { @@ -495,6 +513,7 @@ export class KernelInstance implements KernelHandle { #shm: ShmClient | undefined; #mounts = new MountTable(undefined, () => {}); #commands = new CommandTable(undefined, () => {}); + #gl: GlHost | undefined; /** @internal Use createKernel(). */ constructor(kernel: Kernel, module: WebAssembly.Module, cmdline: string, net: NetDevice | undefined, compileMs: number) { @@ -506,6 +525,7 @@ export class KernelInstance implements KernelHandle { this.#out = new ConsoleOutput(() => !!kernel.result); if (kernel.shm.enabled) this.#shm = inlineShm(kernel.shm); this.exited = kernel.exited.then((res) => { + this.#gl?.shutdown(); this.#commands.shutdown(); this.#mounts.shutdown(); this.#vsock?.shutdown(); @@ -554,6 +574,17 @@ export class KernelInstance implements KernelHandle { this.#commands.addAll(list); } + /** @internal createKernel's `gl`, once the kernel runs. */ + attachGl(gl: GlHost | undefined): void { + this.#gl = gl; + if (gl && this.kernel.result) gl.shutdown(); + } + + /** With the gl option: the GL renderer's host side (gl.ts), or undefined. */ + get gl(): GlHost | undefined { + return this.#gl; + } + /** createKernel's `mounts` and `commands` first (see KernelHandle.spawn()). */ #gate(fn: () => Promise): Promise { return this.#mounts.gate(() => this.#commands.gate(fn)); @@ -854,6 +885,7 @@ export async function createKernelOn(platform: Platform, opts: CreateKernelOptio const vm = await createKernelInWorker(platform, opts, progress); vm.startMounts(mounts); vm.startCommands(commands); + vm.attachGl(startGl(opts.gl, vm.vsock, platform.glModule?.(), opts.log ?? ((m: string) => console.error(m)))); return vm; } const loadOpts = { signal, readFile: platform.readFile, onProgress: progress }; @@ -968,6 +1000,7 @@ export async function createKernelOn(platform: Platform, opts: CreateKernelOptio booting.catch(() => {}); instance.startMounts(rest); instance.startCommands(commands); + instance.attachGl(startGl(opts.gl, vsock, platform.glModule?.(), log)); if (signal) { const onAbort = () => instance.stop({ code: 130, reason: "aborted" }); if (signal.aborted) onAbort(); diff --git a/js/core/worker-host.ts b/js/core/worker-host.ts index e8eca1a..03c005b 100644 --- a/js/core/worker-host.ts +++ b/js/core/worker-host.ts @@ -23,6 +23,7 @@ import { attachOn, connectOn, execOn, spawnOn, ttySessions, type AttachOptions, import { fetchOver } from "./http.ts"; import { CommandTable, type HostCommand, type parseCommands } from "./commands.ts"; import { MountTable, type FsSource, type Mount, type MountOptions, type parseMounts } from "./mounts.ts"; +import type { GlHost } from "./gl.ts"; import { FrameClient, RemoteEvdev, SoundBridge } from "./worker-devices.ts"; import { SharedOwner, newSharedControl, sharedMemoryAvailable, type KernelTransport } from "./worker-shared.ts"; import type { CreateKernelOptions, InstanceStats, KernelHandle, Platform, BootProgress, VsockOption } from "./instance.ts"; @@ -202,6 +203,7 @@ export class WorkerKernel implements KernelHandle { #vsockOut: Uint8Array[] = []; #mounts: MountTable; #commands: CommandTable; + #gl: GlHost | undefined; #shm: ShmClient | undefined; #shmCalls = new Map void; reject: (e: Error) => void }>(); #nextShm = 1; @@ -450,6 +452,7 @@ export class WorkerKernel implements KernelHandle { this.#evdev?.close(); this.#frames?.close(); this.#shared?.close(); + this.#gl?.shutdown(); this.#commands.shutdown(); this.#mounts.shutdown(); this.#vsock?.shutdown(); @@ -672,6 +675,17 @@ export class WorkerKernel implements KernelHandle { this.#commands.addAll(list); } + /** @internal createKernel's `gl`, once the kernel runs: served on this thread, as vsock is. */ + attachGl(gl: GlHost | undefined): void { + this.#gl = gl; + if (gl && this.#result) gl.shutdown(); + } + + /** With the gl option: the GL renderer's host side (gl.ts), on this thread as inline. */ + get gl(): GlHost | undefined { + return this.#gl; + } + /** * With the shm option: open(), create() and openId() as inline. Each call * is a round trip to the worker, which runs it when the kernel next diff --git a/js/virgl.mjs b/js/virgl.mjs new file mode 120000 index 0000000..a19c9f0 --- /dev/null +++ b/js/virgl.mjs @@ -0,0 +1 @@ +../vendor/build/gl-wasm/virgl.mjs \ No newline at end of file diff --git a/js/virgl.wasm b/js/virgl.wasm new file mode 120000 index 0000000..4d0c706 --- /dev/null +++ b/js/virgl.wasm @@ -0,0 +1 @@ +../vendor/build/gl-wasm/virgl.wasm \ No newline at end of file diff --git a/js/web.ts b/js/web.ts index 365faa5..df07b5b 100644 --- a/js/web.ts +++ b/js/web.ts @@ -14,6 +14,7 @@ // term.onData((d) => vm.write(d)); // // Needs JSPI (WebAssembly.Suspending/promising); checkSupport() tells. +// `gl: true` gives the guest GL through WebGL2 (virgl.mjs, loaded only then). import { createKernelOn, type CreateKernelOptions, type KernelHandle, type KernelInstance, type WorkerOption } from "./core/instance.ts"; import type { WorkerKernel } from "./core/worker-host.ts"; @@ -34,7 +35,14 @@ export { serveWasiPrograms } from "./web/wasi.ts"; */ export const bundledKernelUrl: URL = new URL("./unkernel.wasm", import.meta.url); -const platform = webPlatform(bundledKernelUrl); +/** + * The guest GL renderer (createKernel({ gl: true })): virglrenderer compiled + * to wasm, an emscripten module with virgl.wasm next to it, both next to + * this module. Imported only when `gl` asks for it. + */ +export const bundledGlUrl: URL = new URL("./virgl.mjs", import.meta.url); + +const platform = webPlatform(bundledKernelUrl, bundledGlUrl); /** * Load, compile and boot a kernel (default: the bundled one, which boots diff --git a/js/web/platform.ts b/js/web/platform.ts index e300db4..dbcc033 100644 --- a/js/web/platform.ts +++ b/js/web/platform.ts @@ -10,7 +10,8 @@ // or a worker of the caller's own; never on the page's main thread // (webCpuBlocker()). // The entry (web.ts, or the page's web/src/sdk.ts) passes the -// default kernel's URL, so `new URL(..., import.meta.url)` stays in it. +// default kernel's URL and the GL renderer's (web.ts only), so +// `new URL(..., import.meta.url)` stays in it. import type { Platform } from "../core/instance.ts"; import { DEFAULT_MEMORY_FALLBACK_MIB, autoMemoryMiB } from "./memory.ts"; @@ -18,9 +19,11 @@ import { spawnWebCpu, webCpuBlocker } from "./cpu.ts"; import { webDevices } from "./devices.ts"; import { spawnWebWorker } from "./worker.ts"; -export function webPlatform(defaultKernel: URL): Platform { +export function webPlatform(defaultKernel: URL, glModule?: URL): Platform { return { defaultKernel: () => defaultKernel, + // The `gl` option's renderer (virgl.mjs), imported only when asked for. + glModule: glModule && (() => glModule), defaultMemoryMiB: () => autoMemoryMiB().mib, defaultMemoryFallbackMiB: [...DEFAULT_MEMORY_FALLBACK_MIB], spawnWorker: spawnWebWorker, diff --git a/package.json b/package.json index 79b69af..cc468d6 100644 --- a/package.json +++ b/package.json @@ -30,6 +30,8 @@ "default": "./dist/web.mjs" }, "./unkernel.wasm": "./dist/unkernel.wasm", + "./virgl.mjs": "./dist/virgl.mjs", + "./virgl.wasm": "./dist/virgl.wasm", "./package.json": "./package.json" }, "types": "./dist/node.d.mts", diff --git a/test/gl/build-guest-state.sh b/test/gl/build-guest-state.sh new file mode 100755 index 0000000..d0ce9dd --- /dev/null +++ b/test/gl/build-guest-state.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +# SPDX-License-Identifier: GPL-2.0-or-later +# Copyright (C) 2026 Pooya Parsa +# Builds kwgl-state.c for the Debian guest (aarch64, glibc), for +# unkernel-check.mjs: zig cc with this host's EGL and GLES headers, linked +# against stand-ins for libEGL.so.1 and libGLESv2.so.2 made here from the +# symbols it uses, so the guest's own libraries (glvnd, Mesa) serve it at +# run time and the build needs nothing of Debian's. +# +# test/gl/build-guest-state.sh [OUT] (default: $build/gl/kwgl-state-aarch64) +set -eu +. "$(cd "$(dirname "$0")/../.." && pwd)/guest/lib/env.sh" +need_zig +out=${1:-$build/gl/kwgl-state-aarch64} +for d in EGL GLES2 GLES3 KHR; do + [ -d "/usr/include/$d" ] || { echo "no /usr/include/$d (EGL and GLES development headers)" >&2; exit 2; } +done +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT +mkdir -p "$work/inc" "$(dirname "$out")" +cp -r /usr/include/EGL /usr/include/GLES2 /usr/include/GLES3 /usr/include/KHR "$work/inc/" +cc=("$zig" cc -target aarch64-linux-gnu.2.36 -mcpu=generic "-ffile-prefix-map=$root/=") +"${cc[@]}" -O2 -Wall -I "$work/inc" -c "$root/test/gl/kwgl-state.c" -o "$work/kwgl-state.o" +syms=$(nm -u "$work/kwgl-state.o" | awk '{ print $2 }') +stub() { # soname, symbol prefix + grep "^$2" <<<"$syms" | sed 's/$/(void) {}/; s/^/void /' >"$work/$1.c" + "${cc[@]}" -shared -nostdlib -Wl,-soname,"$1" -o "$work/$1" "$work/$1.c" +} +stub libEGL.so.1 egl +stub libGLESv2.so.2 gl +"${cc[@]}" -s -o "$out" "$work/kwgl-state.o" "$work/libEGL.so.1" "$work/libGLESv2.so.2" +echo "$out" diff --git a/test/gl/debian-disk.mjs b/test/gl/debian-disk.mjs new file mode 100755 index 0000000..df288bd --- /dev/null +++ b/test/gl/debian-disk.mjs @@ -0,0 +1,98 @@ +#!/usr/bin/env node +// SPDX-License-Identifier: MIT +// Copyright (C) 2026 Pooya Parsa +// The prepared data disk of the guest GL tests (unkernel-check.mjs): a data +// disk (.agents/data-disk.md) whose Debian upper layer has Mesa and the GL +// test programs installed, so that test runs download nothing. Made once: +// boots the Debian image on Node with the guest network (the SDK's direct +// backend), apt-installs the packages below as root, powers off cleanly and +// renames the image into place. Skipped when the image exists (delete it to +// make it again, e.g. after a new Debian image: the upper layer belongs to +// the image it was made on). +// +// node test/gl/debian-disk.mjs [--out FILE] [--kernel unkernel.wasm] [--distro debian.erofs] +// +// Default out: $KW_BUILD/gl/debian-gl.img (vendor/build). The packages: +// surfaceless EGL (eglinfo, libEGL and libGLESv2 for kwgl-state) and X11 +// (Xvfb, glmark2 for GLES 2 and GL). +import { existsSync, mkdirSync, renameSync, rmSync, statSync, readFileSync } from "node:fs"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { createImageFromKwsparse, createKernel } from "../../js/node.ts"; + +export const GL_PACKAGES = [ + "mesa-utils", "libegl-mesa0", "libgles2", + "libgl1-mesa-dri", "libglx-mesa0", "xvfb", "xauth", "glmark2-es2-x11", "glmark2-x11", +]; + +const here = dirname(fileURLToPath(import.meta.url)); +const root = resolve(here, "../.."); +const build = process.env.KW_BUILD ? resolve(process.env.KW_BUILD) : join(root, "vendor/build"); +const args = process.argv.slice(2); +const opt = (name, dflt) => { + const i = args.indexOf(name); + return i >= 0 ? args[i + 1] : dflt; +}; +const out = resolve(opt("--out", join(build, "gl/debian-gl.img"))); +const kernel = opt("--kernel"); +const distro = resolve(opt("--distro", join(build, "distro/debian.erofs"))); + +if (existsSync(out)) { + console.log(`${out} exists (${(statSync(out).blocks * 512 / 1048576).toFixed(0)} MiB used); delete it to make it again`); + process.exit(0); +} +if (!existsSync(distro)) { + console.error(`no ${distro} (kernel/build.sh distro debian)`); + process.exit(2); +} +mkdirSync(dirname(out), { recursive: true }); +const tmp = `${out}.tmp`; +rmSync(tmp, { force: true }); +const t0 = performance.now(); +const secs = () => ((performance.now() - t0) / 1000).toFixed(0); +await createImageFromKwsparse(tmp, readFileSync(join(build, "disk/kwdata.kwsparse.gz"))); + +const vm = await createKernel({ + ...(kernel ? { kernel: resolve(kernel) } : {}), + distro, + disks: [{ kind: "file", path: tmp }], + net: { kind: "net", backend: { kind: "direct" } }, + memoryMiB: 1024, +}); +vm.onOutput((b) => process.stderr.write(b)); +// apt as the image's kw-apt-install does it: the image's package lists +// first, fetched again if a version is gone from the mirror. +const script = `set -e +export DEBIAN_FRONTEND=noninteractive +inst() { apt-get install -y -q --no-install-recommends ${GL_PACKAGES.join(" ")} /dev/null || { echo "missing: $c"; exit 1; }; done +ls /usr/lib/aarch64-linux-gnu/dri/ | grep -c . >/dev/null +sync`; +let code = 1; +try { + const r = await vm.exec("bash", ["-c", script], { user: "root", timeout: 3 * 3600_000 }); + process.stdout.write(r.stdout); + process.stderr.write(r.stderr); + code = r.exitCode ?? 1; + console.log(`[gl-disk] apt-get finished with ${code} after ${secs()} s`); +} catch (e) { + console.error(`[gl-disk] ${e?.message ?? e}`); +} +// A clean shutdown: the base stops the overlay and syncs the data disk. +vm.write("sudo poweroff\n"); +const res = await Promise.race([vm.exited, new Promise((r) => setTimeout(() => r(null), 120_000))]); +if (!res) { + console.error("[gl-disk] no power-off within 120 s"); + await vm.stop(); + code = 1; +} +if (code !== 0) { + rmSync(tmp, { force: true }); + console.error(`[gl-disk] failed after ${secs()} s`); + process.exit(1); +} +renameSync(tmp, out); +console.log(`[gl-disk] ${out}: ${(statSync(out).blocks * 512 / 1048576).toFixed(0)} MiB used (sparse, ${statSync(out).size / 1048576} MiB), made in ${secs()} s`); +process.exit(0); diff --git a/test/gl/stream-check.sh b/test/gl/stream-check.sh index 387ec47..dfca71c 100755 --- a/test/gl/stream-check.sh +++ b/test/gl/stream-check.sh @@ -5,7 +5,7 @@ # link the guest's bridge uses over kwvsock (a unix socket here): # # Mesa -> unix socket -> vtest-bridge bridge --link unix:... -> stream -# -> stream-relay.js (gl/bridge/stream.js, the relay renderer) +# -> stream-relay.js (js/core/gl-stream.ts, the relay renderer) # -> WebSocket -> vtest-bridge helper -> unix socket -> virgl_test_server # # test/gl/stream-check.sh [--server PATH] [--single] [--loose] [--keep] @@ -106,7 +106,8 @@ report() { # name, unexpected lines routine='listening on\|page connected\|link connected\|ready: vtest clients\|: open$\|hung up\|closed after' report bridge-log "$(grep -v "$routine" "$work/bridge.log")" report helper-log "$(grep -v "$routine" "$work/helper.log")" -report relay-log "$(grep -v 'stream-relay: renderer: relay\|listening on\|bridge connected' "$work/relay.log")" +# (the bridge's own lines come over the link too, as "bridge: ...") +report relay-log "$(grep -v 'stream-relay: renderer: relay\|bridge connected' "$work/relay.log" | grep -v "$routine")" report server-log "$(log_errors "$work/server.log")" [ $fails = 0 ] || keep=1 exit $((fails > 0)) diff --git a/test/gl/stream-relay.js b/test/gl/stream-relay.js index 69e101a..1e070ca 100644 --- a/test/gl/stream-relay.js +++ b/test/gl/stream-relay.js @@ -2,8 +2,8 @@ // Copyright (C) 2026 Pooya Parsa // The far end of vtest-bridge's stream link on this host, for // stream-check.sh: accepts bridges on a unix socket and serves each with -// gl/bridge/stream.js (as the page will serve the guest's vsock connection) -// and the relay renderer (gl/bridge/relay.js), which carries every client +// the SDK's StreamHost (js/core/gl-stream.ts, which serves the guest's vsock +// connection for the `gl` option) and the relay renderer (gl/bridge/relay.js), which carries every client // over a WebSocket to `vtest-bridge helper` and on to virgl_test_server. // // node test/gl/stream-relay.js --listen PATH --relay ws://127.0.0.1:PORT/ @@ -11,7 +11,7 @@ import { unlinkSync } from "node:fs"; import net from "node:net"; import { Duplex } from "node:stream"; import { RelayRenderer } from "../../gl/bridge/relay.js"; -import { StreamHost } from "../../gl/bridge/stream.js"; +import { StreamHost } from "../../js/core/gl-stream.ts"; const args = process.argv.slice(2); const opt = (name) => { diff --git a/test/gl/unkernel-check.mjs b/test/gl/unkernel-check.mjs new file mode 100755 index 0000000..67ab904 --- /dev/null +++ b/test/gl/unkernel-check.mjs @@ -0,0 +1,231 @@ +#!/usr/bin/env node +// SPDX-License-Identifier: MIT +// Copyright (C) 2026 Pooya Parsa +// Guest GL end to end in headless Chromium: unkernel (the built package, +// dist/) boots Debian with the prepared data disk (debian-disk.mjs: Mesa +// from apt, made once) and createKernel({ gl: true }), whose wasm renderer +// runs on the page's WebGL2 (ANGLE on SwiftShader here, software: the virgl +// numbers are a floor) and whose forwarder the SDK starts in the guest. The +// page (unkernel-page.js) runs, in the guest: +// +// a eglinfo -B -p surfaceless on virpipe: the renderer must be virgl +// b kwgl-state.c (built for the guest by build-guest-state.sh): seven +// clients with different GL state interleaved on the page's renderer, +// whose 60 frame checksums must equal those of each client run alone +// (as vtest-check.sh state); with --state-ref FILE (a state.txt of +// `test/gl/bridge-check.sh --wasm --keep state` on this host) they +// must also equal the host's; the same clients on llvmpipe are +// reported, not judged (another rasterizer rounds differently) +// c glmark2-es2 under Xvfb, the same scenes at the same size, on +// llvmpipe and on virgl: FPS of each (default 640x480; build, texture, +// shading=phong, jellyfish and desktop, 10 s each; --scenes takes a +// comma-separated list of glmark2 -b values) +// +// node test/gl/unkernel-check.mjs [--worker] [--size WxH] [--scenes LIST] [--skip a,b,c] +// [--state-ref FILE] [--out DIR] [--browser BIN] [--timeout S] [--no-build] +// +// Builds first, each skipped when done: dist (pnpm build, unless +// --no-build), the disk ($KW_BUILD/gl/debian-gl.img), kwgl-state for the +// guest. Exit 0 when every step run passed, 1 on a failure, 2 when it could +// not run. Writes the steps' output, the frames (PPM), the page's log and +// the guest's console to --out (default a new /tmp/kwgl.* directory, +// printed). The images are served read-only with Range support; the +// guest's writes stay in the page's memory. +import { spawn, spawnSync } from "node:child_process"; +import { appendFileSync, createReadStream, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { createServer } from "node:http"; +import { dirname, join, normalize, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +const here = dirname(fileURLToPath(import.meta.url)); +const root = resolve(here, "../.."); +const build = process.env.KW_BUILD ? resolve(process.env.KW_BUILD) : join(root, "vendor/build"); +const args = process.argv.slice(2); +const opt = (name, dflt) => { + const i = args.indexOf(name); + return i >= 0 ? args[i + 1] : dflt; +}; +const has = (name) => args.includes(name); +const timeout = Number(opt("--timeout", "3600")) * 1000; +const browser = opt("--browser", process.env.CHROMIUM || "chromium-headless"); +const out = resolve(opt("--out", "") || mkdtempSync("/tmp/kwgl.")); +mkdirSync(out, { recursive: true }); +const disk = join(build, "gl/debian-gl.img"); +const distro = join(build, "distro/debian.erofs"); +const stateBin = join(build, "gl/kwgl-state-aarch64"); + +const step = (what, cmd, cmdArgs) => { + console.log(`== ${what}`); + const r = spawnSync(cmd, cmdArgs, { cwd: root, stdio: "inherit" }); + if (r.status !== 0) { + console.error(`${what} failed`); + process.exit(2); + } +}; +if (!existsSync(distro)) { + console.error(`no ${distro} (kernel/build.sh distro debian)`); + process.exit(2); +} +if (!has("--no-build")) step("pnpm build", "pnpm", ["build"]); +if (!existsSync(join(root, "dist/web.mjs")) || !existsSync(join(root, "dist/virgl.wasm"))) { + console.error("no dist/web.mjs or dist/virgl.wasm (pnpm build)"); + process.exit(2); +} +step("the prepared disk", process.execPath, [join(here, "debian-disk.mjs"), "--out", disk]); +if (!existsSync(stateBin)) step("kwgl-state for the guest", join(here, "build-guest-state.sh"), [stateBin]); + +const types = { ".html": "text/html", ".mjs": "text/javascript", ".js": "text/javascript", ".wasm": "application/wasm" }; +let resolveResult; +const result = new Promise((r) => (resolveResult = r)); +const pageLog = join(out, "page.log"), consoleLog = join(out, "console.log"); +writeFileSync(pageLog, ""); +writeFileSync(consoleLog, ""); + +// A file with Range support (one range; HttpBase asks for nothing else). +function sendFile(req, res, file, type) { + const st = statSync(file); + const etag = `"${st.size.toString(16)}-${Math.floor(st.mtimeMs).toString(16)}"`; + const h = { "content-type": type, "accept-ranges": "bytes", etag, "cache-control": "no-cache" }; + const m = /^bytes=(\d*)-(\d*)$/.exec(req.headers.range || ""); + let start = 0, end = st.size - 1, status = 200; + if (m && (m[1] || m[2])) { + if (m[1]) { + start = Number(m[1]); + if (m[2]) end = Math.min(Number(m[2]), st.size - 1); + } else start = Math.max(0, st.size - Number(m[2])); + if (start >= st.size || start > end) { + res.writeHead(416, { "content-range": `bytes */${st.size}`, etag }); + res.end(); + return; + } + status = 206; + h["content-range"] = `bytes ${start}-${end}/${st.size}`; + } + h["content-length"] = String(end - start + 1); + res.writeHead(status, h); + if (req.method === "HEAD") res.end(); + else createReadStream(file, { start, end }).pipe(res); +} + +const server = createServer(async (req, res) => { + const url = new URL(req.url, "http://x"); + const p = decodeURIComponent(url.pathname); + if (req.method === "POST") { + const chunks = []; + for await (const c of req) chunks.push(c); + const body = Buffer.concat(chunks); + res.end("ok"); + if (p === "/log") { + appendFileSync(pageLog, body + "\n"); + console.log(`page: ${body}`); + } else if (p === "/console") appendFileSync(consoleLog, body); + else if (p.startsWith("/file/") && /^[\w.-]+$/.test(p.slice(6))) writeFileSync(join(out, p.slice(6)), body); + else if (p === "/result") resolveResult(body.toString()); + return; + } + if (p === "/img/debian.erofs") return sendFile(req, res, distro, "application/octet-stream"); + if (p === "/img/debian-gl.img") return sendFile(req, res, disk, "application/octet-stream"); + if (p === "/files/kwgl-state") return sendFile(req, res, stateBin, "application/octet-stream"); + for (const [prefix, dir] of [["/dist/", join(root, "dist")], ["/test/", here]]) { + if (!p.startsWith(prefix)) continue; + const rel = normalize(p.slice(prefix.length)); + if (rel.startsWith("..") || !existsSync(join(dir, rel))) break; + return sendFile(req, res, join(dir, rel), types[rel.slice(rel.lastIndexOf("."))] || "application/octet-stream"); + } + res.writeHead(404); + res.end(); +}); +await new Promise((r) => server.listen(0, "127.0.0.1", r)); +const query = new URLSearchParams(); +if (has("--worker")) query.set("worker", "1"); +for (const k of ["size", "scenes", "skip"]) if (opt(`--${k}`)) query.set(k, opt(`--${k}`)); +const url = `http://127.0.0.1:${server.address().port}/test/unkernel.html?${query}`; +console.log(`== ${url}\n output in ${out}`); + +const t0 = Date.now(); +const chrome = spawn(browser, [ + "--no-sandbox", "--headless", "--use-angle=swiftshader", "--enable-unsafe-swiftshader", + "--no-first-run", "--disable-gpu-sandbox", `--user-data-dir=${join(out, "chromium-profile")}`, + url, +], { stdio: ["ignore", "ignore", "pipe"] }); +let chromeErr = ""; +chrome.stderr.on("data", (d) => (chromeErr += d)); +chrome.on("error", (e) => { + console.error(`cannot run ${browser}: ${e.message}`); + process.exit(2); +}); +const exited = new Promise((r) => chrome.on("exit", () => r(null))); +const body = await Promise.race([result, exited, new Promise((r) => setTimeout(() => r(null), timeout))]); +chrome.kill("SIGKILL"); +server.close(); +writeFileSync(join(out, "chromium.log"), chromeErr); +await exited; +rmSync(join(out, "chromium-profile"), { recursive: true, force: true }); +if (body === null) { + console.error(`no result from the page within ${timeout / 1000} s (or the browser exited); see ${out}`); + process.exit(2); +} +writeFileSync(join(out, "result.json"), body); +const res = JSON.parse(body); +if (res.error) { + console.log(`FAIL the page: ${res.error}`); + process.exit(1); +} +for (const [name, s] of Object.entries(res.steps)) writeFileSync(join(out, `${name}.txt`), s.stdout + (s.stderr ? `\n--- stderr\n${s.stderr}` : "")); + +let fails = 0; +const report = (name, ok, detail) => { + console.log(`${ok ? "PASS" : "FAIL"} ${name} ${detail}`); + if (!ok) fails++; +}; +console.log(`renderer: ${res.renderer} (gl ready ${res.readyS} s after the page started; ${res.worker ? "worker" : "inline"} mode)`); + +const e = res.steps.eglinfo; +if (e) { + const es = /OpenGL ES profile renderer: (.*)/.exec(e.stdout)?.[1] ?? "?"; + const ver = /OpenGL ES profile version: (.*)/.exec(e.stdout)?.[1] ?? "?"; + report("eglinfo", e.exitCode === 0 && /^virgl \(/.test(es), `GLES renderer "${es}", version "${ver}" (${(e.ms / 1000).toFixed(1)} s)`); +} + +const lines = (s) => s.stdout.split("\n").filter((l) => /^[a-z.0-9]+ \d+ [0-9a-f]{16}$/.test(l) || /samples-passed/.test(l)).sort(); +if (res.steps.state) { + const alone = lines(res.steps["state-alone"]), mixed = lines(res.steps.state); + const sums = alone.filter((l) => / [0-9a-f]{16}$/.test(l)); + const per = new Map(); + for (const l of sums) { + const [v, , sum] = l.split(" "); + if (!per.has(v)) per.set(v, new Set()); + per.get(v).add(sum); + } + const flat = [...per].filter(([, s]) => s.size < 2).map(([v]) => v); + const bad = mixed.filter((l, i) => l !== alone[i]).length + Math.max(0, alone.length - mixed.length); + const samples = mixed.some((l) => /samples-passed=[^0]/.test(l)); + let detail = `${bad} of ${sums.length} frames differ from the clients alone`; + let ok = sums.length === 60 && !flat.length && bad === 0 && alone.length === mixed.length && !samples && res.steps.state.exitCode === 0; + if (flat.length) detail += `; frames that do not change: ${flat.join(" ")}`; + const refFile = opt("--state-ref"); + if (refFile) { + const ref = readFileSync(refFile, "utf8").split("\n").filter((l) => / [0-9a-f]{16}$/.test(l)).sort(); + const diff = ref.filter((l, i) => l !== sums[i]).length; + detail += `; ${diff} of ${ref.length} differ from the host's (${refFile})`; + ok &&= diff === 0 && ref.length === sums.length; + } + const llvm = lines(res.steps["state-llvmpipe"]).filter((l) => / [0-9a-f]{16}$/.test(l)); + const llvmDiff = llvm.filter((l, i) => l !== sums[i]).length; + detail += `; llvmpipe in the guest: ${llvmDiff} of ${llvm.length} differ (rounding; not judged); ${(res.steps.state.ms / 1000).toFixed(1)} s virgl, ${(res.steps["state-llvmpipe"].ms / 1000).toFixed(1)} s llvmpipe`; + report("state", ok, detail); +} + +const fps = (s) => [...(s?.stdout ?? "").matchAll(/^\[(\S+)\] (.*?): FPS: (\d+) FrameTime: ([\d.]+) ms/gm)].map((m) => ({ scene: m[1], opts: m[2], fps: Number(m[3]), ms: Number(m[4]) })); +const gv = res.steps["glmark2-virgl"], gl = res.steps["glmark2-llvmpipe"]; +if (gv || gl) { + const v = fps(gv), l = fps(gl); + const ok = v.length > 0 && v.length === l.length && v.every((x) => x.fps > 0) && l.every((x) => x.fps > 0) && /virgl/.test(gv.stdout) && /llvmpipe/.test(gl.stdout); + // glmark2 rounds FPS to an integer; its mean frame time is exact + const f = (x) => (x ? `${(1000 / x.ms).toFixed(x.ms > 100 ? 2 : 1)} FPS (${x.ms} ms)` : "?"); + const rows = v.map((x, i) => `${x.scene} ${x.opts}: virgl ${f(x)}, llvmpipe ${f(l[i])}`); + const renderers = [gv, gl].map((s) => /GL_RENDERER:\s*(.*)/.exec(s?.stdout ?? "")?.[1]?.trim() ?? "?"); + report("glmark2", ok, `${res.size}, ${rows.join("; ") || "no FPS lines"} (renderers: ${renderers.join(" | ")})`); +} +console.log(`stats: ${JSON.stringify(res.gl)}; ${((Date.now() - t0) / 1000).toFixed(0)} s in the browser; output in ${out}`); +process.exit(fails ? 1 : 0); diff --git a/test/gl/unkernel-page.js b/test/gl/unkernel-page.js new file mode 100644 index 0000000..4f743f1 --- /dev/null +++ b/test/gl/unkernel-page.js @@ -0,0 +1,98 @@ +// SPDX-License-Identifier: MIT +// Copyright (C) 2026 Pooya Parsa +// The page of unkernel-check.mjs: boots unkernel from the built package +// (/dist/web.mjs) with the Debian image and the prepared data disk (Mesa +// installed: debian-disk.mjs; read over HTTP, the guest's writes kept in +// memory) and `gl: true`, waits for the guest's forwarder, runs the GL +// steps in the guest through vm.exec() and posts what they printed; the +// harness judges. Query: worker=1 (worker mode), size=WxH (glmark2's +// window), scenes= (glmark2 -b list, comma-separated), skip=a,b,c. +import { createKernel } from "/dist/web.mjs"; + +const q = new URLSearchParams(location.search); +const skip = new Set((q.get("skip") || "").split(",").filter(Boolean)); +const size = q.get("size") || "640x480"; +const scenes = (q.get("scenes") || "build:duration=10,texture:duration=10,shading:shading=phong:duration=10,jellyfish:duration=10,desktop:duration=10").split(","); +const t0 = performance.now(); +const secs = () => ((performance.now() - t0) / 1000).toFixed(1); + +const post = (path, body) => fetch(path, { method: "POST", body }).catch(() => {}); +function log(s) { + const line = `[${secs()}] ${s}`; + document.getElementById("log").append(line + "\n"); + post("/log", line); +} +let consoleBuf = ""; +setInterval(() => { + if (consoleBuf) post("/console", consoleBuf), (consoleBuf = ""); +}, 500); +addEventListener("error", (e) => log(`error: ${e.message}`)); +addEventListener("unhandledrejection", (e) => log(`error: ${e.reason?.stack || e.reason}`)); + +const VIRGL = "GALLIUM_DRIVER=virpipe LIBGL_ALWAYS_SOFTWARE=1"; +const LLVMPIPE = "LIBGL_ALWAYS_SOFTWARE=1"; +const VARIANTS = "tex stencil raster plain query mip dual"; + +async function main() { + const result = { worker: q.has("worker"), size, scenes, steps: {} }; + const vm = await createKernel({ + distro: "/img/debian.erofs", + disks: [{ kind: "http", url: "/img/debian-gl.img" }], + gl: true, + worker: q.has("worker"), + memoryMiB: 1024, + log, + }); + vm.onOutput((b) => (consoleBuf += new TextDecoder().decode(b))); + log(`booted (transport ${vm.transport})`); + result.renderer = await vm.gl.ready; + result.readyS = Number(secs()); + log(`gl ready: ${result.renderer}`); + + const run = async (name, cmd, opts = {}) => { + log(`run ${name}: ${cmd}`); + const t = performance.now(); + const r = await vm.exec("bash", ["-c", cmd], { timeout: 1800_000, ...opts }); + const s = { exitCode: r.exitCode, signal: r.signal, stdout: r.stdout, stderr: r.stderr, ms: Math.round(performance.now() - t) }; + log(`${name}: exit ${r.exitCode ?? r.signal} after ${(s.ms / 1000).toFixed(1)} s`); + result.steps[name] = s; + return s; + }; + + // (a) the renderer the guest sees + if (!skip.has("a")) await run("eglinfo", `${VIRGL} eglinfo -B -p surfaceless`); + + // (b) pixels: kwgl-state's clients interleaved on the page's one renderer + // against each run alone (both virgl), and the same on llvmpipe + if (!skip.has("b")) { + const bin = new Uint8Array(await (await fetch("/files/kwgl-state")).arrayBuffer()); + await vm.exec("sh", ["-c", "cat >/tmp/kwgl-state && chmod 755 /tmp/kwgl-state"], { input: bin }); + await run("state-alone", `for v in ${VARIANTS}; do ${VIRGL} timeout 600 /tmp/kwgl-state -t 8 $v; done | sort`); + await run("state", `mkdir -p /tmp/state && ${VIRGL} timeout 900 /tmp/kwgl-state -t 8 -o /tmp/state ${VARIANTS} | sort`); + await run("state-llvmpipe", `${LLVMPIPE} timeout 900 /tmp/kwgl-state -t 8 ${VARIANTS} | sort`); + for (const v of VARIANTS.split(" ")) { + const r = await vm.exec("cat", [`/tmp/state/${v}.ppm`], { encoding: "buffer" }).catch(() => null); + if (r?.exitCode === 0) await post(`/file/state-${v}.ppm`, r.stdout); + } + } + + // (c) the same glmark2-es2 scenes at the same size under Xvfb, on llvmpipe + // (software rendering under the emulated CPU) and on virgl (the page's WebGL2) + if (!skip.has("c")) { + const [w, h] = size.split("x"); + const bench = (env) => `${env} timeout 1500 xvfb-run -a -s "-screen 0 ${w}x${h}x24" glmark2-es2 -s ${size} ${scenes.map((s) => `-b ${s}`).join(" ")} 2>&1`; + await run("glmark2-virgl", bench(VIRGL)); + await run("glmark2-llvmpipe", bench(LLVMPIPE)); + } + + result.gl = vm.gl.stats; + result.totalS = Number(secs()); + await post("/result", JSON.stringify(result)); + log("done"); + await vm.stop(); +} + +main().catch(async (e) => { + log(`error: ${e?.stack || e}`); + await post("/result", JSON.stringify({ error: String(e?.stack || e) })); +}); diff --git a/test/gl/unkernel.html b/test/gl/unkernel.html new file mode 100644 index 0000000..8aecbfa --- /dev/null +++ b/test/gl/unkernel.html @@ -0,0 +1,7 @@ + + + + +unkernel guest GL check +

+