Skip to content

gl, js: snapshot a machine while GL programs run (gl.snapshots) - #205

Draft
Aditya1404Sal wants to merge 3 commits into
pithings:mainfrom
Aditya1404Sal:pr/gpu-snapshot
Draft

Aditya1404Sal wants to merge 3 commits into
pithings:mainfrom
Aditya1404Sal:pr/gpu-snapshot

Conversation

@Aditya1404Sal

Copy link
Copy Markdown

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:

  1. gl: stop the renderer build when kw-wasm lacks the series' later patches. gl/wasm/build.sh never applies an existing kw-wasm branch
    again. 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.
  2. gl: save and restore the renderer's guest state (KWGPU1). A journal
    per 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.
  3. 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 of
    a restore, worker mode, and the blob as an optional gpuBytes section
    of 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 a
    GpuRestoreError, and the caller boots fresh. The commit message
    lists the new API. Step S of test/gl/unkernel-check.mjs checks it in
    a browser.

Without gl: { snapshots: true } nothing changes: no record is kept and
no 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. Whichever
lands second needs a small rebase there.

The third commit also fixes the doc statements the change makes wrong,
in five files:

  • docs/1.sdk/14.snapshots.md:37 now says that with gl: { snapshots: true } and gpu a snapshot keeps the renderer's state, or is refused
    with the reason, and that the restore needs the same options.
  • .agents/js.md's virtio-gpu "Snapshots (blocker())" bullet and
    .agents/kernel/devices.md's virtio-gpu "Snapshots" bullet now start
    with "outside a GPU snapshot session".
  • docs/1.sdk/12.graphics.md and README.md said virgl.wasm loads before
    the boot only with gl: { eager: true }. They now say a session loads
    it 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 PR
changes 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 typecheck and pnpm typecheck:web: pass (load 7.59).
  • pnpm test:gl-gpu 32 of 32, pnpm test:snapshot-gpu 10 of 10,
    node --test web/test/open.test.ts 5 of 5 (load about 7.5).
  • pnpm test:api with b5d1726's bundle: 178 tests, 165 pass, 10
    skipped, 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 this
    renderer by KW_KERNEL, KW_DISTROS, KW_GL): pass (its own load
    was not noted; the checks just before and after it started at 7.6 and
    6.5).
  • journal-test.c and snap-test.c on Linux under ASan and UBSan: ok
    22 and ok 5 (load 5.93).
  • The module test, node gl/wasm/test/check.mjs, on SwiftShader and on
    the Mac's GPU: pass (KWGPU1 blobs of 49,712 and 49,688 bytes). Capset
    coverage both ways (--dump-capsets, --saved-capsets): each
    implementation covers the other's profiled capsets, and the profiled
    capsets of the two are the same bytes (loads 6.1 to 6.5).
  • The virtio-gpu quick checks: test/gpu/check.mjs UP and --cpus 2 --pin 1 pass (a snapshot is refused while a dumb buffer is held; the
    restored machine runs its KMS client again). flip-check.mjs: pass,
    119 vblanks for 119 flips, 0 not consecutive (loads 5.6 to 7.1).
  • Step S, node test/gl/unkernel-check.mjs --drm --gpu-snapshot --skip c, in all four configurations (SwiftShader or the Mac's GPU, inline or
    worker 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 --snapshot too (inline,
    SwiftShader): 18 of 18, the idle 3D context restored (loads 2.95 to
    15.2).
  • Across browsers (--gpu-snapshot save, then restore in a new
    Chrome): 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 a
    GpuRestoreError. The same file then restores with this build (loads
    7.3 to 9.2).
  • The renderer build's stop (commit 1), with a virglrenderer tree whose
    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:

Program Configuration vm.snapshot() (of 5000) renderer save createKernel renderer restore first new frame, from the call 30th new frame, from the resolve
kwgl-state SwiftShader, inline 35 9 87 12
kwgl-state GPU, inline 36 11 91 15
kwgl-state SwiftShader, worker 39 10 113 12
kwgl-state GPU, worker 41 13 159 17
kmscube SwiftShader, inline 44 2 98 3 104 521
kmscube GPU, inline 49 13 88 7 104 615
kmscube SwiftShader, worker 45 2 100 3 109 509
kmscube GPU, worker 44 9 125 8 140 498

The 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

  • The renderer module (loaded only with gl), against b5d1726's own
    build: 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).
  • The SDK's dist/web.mjs: 688,971 to 705,686 bytes (+16,715), gzip -9
    222,673 to 227,967 (+5,294).
  • The kernel bundle: unchanged.
  • At run time, without gl: { snapshots: true }: nothing is recorded
    and 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).
  • The journal's cost was measured 2026-11-25 with glmark2, three runs
    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.
  • The design note's Costs has the rest (the renderer's heap after a save
    or restore).

