Repository navigation
gl, js: snapshot a machine while GL programs run (gl.snapshots) - #205
Aditya1404Sal wants to merge 3 commits into
Conversation
gl/wasm/build.sh never re-applies an existing kw-wasm branch, and only warned when its commit count differed from gl/patches/virglrenderer. A checkout that applied the series before newer patches came keeps the old branch, so the build went on without them: a module whose code calls a later patch's function then failed only at the link, with undefined symbols, the warning screens above. `source` now compares kw-wasm with the series patch by patch (patch ids). A branch that is the series' first patches without the later ones stops the build at once, naming the first missing patch and the command that re-applies the series (rename the branch). Any other difference, commits not exported yet or a patch changed since it was applied, warns as before, now with the first commit that differs and the same two ways out.
A machine snapshot keeps the guest's memory, but a guest's GL contexts live in the renderer: their objects, bindings and textures are WebGL2 state in the page, which a restore starts empty. So no snapshot could be taken while a GL program ran. In a snapshot session (opt-in, kw_vgpu_set_profile) the module keeps, per guest context, a journal of what its command streams made and set that still holds (kw_journal.c), and kw_snap.c saves the renderer's guest state into one blob, KWGPU1: the journals, the contexts and their attachments, and the resources, with the contents of buffers and colour textures read back. A restore checks everything before it changes anything, makes the contexts again by replaying the journals through vrend's own decoder, then uploads the contents, each checked against its hash first. The guest's kernel caches the capsets, and Mesa derives formats and limits from them, so a restored guest goes on with the capsets of the browser that saved it. A session therefore gives a fixed capset profile (profile 1: the formats both measured WebGL2 implementations offer, and limits every browser of a session can give), and a restore asks whether the host's real capsets cover it (-95 if not). The blob also carries the build id of the module that wrote it, 16 hex digits of a SHA-256 over the virglrenderer tree and gl/wasm, and another build refuses it (-116, ESTALE): the journal's records and the profile's lists are that build's. A save keeps buffers and colour textures exactly. Depth, stencil and multisample resources it keeps without content (CLEARED): WebGL2 reads none of them back exactly, and EGL leaves a window surface's ones undefined after each swap, so programs clear them every frame. A restore makes them as new, WebGL2's zeros, which only a frame in progress at the snapshot point, or a program that keeps them across frames without a clear, can show; refusing them would refuse every save of a program whose window has a depth or stencil buffer. A save refuses, with its reason on stderr, the rest it cannot keep exactly: a context whose journal is tainted or that vrend has in error (-5), a texture it cannot read back (-95), an open vtest client, an active query or a query result the guest waits for still to come (-16: the caller saves again from a later task). Two virglrenderer patches let it see the last ones: 22 tells whether a context is in error, 23 writes the waited-for query results that are ready. Module.virgl.gpu gets setProfile(id), buildId(), save() (a code and the blob), restore(blob) and snapStats(). Tests: journal-test.c and snap-test.c on the host under ASan and UBSan (hostile blobs included), and check.mjs's profile and save-and-restore stages in headless Chromium, on SwiftShader and on the host's GPU.
With virtio-gpu 3D a snapshot was refused while any GL context lived
(the device side's blocker()): the renderer's state is in the page, not
in the guest's memory. Now that the renderer can save and restore its
guest state (KWGPU1), the machine keeps it.
createKernel({ gpu: true, gl: { snapshots: true } }) starts a GPU
snapshot session. The renderer loads before the boot and gives the
fixed capset profile before any capset; the device side keeps each
context's CTX_CREATE, each 3D resource's RESOURCE_CREATE_3D, the
attachments, the backing pages and the last SET_SCANOUT. At the
snapshot point (every task parked) the kernel waits up to 2 s for the
virtio-gpu commands in flight, takes the renderer's blob and the
device's records, and asks everything the synchronous point asks again
after each wait; 5 s at most in all. A renderer that refuses, or
anything in flight then, rejects the snapshot with the reason, and the
guest goes on. The blob is the snapshot file's optional gpuBytes
section, between the input and the memory chunks. A file with it is
version 2, so that a decoder from before it refuses the file by its
version instead of reading the blob as memory chunks; a file without it
is version 1 and decodes as before, and a bad or overlong gpuBytes is
refused.
A restore puts the renderer's state back after loadSnapshot() and before
the guest runs, gives the display the saved 3D scanout, raises each
virtio device's interrupt once and sets the guest's clock from the
snapshot's again. A renderer that refuses the blob (another build,
capsets that do not cover the profile, a damaged blob) rejects
createKernel() with a GpuRestoreError, and nothing is left running: the
caller boots fresh. Any failure of createKernel() before the kernel
takes the session's renderer lets the renderer's WebGL2 context go at
once (browsers cap live ones, and the caller boots again). A snapshot
with GPU state restores only into a session. In worker mode the kernel
and the device side are the worker's and the renderer is the owner's;
saves and restores cross as gpu-save and gpu-restore messages.
The API (js/core; GpuRestoreError is also exported by the package):
- GlOptions.snapshots?: boolean; glSnapshots(opt: GlOption | undefined):
boolean; dropGl(prep: GlPrep | undefined): void; GlPrep.session?:
boolean
- class GpuRestoreError extends Error { readonly reason: string;
constructor(reason: string, opts?: { cause?: unknown }) }; its message
is "gpu restore: <reason>"
- snapshotHoldsGpu(s: KernelSnapshot | undefined): boolean
- KernelSnapshot.gpu?: Uint8Array (the KWGPU1 blob)
- DeviceSnapshots.gpu?: { transport: VirtioTransportSnapshot[];
virgl?: VirglDeviceState } | null
- interface VirglDeviceState { v: 1; contexts: Array<{ id: number;
create: string; attached: number[]; submitted: boolean; refused?: true
}>; resources: Array<{ id: number; create: string; backing:
Array<[addr: number, len: number]> | null; refused?: true }>; scanout:
string | null }
- GpuBackend: readonly snapshots?: boolean; saveState?(): Promise<{
state: VirglDeviceState; blob: Uint8Array } | null>;
restoreState?(state: VirglDeviceState, blob: Uint8Array | undefined,
ctx: GpuBackendContext): Promise<void>
- VirtioGpu: drainCommands(ms: number): Promise<boolean>; save3d():
Promise<{ state: VirglDeviceState; blob: Uint8Array } | null>;
restore3d(state: VirglDeviceState | undefined, blob: Uint8Array |
undefined): Promise<void>; VirtioHost.interruptAll(): void
- new VirglGpuBackend(link: GpuLink, log?: (msg: string) => void, opts?:
{ snapshots?: boolean }); get snapshots(): boolean
- GpuLink: save?(): Promise<Uint8Array>; restore?(blob: Uint8Array):
Promise<void>
- GpuRendererOptions.snapshots?: boolean; GpuRenderer: save(waitMs?:
number): Promise<Uint8Array> (rejects with Error "gpu save: <reason>");
restore(blob: Uint8Array): Promise<void> (rejects with
GpuRestoreError); get snapshots(): boolean; dispose(): void;
GpuRendererStats.snapshot?: { saved; cleared; contentBytes;
journalBytes; saveMs; restoreMs }
- VirglGpuApi (Module.virgl.gpu): setProfile?(id: number): number;
buildId?(): string; save?(): { code: number; data?: Uint8Array };
restore?(blob: Uint8Array): number; snapStats?(): { saved; cleared;
contentBytes; journalBytes }
- GPU_COMMANDS (the blocker() text of commands in flight),
NO_SESSION_RENDERER (a GpuRestoreError reason), GPU_SAVE_WAIT_MS = 2000
- worker-protocol: { t: "gpu-save"; rid } answered by { t: "gpu-saved";
rid; blob?; error? }; { t: "gpu-restore"; rid; blob } answered by
{ t: "gpu-restored"; rid; error? }; WorkerBootSpec.gpuSnapshots?:
boolean; boot-error's gpuRestore?: string (the reason); ownedBytes(b:
Uint8Array): [Uint8Array, ArrayBuffer[]]; worker-serve's toOwner(snap:
KernelSnapshot): [KernelSnapshot, ArrayBuffer[]]
A refused snapshot rejects snapshot() with Error "snapshot: <reason>";
a refused restore rejects createKernel() with the GpuRestoreError
itself, not a BootError.
The page's GPU frame counters leave the new stats.snapshot out.
Tests without a browser: test/gl-gpu.test.ts (the device side's records,
the renderer's save and restore against fake modules, the snapshot
point's drain and limits, the renderer let go when a boot fails),
test/snapshot-gpu.test.ts (gpuBytes in the file and its version,
hostile values, what a worker posts) and test/api.test.ts's GPU
snapshot sessions (a booted machine, inline and in worker mode, with a
fake renderer). In a browser: unkernel-check.mjs --gpu-snapshot (step S:
programs snapshotted while they run and restored, also on another
WebGL2 implementation and refused by another build).
Snapshots of a machine with live GL state (design note)Today a machine with It was needed to save and restore a guest whose home screen draws on ShapeIt is opt-in: Two halves:
What is saved
Depth, stencil and multisample contentsWebGL2 has no exact way to read them:
Between frames a window surface loses nothing a program may use: EGL
Refusing such saves would refuse every one of these: any program whose The capset profileThe guest's kernel caches the capsets, and Mesa (and Skia, Chromium) derive The build id ruleThe blob records the build id of the module that wrote it: 16 hex digits of The hash takes the virglrenderer tree's commit and its uncommitted changes A host that offers saved snapshots can compare What is refused, and whyA refusal never leaves a half-made state behind on the saving side: a At the snapshot point (every task parked; on SMP every other CPU held):
By the renderer's save (with its reason, the module's code in brackets):
By a restore, before it changes anything:
A refused restore rejects CostsMeasured 2026-12-04 on this branch's code (renderer build
Open points
Tests
|
The design note is in the first comment below. It says what a save
keeps, what it refuses and why, the capset profile, the build id rule
and the costs. This text lists the commits, the tests and what to know
before review.
What
Three commits:
gl: stop the renderer build when kw-wasm lacks the series' later patches. gl/wasm/build.sh never applies an existing kw-wasm branchagain. It now compares that branch with gl/patches/virglrenderer,
patch by patch. A branch that lacks the later patches stops the build
at once, with the command that renames it. Before, the build went on
and failed at the link, with undefined symbols. This matters here
because the next commit adds two patches: a checkout that applied
main's 21 patches would build without them.
gl: save and restore the renderer's guest state (KWGPU1). A journalper guest context (kw_journal.c), and the save and restore of the
renderer's guest state as one blob (kw_snap.c). A fixed capset
profile, and the build id rule. Two virglrenderer patches: 22 tells
whether a context is in error, 23 writes the waited-for query results
that are ready. Host tests under ASan and UBSan, and new stages in the
module test.
js: snapshot and restore a machine while GL programs run (gl.snapshots).createKernel({ gpu: true, gl: { snapshots: true } }): the device side's records, the snapshot point, the boot order ofa restore, worker mode, and the blob as an optional
gpuBytessectionof the snapshot file. A file with it is version 2, so an SDK from
before refuses it by its version. A file without it is version 1, as
before. A refused restore rejects
createKernel()with aGpuRestoreError, and the caller boots fresh. The commit messagelists the new API. Step S of
test/gl/unkernel-check.mjschecks it ina browser.
Without
gl: { snapshots: true }nothing changes: no record is kept andno journal is walked.
What a save keeps: buffers and colour textures exactly, each read back
through vrend's own transfer path, hashed, and compared again after a
restore. Depth, stencil and multisample resources are saved without
content (CLEARED), and a restore makes them as new, with WebGL2's zeros.
WebGL2 reads none of them back exactly, and EGL leaves a window
surface's ones undefined after each swap, so programs clear them every
frame. Only a frame in progress at the snapshot point, or a program that
keeps them across frames without a clear, can show wrong pixels, until
its next clear. Such saves are not refused: refusing them would refuse
every save of a program whose window has a depth or stencil buffer. The
design note gives the alternatives.
Why
.agents/gl.md:792-794 at b5d1726: "Snapshots: refused while any 3D
resource exists or a context has submitted commands (its objects,
shaders, states, sub contexts, live only in the renderer), before the
guest parks". The renderer's state is WebGL2 state in the page, not in
the guest's memory, so a machine with guest GL could not be saved while
a GL program ran. The SDK docs say the same
(docs/1.sdk/14.snapshots.md:37 at b5d1726: "A snapshot is refused while
virtio-gpu holds resources.").
It was needed to save and restore a guest whose home screen draws with
virtio-gpu 3D (an Android one). Nothing here depends on the guest.
This PR does not need the snapshot fixes PR (pr/snapshot-fixes, network
names, a distro image's SHA-256, data disk import): it sits on main
alone. The two touch neighbouring lines in
Kernel.saveDevices()(js/core/kernel.ts: the network line, then the gpu line), so whichever
lands second needs a one-line rebase there.
It does not need the worker memory PR (pr/worker-one-copy) either. Both
change the code that takes a snapshot in js/core/kernel.ts (this PR
splits it into
#take()) and one sentence of .agents/js.md. Whicheverlands second needs a small rebase there.
The third commit also fixes the doc statements the change makes wrong,
in five files:
gl: { snapshots: true }andgpua snapshot keeps the renderer's state, or is refusedwith the reason, and that the restore needs the same options.
blocker())" bullet and.agents/kernel/devices.md's virtio-gpu "Snapshots" bullet now start
with "outside a GPU snapshot session".
virgl.wasmloads beforethe boot only with
gl: { eager: true }. They now say a session loadsit before the boot too.
How tested
All on 2026-12-04, on this branch's code as it is now. Only doc lines
came after the runs. macOS on an Apple M5 Pro, AC power, Low Power Mode
off; headless Google Chrome 158.0.8127.108; Node 26.0.0. The kernel is
b5d1726's own default bundle (build id
#c7a405545d92): this PRchanges no kernel. The renderer is this branch's, built from a fresh
local clone of virglrenderer 1.3.0 with the branch's 23 patches: build
id 72abd1ab296ae4b5. The Debian image is debian-13.7 with the GL test
disk (Mesa from apt), made before for this work and only read here. The
1-minute load at the start is given for each check (for the web build,
the loads of the checks around it). Checks that start above 4 are
pass/fail only.
pnpm typecheckandpnpm typecheck:web: pass (load 7.59).pnpm test:gl-gpu32 of 32,pnpm test:snapshot-gpu10 of 10,node --test web/test/open.test.ts5 of 5 (load about 7.5).pnpm test:apiwith b5d1726's bundle: 178 tests, 165 pass, 10skipped, 3 fail. The three fail on b5d1726 too (two nodeFs mount tests:
macOS refuses file names that are not UTF-8; "worker mode rejects
device objects": it needs a built js/unkernel.wasm). The "GPU snapshot
sessions" tests pass (load 8.32).
pnpm build:web(the local kernel, the Debian image and thisrenderer by
KW_KERNEL,KW_DISTROS,KW_GL): pass (its own loadwas not noted; the checks just before and after it started at 7.6 and
6.5).
journal-test.candsnap-test.con Linux under ASan and UBSan: ok22 and ok 5 (load 5.93).
node gl/wasm/test/check.mjs, on SwiftShader and onthe Mac's GPU: pass (KWGPU1 blobs of 49,712 and 49,688 bytes). Capset
coverage both ways (
--dump-capsets,--saved-capsets): eachimplementation covers the other's profiled capsets, and the profiled
capsets of the two are the same bytes (loads 6.1 to 6.5).
test/gpu/check.mjsUP and--cpus 2 --pin 1pass (a snapshot is refused while a dumb buffer is held; therestored machine runs its KMS client again).
flip-check.mjs: pass,119 vblanks for 119 flips, 0 not consecutive (loads 5.6 to 7.1).
node test/gl/unkernel-check.mjs --drm --gpu-snapshot --skip c, in all four configurations (SwiftShader or the Mac's GPU, inline orworker mode): every step passes (17 of 17 each). kwgl-state (S1) is
snapshotted while its seven clients run and restored in the page: 0 of
480 checksum lines differ from the reference, with 8 depth-stencil
resources saved CLEARED. kmscube (S2) keeps running across a snapshot
and a restore: at least 30 new frames after the restore, and in each
run three sampled frames have 0 pixels that differ from the scanout
read back (no wrong pixels). With
--snapshottoo (inline,SwiftShader): 18 of 18, the idle 3D context restored (loads 2.95 to
15.2).
--gpu-snapshot save, thenrestorein a newChrome): SwiftShader to the Mac's GPU and the GPU to SwiftShader both
pass. Before the pause 0 of 240 checksums differ; after it 0 of 240
differ from the restoring implementation's own run, and a new kmscube
shows frames with 0 wrong pixels. A renderer of another build (one that
can read KWGPU1, built 2026-12-03 from more patches) refuses the blob:
"gpu restore: the blob is of build 72abd1ab296ae4b5, this module is
67b63457b3144f13 (-116 ESTALE)", and
createKernel()rejects with aGpuRestoreError. The same file then restores with this build (loads7.3 to 9.2).
kw-wasm holds main's 21 patches: with the build script as it was, it
only warns ("21 commits ..., 23 patches") and fails at the link
(
undefined symbol: vrend_renderer_queries_pending,vrend_renderer_context_in_error). With this branch it stops at once,naming 0022 and the command that renames the branch. A fresh tree
applies all 23 patches and builds with no warning from the script
(its one compiler warning, in Mesa's u_debug.c, comes on b5d1726
too) (load 6.14).
Times. Step S again in the four configurations, one run each, 12:27 to
12:31. Each run started at a 1-minute load of 4.00 or less. The loads
at the start and at the end: SwiftShader inline 3.76 and 4.48, GPU
inline 3.87 and 2.91, SwiftShader worker 2.91 and 6.30, GPU worker 4.00
and 8.80. So the GPU worker run, with the slowest
createKernel(159 ms), ran while the load more than doubled. All four pass 17 of 17.
In ms:
vm.snapshot()(of 5000)createKernelThe blobs: kwgl-state 5,924,132 bytes on SwiftShader and 5,924,108 on
the GPU (44 resources, 8 of them CLEARED); kmscube 2,463,036 and
2,463,012 bytes (3 resources).
Cost
gl), against b5d1726's ownbuild: virgl.wasm 490,209 to 527,942 bytes (+37,733), gzip -9 188,063
to 203,356 (+15,293); virgl.mjs 112,812 to 114,576 (+1,764), gzip -9
29,988 to 30,437 (+449).
222,673 to 227,967 (+5,294).
gl: { snapshots: true }: nothing is recordedand no journal is walked. In a session: the renderer loads before the
boot (not at the first GL use), and a snapshot carries the blob
(above: 2.5 to 5.9 MB for these programs; 61.2 to 61.3 MB for
LineageOS at its home screen, measured 2026-12-03 with these commits
plus the renderer patch of the YV12 follow-up PR: renderer build
67b63457b3144f13).
with a session and three without (.agents/gl.md, Measured). Those runs
started at 1-minute loads of 3.4 to 5.9, so this text gives no number
from them.
or restore).
Notes for review
change refuses it by its version.
id). Every renderer change needs new snapshots.
refused (What, above; the design note's Open points has the
alternatives).
be read back, so a save is refused while a texture in one of them
lives. Masking them out of the profile is the alternative, to decide
before the first public snapshot.
decodeSnapshot(). A stream decoder for large files is a separatefollow-up PR, which then switches this page to it.
same GL code with one more renderer patch (YV12, a follow-up PR), on a
kernel with more patches (an Android series' default build). The
table above is this branch's, on b5d1726's kernel; its numbers are in
the same range. gl.md's times that include the snapshot file's fetch
and decode were taken with the stream decoder of a follow-up PR. This
branch's test page decodes with
decodeSnapshot()(above).Linux) are not measured against profile 1.
runs started at loads of 7.3 to 9.2, so they are pass/fail only).