Notes for review

  • A snapshot file with GPU state is version 2: an SDK from before this
    change refuses it by its version.
  • A blob restores only on the renderer build that wrote it (the build
    id). Every renderer change needs new snapshots.
  • Depth, stencil and multisample resources are saved CLEARED, not
    refused (What, above; the design note's Open points has the
    alternatives).
  • 30 of capset profile 1's 97 sampler formats (ETC2 among them) cannot
    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.
  • The DRM test page restores the split run's saved file with
    decodeSnapshot(). A stream decoder for large files is a separate
    follow-up PR, which then switches this page to it.
  • .agents/gl.md's Measured section (2026-12-03) was measured on the
    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).
  • Other browsers' capsets (Chrome and Edge on Windows with D3D11, and on
    Linux) are not measured against profile 1.
  • Not measured here: a restore in a new browser for timing (the split
    runs started at loads of 7.3 to 9.2, so they are pass/fail only).

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).
@Aditya1404Sal

Copy link
Copy Markdown
Author

Snapshots of a machine with live GL state (design note)

Today a machine with gpu and gl cannot be snapshotted while any guest GL
context lives: the virtio-gpu device side refuses (blocker()), because the
renderer's state (the contexts' objects, bindings and textures) is WebGL2
state in the page, not in the guest's memory. This change lets a machine keep
that state and get it back on restore.

It was needed to save and restore a guest whose home screen draws on
virtio-gpu 3D (an Android one). Nothing below depends on the guest.

Shape

It is opt-in: createKernel({ gpu: true, gl: { snapshots: true } }) starts a
GPU snapshot session. Without the option nothing changes: no record is kept,
no journal is walked, and a snapshot with GPU state is refused at boot
("snapshot: it holds GPU state; pass gl: { snapshots: true } and gpu").

Two halves:

  • The renderer module (gl/wasm/kw_journal.c, kw_snap.c): a journal per
    guest context, and a save and restore of the renderer's guest state as one
    blob, KWGPU1.
  • The machine (js/core): the device side's records, the snapshot point, the
    boot order of a restore, worker mode, and an optional gpuBytes section in
    the KWSNAP1 file (between the input and the memory chunks). A file with it
    is version 2, so an SDK from before it refuses the file by its version
    ("unsupported snapshot version 2") instead of reading the blob as memory
    chunks. A file without it is version 1 and decodes as before. A bad or
    overlong gpuBytes is refused.

What is saved

  • Per guest context, a journal of what its command streams made and set that
    still holds: the sub contexts, the CREATE_OBJECT packets of the live
    objects in creation order, and the state commands whose effect is still
    current. A restore replays it through vrend's own decoder, so the objects
    are made by the same code that made them the first time.
  • The contexts and their attachments, and every resource with its create
    arguments. Buffers and colour textures keep their contents exactly: read
    back per level, layer and face through vrend's own transfer path, each
    with an XXH64 hash, and after a restore read back again and compared.
  • Depth, stencil and multisample resources keep no content (the blob marks
    them CLEARED). A restore makes them as new, so they hold WebGL2's zeros:
    depth 0.0 (programs usually clear it to 1.0), stencil 0, every sample 0.
    Below: what that loses and why such saves are not refused.
  • On the device side (VirglDeviceState, in the machine snapshot's
    devices.gpu.virgl): each context's CTX_CREATE and each 3D resource's
    RESOURCE_CREATE_3D as the guest sent them, the attachments, the backing
    pages, and the last SET_SCANOUT. A restore makes the contexts and
    resources again, empty, with the same commands, and the blob fills them.
  • The capset profile number and the build id of the module that wrote the
    blob (below).

Depth, stencil and multisample contents

WebGL2 has no exact way to read them: readPixels reads colour buffers
only, WebGL2 cannot sample stencil, and a multisample buffer reads only
through a resolve, which loses its samples. So a save keeps none of their
contents, and a restored program finds zeros in them. That shows wrong
pixels in two cases:

  • a frame in progress at the snapshot point: what it drew before the point
    reached the renderer, and the rest is drawn after the restore against the
    zeros. With a depth test of LESS no fragment passes 0.0, a stencil clip is
    gone, and a multisample buffer loses what it held before its resolve, so
    that frame misses those draws. The next frame clears and is right.
  • a program that keeps depth, stencil or samples across frames in a
    framebuffer of its own without clearing them: until its next clear.

Between frames a window surface loses nothing a program may use: EGL
leaves the depth, stencil and multisample buffers of a window surface
undefined after each eglSwapBuffers, so programs clear them every frame.
The saves measured clear only such buffers:

  • LineageOS at its home screen (three snapshot files of 2026-12-03, made
    with these commits plus the renderer patch of the YV12 follow-up PR):
    6 to 9 depth-stencil resources per save (virgl format 20,
    S8_UINT_Z24_UNORM, no samples) at window sizes (720x1280, 720x1224,
    720x96, 720x56, 200x56), the window surfaces' buffers; every restore
    shows the saved home screen.
  • kwgl-state (step S): the eight 64x64 depth-stencil renderbuffers of its
    own framebuffers, which it clears at every turn; after the restore every
    one of its checksums equals the reference's.

Refusing such saves would refuse every one of these: any program whose
window has a depth or stencil buffer could never be saved. So a save
clears them, and the docs say what that loses. A host that controls the
guest can take its snapshot when no frame is in progress; vm.snapshot()
itself does not wait for one to end. Open points has the alternatives.

The capset profile

The guest's kernel caches the capsets, and Mesa (and Skia, Chromium) derive
formats, limits and workarounds from them, so a restored guest goes on with
the capsets of the browser that saved it. A session therefore gives fixed
capsets, profile 1: the formats both measured WebGL2 implementations offer
(SwiftShader and ANGLE on Metal), and limits every browser of a session can
give (MAX_SAMPLES 4, MAX_TEXTURE_SIZE 4096, the GLES 3.0 minimum where a
desktop backend of Chrome or Edge is known to report less). A restore asks
whether the host's real capsets cover the saved ones; a host below the
profile boots fresh.

The build id rule

The blob records the build id of the module that wrote it: 16 hex digits of
a SHA-256 over the virglrenderer tree (with our patches applied) and
gl/wasm (its tests left out). A restore checks it first and refuses any
other build (-116, ESTALE). The journal's records and the profile's lists are
that build's, so a blob is only read by the code that wrote it. A profile
number names a shape of capsets, and the build id pins its lists: a change to
the lists under the same number (a format added) needs no new number.

The hash takes the virglrenderer tree's commit and its uncommitted changes
(git diff HEAD), not its untracked files: a file added to that tree and
not committed changes the module but not its id (kernel/build.sh hashes
the kernel tree's untracked files too). A tree that gl/wasm/build.sh
made from the patches has none.

A host that offers saved snapshots can compare Module.virgl.gpu.buildId()
of the module it serves with the one that saved them before any large
download, and boot fresh when they differ.

What is refused, and why

A refusal never leaves a half-made state behind on the saving side: a
refused snapshot rejects snapshot() with "snapshot: " and the guest
goes on.

At the snapshot point (every task parked; on SMP every other CPU held):

  • virtio-gpu commands still in flight after 2 s: their answers go into the
    guest's memory, which is copied after, so they must be answered first;
  • anything else in flight after the waits (network frames, vsock packets,
    shm requests the host queued meanwhile): the point asks everything the
    synchronous point asks again after each wait;
  • no renderer state within 5 s in all.

By the renderer's save (with its reason, the module's code in brackets):

  • no renderer (-19), no profile (-95);
  • the WebGL context lost, a record lost to a failed allocation, or a context
    whose journal is tainted or that vrend has in error (-5): a refused command
    buffer, a context error or state the journal does not keep means the
    journal no longer describes the context;
  • a texture whose contents it cannot read back exactly (-95): a format
    WebGL2 does not read back (the compressed ones, among them ETC2), a
    layout it does not keep. Depth, stencil and multisample resources are not
    refused: they are saved without content (above);
  • a vtest client open, a query active or one ended whose result was not asked
    for, stream-out targets set, or a query result the guest waits for still to
    come (-16): the caller saves again from a later task, within the same wait;
  • out of memory (-12), a readback that failed or raised a GL error (-5).

By a restore, before it changes anything:

  • not KWGPU1 or malformed (-22): every offset and count within the blob,
    contents in order with no overlap, each content's hash checked before any
    upload;
  • another build (-116), another profile or capsets that do not cover it
    (-95);
  • resources other than the blob's, or a context the blob does not have that
    the guest has already used.

A refused restore rejects createKernel() with a GpuRestoreError
(reason), not a BootError, and nothing is left running: the caller boots
fresh. A restore that fails after the module's checks leaves the renderer
half restored, so the instance and its renderer are dropped. Any failure of
createKernel() before the kernel takes its renderer lets the renderer's
WebGL2 context go at once, since browsers cap live WebGL2 contexts and the
caller boots again.

Costs

Measured 2026-12-04 on this branch's code (renderer build
72abd1ab296ae4b5; b5d1726's default kernel bundle, #c7a405545d92),
headless Chrome 158 on an Apple M5 Pro, one run in each of four
configurations (SwiftShader or the Mac's GPU, inline or in worker mode),
each started at a 1-minute load of 4.00 or less (they ended at loads of
2.91 to 8.80):

  • The snapshot point: 35 to 49 ms of its 5 s.
  • The blob: kwgl-state 5.9 MB (44 resources, 8 of them cleared, 15 KB of
    journals), kmscube 2.5 MB. LineageOS at its home screen: 61.2 to 61.3
    MB (93 contents; 2026-12-03, made with these commits plus the YV12
    patch). It goes into the file uncompressed; the file's transport
    compresses it (kwgl-state's blob: gzip -6 leaves 0.7 %, 2026-12-03).
  • The renderer's save: 2 to 13 ms. Its restore: 3 to 17 ms in the saving
    page.
  • createKernel({ restore }): 87 to 159 ms in the saving page. A restore
    in a new browser passed both ways (SwiftShader to the GPU and back).
    Those runs started at loads of 7.3 to 9.2, and the 2026-12-03 ones in
    .agents/gl.md at 4.8 to 5.9, so no time is given for it here.
  • The file's JSON header: 150 to 174 KB for LineageOS (the device side's
    records; 2026-12-03).
  • The journal walks each SUBMIT_3D buffer once, before vrend's decoder.
    .agents/gl.md (Measured) has glmark2 with and without a session
    (2026-11-25, three runs each). Those runs started at loads of 3.4 to
    5.9, so no number from them is given here.
  • The module: virgl.wasm +37,733 bytes against b5d1726's (gzip -9
    +15,293), virgl.mjs +1,764 (+449).
  • Memory: the module's wasm heap grows and never shrinks. A save first
    mallocs its bound, every content before identical ones are shared plus
    the tables and journals (65.2 to 65.4 MB for LineageOS' blobs of 61.2
    to 61.3 MB, 2026-12-03), then shrinks it to the blob, which the page
    copies out and frees. A restore mallocs the blob's length and one
    scratch buffer of its largest content. So after its first save or
    restore a session's renderer holds a heap of at least that size.

Open points

  • Depth, stencil and multisample contents (above). Alternatives to clearing
    them: an exact save (depth through a shader that samples it into a colour
    target, stencil bit by bit through the stencil test, multisample buffers
    not at all on WebGL2), or a session option that refuses a save while such
    a resource lives, for a host that cannot choose its snapshot point. Not
    done: every measured save would then be refused, and the exact paths cost
    a draw per resource and level in every save and restore.
  • Other browsers' capsets (Chrome and Edge on Windows with D3D11, and on
    Linux) are not measured against profile 1.
  • 30 of profile 1's 97 sampler formats cannot be saved: a save is refused
    while a texture in one of them lives. Masking them out of the profile
    (Mesa then decompresses ETC2 itself) is the alternative, to be decided
    before the first public snapshot, as it changes the profile's lists.
  • Worker mode refuses a save whose read-back outlasts the 5 s point; a
    program with much more texture memory than measured here may need a
    larger cap.

Tests

  • gl/wasm/test/journal-test.c, snap-test.c: the journal and the save and
    restore on the host under ASan and UBSan, hostile blobs included.
  • gl/wasm/test/check.mjs: the profile and save and restore stages in
    headless Chromium, on SwiftShader and on the host's GPU.
  • test/gl-gpu.test.ts, test/snapshot-gpu.test.ts, and test/api.test.ts's
    "GPU snapshot sessions": the device side, the renderer against fake
    modules, the snapshot point, the file section and its version, the
    renderer let go when createKernel() fails, and a booted machine inline
    and in worker mode with a fake renderer; no browser.
  • test/gl/unkernel-check.mjs --gpu-snapshot (step S): programs snapshotted
    while they run and restored in the page, in a second browser, on another
    WebGL2 implementation, and refused by another build.
  • test/gpu/check.mjs and flip-check.mjs (the quick checks for the
    virtio-gpu files): the device's snapshot refusal while a dumb buffer is
    held, and a restored machine running its KMS client again.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant