Compare commits

...
Author SHA1 Message Date
Xiaochi You 6527829878 Merge pull request #20 from reims-go/feat/win32-aio-rawdisk-perf
feat(win32): native AIO, raw device in-place, disk cache policy, and bumped fast QEMU
2026-12-05 12:30:18 +08:00
YXC0915 91c0ce917a style(reims-ctl): run rustfmt on qemu and runtime 2026-12-05 12:17:08 +08:00
YXC0915 5a2083b951 feat(win32): enable native AIO, raw disk in-place, disk cache policy, and fast QEMU runtime 2026-12-05 12:01:05 +08:00
Xiaochi You 82da699225 Merge pull request #6 from yxc0915/steelbrain/windows-usb-redir
🆕 Enable Windows USB redirection in the portable runtime
2026-12-04 21:49:52 +08:00
YXC0915 1adc8a59ce 🐛 Reconcile and harden Windows iPad enumeration
Keep the current Windows build, which already enables usb-redir. Preserve
successful initial enumeration when the device changes address before QMP
observes the attachment. Encode SuperSpeed EP0 size in bytes and publish
interrupt workers only after they have started.
2026-12-04 21:49:29 +08:00
Xiaochi You 6a1f03f862 Merge pull request #13 from yxc0915/steelbrain/pin-metal2vulkan-fixed-offset
Pin metal2vulkan fixed-offset draw batching
2026-12-04 18:25:24 +08:00
YXC0915 db0c7395f1 🐎 Pin metal2vulkan fixed-offset draw batching
Use the measured revision on the organization development branch and refresh the three workspace lockfile sources.
2026-12-04 18:17:47 +08:00
Xiaochi You 5f690a8165 Merge pull request #12 from yxc0915/steelbrain/merge-vulkan-mdi-pr3
Resolve #3 and merge opt-in Vulkan multi-draw indirect
2026-12-04 17:37:48 +08:00
YXC0915 410d4a3f59 🐎 Merge opt-in Vulkan multi-draw indirect
Resolve the draw-encoder conflict with the adaptation in steelbrain/reims-vgpu#206. Preserve encoded and refused outcomes and keep indirect batching disabled unless requested.
2026-12-04 17:21:04 +08:00
Xiaochi You 66a66b8c26 Merge pull request #11 from yxc0915/steelbrain/sync-upstream-0dc2233
Merge upstream Reims vGPU into the Windows runtime maintenance branch
2026-12-04 17:01:24 +08:00
YXC0915 79fdedd8f0 🐛 Preserve FileVault input during OpenCore renewal
Keep the existing tablet and keyboard EFI files and their UEFI input settings when the guest drivers are rebuilt. Verify the new image before replacing the old one.
2026-12-04 16:45:48 +08:00
YXC0915 f71a03f37c 🐛 Keep the scanout copy fallback scoped to fixed mode
Preserve upstream import refusal behavior for ordinary Windows and Unix scanouts. Describe the loopback endpoint without rustdoc HTML.
2026-12-04 16:26:34 +08:00
YXC0915 01df95a4a4 🐛 Use runtime clocks in the suspend paths
Keep snapshot timing and waits on the runtime monotonic clock, avoid overflow in the restored address range, and retain the pool test inspector.
2026-12-04 16:16:32 +08:00
YXC0915 f8f29ada50 🆕 Merge upstream into the Windows runtime maintenance branch
Integrate the upstream runtime and verified dependency pins. Preserve the Windows window handoff and GPU suspend state alongside the upstream device and rendering changes.
2026-12-04 16:14:04 +08:00
Xiaochi You e8a21294e6 Merge pull request #10 from yxc0915/codex/backport-processor-display
Backport the macOS processor display fix
2026-12-04 16:01:26 +08:00
YXC0915 2373afdd01 🐛 Backport the macOS processor display fix
Use the host CPU family when Apple provides a label for the x86 guest topology. Preserve explicit OpenCore settings and apply the change to a verified copy before boot.
2026-12-04 15:48:55 +08:00
千川白浪 e68e3ce939 Merge pull request #4 from reiasu2/fix/export-unattached-cb-deadlock
🐛 Fix snapshot save deadlock when >64 unattached surface caches are dirty
2026-12-04 13:51:42 +08:00
Anees Iqbal 0dc2233a33 👷 Run CI on pushes to development and master alone
CI / Linux, cargo xtask check (push) Canceled after 0s
CI / Linux, make check-ctl (push) Canceled after 0s
CI / Linux, rustdoc (push) Canceled after 0s
CI / Linux, QEMU and its unit tests (push) Canceled after 0s
CI / Linux, device tests on lavapipe (push) Canceled after 0s
CI / macOS, cargo xtask check --lints (push) Canceled after 0s
CI / macOS, cargo xtask check --tests (push) Canceled after 0s
CI / macOS, make check-ctl (push) Canceled after 0s
CI / macOS, rustdoc (push) Canceled after 0s
CI / macOS, guest tests (push) Canceled after 0s
CI / Windows, clippy and tests (push) Canceled after 0s
CI / Windows, make check-ctl (push) Canceled after 0s
The workflow ran on pushes to its own branch, steelbrain/ci-merge, while the
batch was brought up; the batch merges now, and that branch's trigger goes with
it. Pull requests and runs by hand stay.

(cherry picked from commit c8a16c0c4b65b3c8261543d0d5d74a196e94d891)
2026-12-03 18:38:41 -08:00
Anees Iqbal 1c8ae8006e 👷 Let the lavapipe job's failures fail CI
The job held continue-on-error until it had a green baseline. With its two
known failures expected by name, it reads green, and a failure it meets now is
a new one, which fails the run as every other job's does.

(cherry picked from commit bb91f5f234b87e4e86898d676f901d669fcb7353)
2026-12-03 18:38:41 -08:00
Anees Iqbal ca2da2413a 👷 Expect lavapipe's two ledgered failures by name
A job red on every run hides the next real red. The lavapipe job's two failures
in every run so far are known: a CPU device's host buffers inside the contexts'
range, and format 94 one LSB apart. A list names them, each under its reason,
and the job runs every other device test, which must pass, then each of the two
alone, which must fail. A third failure, or one of the two passing, fails the
job, which reads green at 622 passed and 2 failing as expected. nextest has no
expected failures of its own, so a script makes the two runs and reads nextest's
exit codes (100: a test failed; 4: the filter took no test). continue-on-error
stays until a run shows the job green this way.

(cherry picked from commit dac6b70fda20a1404a008c46300134e2e63e9984)
2026-12-03 18:38:41 -08:00
Anees Iqbal dfec5075e2 📝 Note the contexts' range a CPU device can reach [ci skip]
lavapipe's device addresses are the host process's own, and on GitHub's
ubuntu-26.04 runner it put a buffer of the host's in the process's mmap area,
inside [2^46, 2^47), in each of three runs, where the test that the host's
ranges lie outside every unit fails. The range's claim holds for the GPUs'
drivers measured; the doc now says where it stops.

(cherry picked from commit a416d7e576f7d674fac673e260d5c3d21ead2b12)
2026-12-03 18:38:41 -08:00
Anees Iqbal 066bff480f 📝 Say what CI runs and how long its jobs take [ci skip]
docs/development.md gains a CI section: the jobs of .github/workflows/ci.yml,
the ci profile that leaves the device tests to lavapipe and the lab, what stays
in the lab, the cache bound, and the first green run's cold times (run
47245616506) beside the lab's warm figures.

(cherry picked from commit bd93b39f1454c087e29c3c6cd74d566685893e86)
2026-12-03 18:38:41 -08:00
Anees Iqbal 7f029b1641 📝 Note the macOS runner's thread limits by the lanes test [ci skip]
The busy lanes test met a refused spawn on GitHub's macos-26 runner, whose
limits run 47245616506 printed: 2048 threads a process, 1333 a user, against
the M3 Max's 16384 a process.

(cherry picked from commit b369ddc6f757f59f1ba06a6bab79758755f6358d)
2026-12-03 18:38:41 -08:00
Anees Iqbal 91683f5bd0 🐛 Hold reims-vgpu's on_rt_ tests to the NVIDIA legs' device bound
The nvidia profile runs at most three tests that make a Vulkan device at a
time, so that a vkCreateDevice is not refused once the live devices hold too
much of an RTX 2080's BAR1. Its filter matched reims-vgpu's tests by on_vulkan
alone, and missed the five on_rt_ tests of graphics::vaapi::fill and gpu_copy,
which make an rt device too: with no Vulkan driver they fail, as the group's
tests do (potluck job m3-max-85816). They join the group.

(cherry picked from commit 880d134a5d668250bad1784de5391d8ccb99b56c)
2026-12-03 18:38:41 -08:00
Anees Iqbal 65435d7272 ✅ Keep the texture release count bound off CPU devices
released_textures_go_while_the_gpu_stays_busy_on_vulkan bounds the textures rt
keeps at the end of its load by the command buffers in flight and 12 more, for
its threads' lag. On a CPU device the work runs on the processors rt's threads
run on, and the count there says how far they lagged: lavapipe on GitHub's
ubuntu-26.04 runner kept 1998 of the 3000 (bound 750), and every gauge came
back to where it started once the work was done, so nothing was kept.

The test reads the device type from rt's physical device. On a CPU device it
passes once the gauges come back inside the same 10 s poll, without the count
at the load's end; on any other device both checks stand as before. Three
tests without a device pin the decision: the count fails on a GPU, a load whose
gauges come back passes on a CPU device, and a planted leak, gauges that never
come back, fails there.

(cherry picked from commit 905457c64f5289ab42e4b032c8b912472d6babb4)
2026-12-03 18:38:41 -08:00
Anees Iqbal 7dacf2e3e4 👷 Print the macOS test job's thread limits
The busy lanes test hung on the macos-26 runner (36464eaec6), as it does on
Linux where a lane's thread is refused, and the runner's limits on the threads a
process and a user may have are read nowhere: the macOS test job prints them
before its tests.

(cherry picked from commit 9b9f64f13d4f368bce2fc10ed5e80570871fa569)
2026-12-03 18:38:41 -08:00
Anees Iqbal 8f28ed48e5 ✅ Keep the busy lanes test off its own gate
busy_lanes_hold_one_thread_each_and_the_budget_s starts 2048 lanes and the
budget's 16 threads, each job waiting at a gate the test's thread opens once
they all run. Where the host refuses a lane its own thread, Lane::start runs
the lane's jobs where they are taken, on the caller: here the test's thread,
whose job then waited at the test's own gate, which only that thread opens.
The hang is the test's own: its gate on the caller's thread. On GitHub's
macos-26 runner it held cargo xtask check from 23:46Z to the job's 120-minute
limit (run 47227233764).

A job on the test's thread now counts itself and passes; the assertions stand.
Under ulimit -u (the user's threads + 1200) on Linux the test hung before the
change (killed by timeout at 180 s) and passes after it, and it passes with no
limit before and after (job m3-max-86322).

(cherry picked from commit 386bd1a92b20ab72895a0afb91e1b8b17433b3c4)
2026-12-03 18:38:41 -08:00
Anees Iqbal a40855b1fe 👷 Cancel a branch's old run on its new push
A run waited behind its branch's run in progress: on steelbrain/ci the run of
e7186458af stayed pending behind a macOS job that had passed its hour, with
nothing able to cancel it. cancel-in-progress is now true for every ref but
refs/heads/development and refs/heads/master: the expression compares
github.ref, the full ref name, with those two, so a push to any other branch,
and a pull request's run, whose ref is refs/pull/N/merge, cancels its ref's run
in progress, while on the two public branches a new run waits for it as
before.

(cherry picked from commit fa196eb50438c3b9df7b96db642a7327a7be0a5d)
2026-12-03 18:38:41 -08:00
Anees Iqbal 6d49f00ff9 👷 Refuse cargo xtask check --lints with --tests
Each flag drops the other half of the check, so the two together ran no step
and answered ok. The pair is now an error that says so; one flag, or neither,
runs as before. A test of check_halves pins each case.

(cherry picked from commit 6b80ffb86eb55349796eab9b2e9ef9bf8dbaa456)
2026-12-03 18:38:41 -08:00
Anees Iqbal 03d35b5549 🎨 Lay out the renamed stitched test as rustfmt does
The on_vulkan prefix took the fewer-parameters test's signature past rustfmt's
width, and rustfmt puts its brace on a line of its own.

(cherry picked from commit 52de7bbe3c03a9e99bebc547e567a2e0787bfe14)
2026-12-03 18:38:41 -08:00
Anees Iqbal 958e53b3a2 👷 Split the Mac's check into its lints and its tests
On the macos-26 runner, cargo xtask check ran past an hour in the first run,
over the hour a CI job may take. cargo xtask check takes --lints, every step
but the tests, and --tests, the tests alone (on a Mac with the test binaries'
links and core's tests under Rosetta); with neither it runs every step, as
before. CI's macOS check is two jobs, one for each half, each building on its
own runner.

(cherry picked from commit e82e4f90654997b27b4e616eb467dd5a0a9b3fb1)
2026-12-03 18:38:41 -08:00
Anees Iqbal 71c62c7c7b ✅ Name the Mac stitched-function tests as device tests
made_here_a_stitched_function_links_and_computes_as_metal_s and its
fewer-parameters sibling, macOS-only, run the stitched library through the
decoder on RtPlatform, which makes an rt device: with no Vulkan driver beside
the test binaries they fail at the device's unwrap, the only two of 2596 that
did on the M3 under the ci profile (job m3-max-86070). Their names gain the
on_vulkan prefix their Vulkan-platform siblings carry, by which nextest's ci
profile leaves device tests to the lab and to lavapipe. Nothing else changes.

(cherry picked from commit 499d35b21b25a6e87ff13b6569ee970ffdb48378)
2026-12-03 18:38:41 -08:00
Anees Iqbal 8ba1f66e54 👷 Give the lavapipe job's image cc and git
The first run's lavapipe job failed four tests for want of a tool the image
does not hold: the C API's harness tests and its header's C++ compile run cc,
and the build stamp's test runs git. metal2vulkan's image pins neither, and its
script stays as it is: the job installs gcc and git into the image the script
built, from the pin's own Arch Linux Archive date through the build's
pacman.conf, package cache and databases, and keeps the image under its tag,
which the script's run takes. The downloads' cache key names what the job adds.
No test is skipped.

(cherry picked from commit 9ba94f198dae1d4bc79c96c6e4e9d981152ee4d9)
2026-12-03 18:38:41 -08:00
Anees Iqbal 66d3fce2d0 👷 Run the guest's tests on the Xcode 27 image
The Metal bundle builds against the macOS 27 SDK, whose Metal types it names
(MTLTensorPlaneType among them), and macos-26's default Xcode, 26.6, has no
such types: the first run stopped compiling RgfxCommandObjects.mm. GitHub's
xcode-27 image runs macOS 27 with Xcode 27.0 to 27.2; the job takes 27.2, the
lab's, and the image's Metal toolchain with it.

(cherry picked from commit ce71d2e890123e97f4e3f8e68204b2944c5e0f27)
2026-12-03 18:38:41 -08:00
Anees Iqbal 4ae5d7bd91 👷 Measure the cache where a job has no target dir
The bound step ran du on target and crates/*/target, and a job that builds
only one of them made du exit 1. Under Git for Windows' bash, which runs a
step with pipefail, that failed the step, and with it both Windows jobs, whose
checks had passed.

(cherry picked from commit da73263fcf3d77627d013cb3674190834da3c77b)
2026-12-03 18:38:41 -08:00
Anees Iqbal 7ec90011df 👷 Find the lavapipe image without --locked
The committed Cargo.lock has no source lines for metal2vulkan, and cargo
writes them back on its first run, so cargo metadata --locked would refuse
before the job finds metal2vulkan's checkout. The image's script is run
through bash, whatever mode cargo's checkout gave it.

(cherry picked from commit 21d996a156c17a5139660b4747a3b79f65ddfb67)
2026-12-03 18:38:40 -08:00
Anees Iqbal fb51515661 👷 Run CI on pushes to its own branch until it merges
A push of a branch that the push trigger does not name runs nothing, and a
manual run needs the workflow on the default branch, so the workflow's own
branch needs the trigger for its runs. It is steelbrain/ci-merge, the batch
rebased onto development: steelbrain/ci, where the workflow was brought up,
would take the rebase only by a force push. The batch's last commit removes it.

(cherry picked from commit 1e16e3ada747075107d4a4b578001c30d831343a)
2026-12-03 18:38:40 -08:00
Anees Iqbal 715363f8ee 👷 Run CI on GitHub for Linux, macOS and Windows
The owner asked for CI on all three platforms for what needs no GPU and no
guest, as a check beside the lab's legs. Each job mirrors a lab check:
cargo xtask check on Linux and macOS, make check-ctl on all three, rustdoc
with -D warnings for Linux, Windows and macOS, make qemu and the fork's unit
tests and qtests on Linux, the guest's tests on macOS (the image's Xcode has
its Metal compiler), and on Windows, in MSYS2's CLANG64 with the gnullvm host
toolchain, the two clippy runs and the library crates' tests.

The tests run under nextest's ci profile. The device tests it leaves out run
in a job of their own on lavapipe, in metal2vulkan's pinned lavapipe image,
which does not fail CI until a green baseline exists.

Images and actions are pinned (ubuntu-26.04, macos-26, windows-2025; actions
by commit). Permissions are read-only, nothing reaches the lab, and QEMU's
three meson subprojects come from QEMU's mirrors on GitHub at the commits
their wraps name. rust-cache saves on development alone, and a job whose
target directories pass the bound saves cargo's home alone.

(cherry picked from commit b387ac365cdb3528aa7f990284a6da52b350f66d)
2026-12-03 18:38:40 -08:00
Anees Iqbal ef5343d3ef 👷 Add a nextest profile for runners without a GPU
GitHub's runners have no GPU, so CI needs the tests that make no rt device
apart from those that do. The nvidia profile's vulkan-devices filter already
names the tests that make a Vulkan device; the ci profile's default filter is
everything else, less reims-vgpu's tests named on_rt_, which make one too and
which that filter misses. A run on Linux with no Vulkan driver failed 218 of
3,439 tests, each inside this set.

CI selects the profile with NEXTEST_PROFILE=ci, so cargo xtask check runs
unchanged there, and runs the device tests on lavapipe with the filter turned
over (--ignore-default-filter -E 'not default()').

(cherry picked from commit b7e5939efde61e5ee0771814ab8e7767b18cad62)
2026-12-03 18:38:40 -08:00
Anees Iqbal 6cde0d62da 📝 Record the boot of a host without AVX2's own CPU line [ci skip]
docs/qemu.md records the boot of the line an Ivy Bridge-EP host now gets
(potluck job m3-max-86438, by job m3-max-86342's method): macOS 26.7.2 on
it, with the Xeon E5-2697 v2's brand string, starts its kernel and stops at
its first process, as under reims-ctl's Skylake line with AVX2 hidden, and
QEMU warned of no feature.
2026-12-03 18:31:24 -08:00
Anees Iqbal 6d63f3b212 🆕 Name no CPU model or feature a host without AVX2 lacks
On a host whose CPU lacks AVX2, reims-ctl's line named
Skylake-Client-noTSX-IBRS, and QEMU dropped its AVX2 and the rest of what
the host lacks, warning of each under check. The owner asked that such a
host not be given Skylake. Its line now names no model the host's CPU is
not and no feature it lacks, read from CPUID with no setting: the newest of
IvyBridge, SandyBridge, Westmere and Nehalem whose features the host has
(the -IBRS variant where it has IBRS), + each feature of
Skylake-Client-noTSX-IBRS that the host has and that model lacks, and the
VM's flags without reims-ctl's own whose feature the host lacks (+avx on a
CPU without AVX). An AMD CPU gets the Intel model whose features it has. A
VM with a model of its own in vm.toml keeps it.

On an Ivy Bridge-EP Xeon the line is
IvyBridge-IBRS,kvm=on,vendor=GenuineIntel,+invtsc,vmware-cpuid-freq=on,
model-id=<its brand>,+pcid,+ssse3,+sse4.2,+popcnt,+avx,+aes,+xsave,
+xsaveopt,check.

What changes for the guest on such a host: its feature bits are those it
had, since QEMU gave it only what the host has before too, except KVM's own
x2APIC, TSC deadline timer and ARAT on a CPU whose CPUID lacks them
(Westmere and older, AMD's FX); the CPU model behind them is the host's
kind, so CPUID's family, model and stepping are Ivy Bridge's (or older)
where an image's OpenCore leaves leaf 1 alone (reims-util's images replace
them with Skylake-SP's), and so is the name where the host's CPU gives no
brand string. It does not boot macOS 13 or later there: their first
process still fails, so the create refusal stays.

model_without_avx2 is a function of the host's features, tested on five
CPUs without AVX2 and one with it; the -cpu line's test takes an Ivy
Bridge-EP's features through it and holds the whole line.
2026-12-03 18:27:56 -08:00
Anees Iqbal 1ba338a6b7 🐛 Refuse x86-64 macOS 13 and later on a CPU without AVX2
reims-ctl refused only macOS 26 on a host whose CPU lacks AVX2. The lab's
boots show 13, 14 and 15 stop the same way: macOS 13.7.8, 14.8.9 and 15.8.2
under KVM on a Core i9-13900H, each on reims-ctl's Skylake line with -avx2
(potluck job m3-max-86386, AVX2's absence read with QMP's qom-get): the
kernel (Darwin 22.6.0, 23.6.0, 24.6.0) starts and mounts the system, then
launchd cannot load libSystem ("no dyld cache"), the kernel panics,
"initproc failed to start", and the VM restarts, six times in each boot's
2.5 minutes, as 26.7.2 did (jobs m3-max-86342 and m3-max-86386: on that
line with -avx2, on IvyBridge-IBRS, and on that line with every feature an
Ivy Bridge lacks hidden). No boot stopped at OpenCore's handoff.

AVX2_FROM_MACOS moves from 26 to 13, so a create of macOS 13 or later on
such a host is refused before its download, where it ended in a VM that
restarts at its first process after an install of hours; macOS 12 and
earlier, which no boot here ran without AVX2, are made as before. Doctor's
cpu line now says x86-64 macOS 13 and later need AVX2
(host::without_avx2_from), where it named macOS 26; the refusal's reason
names no single release's libraries. The tests that held 26 as the bound
hold 13: macos_13_and_later_is_refused_on_a_cpu_without_avx2 refuses 13,
14, 15 and 26 and not 12, and doctor's test reads the new line.
docs/qemu.md records the boots.
2026-12-03 18:25:07 -08:00
Anees Iqbal 16211f606d 🐛 Read the snapshots of a qcow2 disk over a backing file
reims-ctl's qcow2 reader refused an image over a backing file, though an
image's internal snapshots, their table in its own header, their L1 tables
and the clusters they count are all in its own file. On a VM whose qcow2
disk is over a backing file (a disk given at a create, which copies it as it
is), a take succeeded through qemu-img, its space read "unknown", the restore
refused with "no longer holds the snapshot", and a delete left the internal
snapshot in the disk: the snapshot manager's run on the Windows mini over an
overlay of a desktop disk (potluck job m3-max-86292) failed its restore, and
the same run on a standalone qcow2 (m3-max-86294) passed. The reader is the
same on every host. It now reads such an image as any other; a cluster the
image never wrote reads from the backing file, is in no L2 entry, and is held
by no snapshot.

(cherry picked from commit 7010a2cec80acb52d73abb15f10e36aea289b0f3)
2026-12-03 18:09:41 -08:00
Anees Iqbal 802a51bec5 🐛 Say what macOS 26 needs AVX2 for: its system libraries
reims-ctl refused an x86-64 macOS 26 VM on a CPU without AVX2 saying its
kernel stops with an invalid-instruction fault as it starts, from one
user's report. The lab's boots say otherwise. macOS 26.7.2 under KVM on a
Core i9-13900H, with AVX2 hidden from the guest (QMP's qom-get read it off),
under reims-ctl's own CPU line with -avx2 and under IvyBridge-IBRS, which
also lacks FMA, BMI1, BMI2, MOVBE and the rest of Haswell's additions: the
kernel starts and mounts the system, launchd cannot load libSystem ("no
dyld cache"), the kernel panics ("initproc failed to start") and the VM
restarts, six times in about 155 s each boot. Neither stopped at the
handoff.

So the refusal stays, and its message, which doctor's cpu line shows too,
now names the cause: the system libraries are built for CPUs with AVX2
alone, so the first process cannot start and the VM restarts over and
over. AVX2_FROM_MACOS's doc and docs/qemu.md record the boots. Public
reports say every macOS from 13 is built so; no earlier macOS was booted
without AVX2 here, so the bound stays at 26.

(cherry picked from commit 31b9145b073877827e5a88d8c3d2407b5961dbe4)
2026-12-03 17:58:37 -08:00
Anees Iqbal 2aacf51fcb ✅ Run the update test's sleeper as this test binary
linux_names_a_replaced_running_binary_deleted copies /bin/sleep to "sleeper"
and runs the copy. On GitHub's ubuntu-26.04 runner /bin/sleep is uutils' one
binary of every utility. 837b29e48b ran the copy with argv[0] "sleep", on the
claim that uutils picks the utility by argv[0]; it picks it by its
executable's file name, and the next run there failed the same way: "coreutils:
unknown program 'sleeper'", then no /proc entry for the child (run 47237404825,
job 144740558610). That fix's proof ran only on GNU coreutils, where the test
passed before it and after it.

The test now copies this test binary and runs it idling in install's idle
test, as the prune test runs its QEMU, so it depends on no coreutils. A lesson
says what proves such a fix.

(cherry picked from commit c9a70082a7cbb8e0d5d7b8a88ac2d11b093cddc7)
2026-12-03 17:40:30 -08:00
Anees Iqbal 8058eaf651 📝 Say what the second drop's warp did under XWayland [ci skip]
The walk's two drops through XWayland parted after the warp. After the
first, the next move of the mouse took XWayland's pointer back to KWin's.
After the second, XWayland's pointer moved on from the warp's point, 168
points from KWin's, and the guest's cursor followed it, away from the
pointer the person sees; so the commit before the register's change also
ends that offset, where its message said the guest saw the same as before.
The doc of warp_moves_the_pointer and the lesson now say both.

(cherry picked from commit ed2fd91feb0884d3a9e365d75dfb67038ce124c0)
(cherry picked from commit 5a1714d358e6504d18e9736a47302767ac6f3cdb)
2026-12-03 17:36:42 -08:00
Anees Iqbal 1589237536 📝 Register a drop leaving the pointer be under XWayland [ci skip]
The register said SDL's warp places the host's pointer through XWayland too.
The walk on KWin 6.8.3 with Xwayland 24.1.15 showed it does not, and the
window now leaves the pointer where it is in a Wayland session, XWayland's
windows included; the entry says so, guarded by the test of that choice.

(cherry picked from commit f8eaff14bd4e658afb9c024fa419ff7b6c91259a)
(cherry picked from commit d64acff2ae5a51de15c1117e478f38e6652aa6bf)
2026-12-03 17:36:42 -08:00
Anees Iqbal 3eec04635d 🐛 Leave the pointer where it is at a drop under XWayland
The two-display walk on KWin 6.8.3 with Xwayland 24.1.15 (potluck job
m3-max-86210) showed that SDL's warp at a drop through XWayland moves only
XWayland's own pointer: an X client read it over the guest's cursor while
KWin's stood 50 points short, and the next move of the mouse took XWayland's
back to KWin's. The drop now warps only where SDL's driver speaks to the
session's own window system, an X server or Windows, and in a Wayland
session leaves the pointer where the other window let it go, as on Wayland.
The guest sees the same as before: its cursor follows the host's pointer at
the next move. docs/lessons.md records the trap.

(cherry picked from commit 38fc18662d4fe4c7d28e0aab308dc3d426067347)
(cherry picked from commit e865e0283db939c70d029d7f23b4aec959bb6445)
2026-12-03 17:31:26 -08:00
Anees Iqbal 2e7dbe9a87 ✅ Quote the GPU copy's reworded module doc
The hand-over table quotes gpu_copy.rs's module doc in rows 32 and 18 (how a
picture reaches the scratch) and rows 33 and 19 (a copy that failed once
submitted). The fake leg's commit reworded the first sentence to name the
scratch's two sources, VA-API's video processing and the video harness's
fake arm, and the lingering-copy fix wrote "planes" for "caches" in the
second, so neither quote matched and
handovers::the_hand_over_table_names_only_what_the_tree_holds failed on
every test leg. The four rows now quote the module doc as it reads.

(cherry picked from commit b3c18cc8d1d067a2ac29955b5285908d001c6fc8)
2026-12-03 17:28:32 -08:00
Anees Iqbal 0bc27ebcd5 🐛 Keep a GPU copy whose wait failed until its command buffer ends
The VA arm's GPU copy (ScratchCopier) took a copy whose wait failed, or
returned with the copy unfinished, as one the GPU may run still: it kept
the copy's scratch and arguments out of use and failed the picture, but
nothing held the planes the copy writes. On the lent path (an arm64
guest's surface, VaGuestDecoder) the decoder answered at once, and the
surface went back to the guest while the copy could still write it; on the
cache path (an x86-64 guest's device caches, the video host's landing) the
landing signalled the decode with the copy perhaps still writing them.

The copier now keeps such a copy on Lingering until its command buffer
ends, from the thread that ran it, as the driver's work past its deadline
is kept. What changes for the guest: after a failed or unfinished copy
wait, the surface comes back, or the decode signals, only once the copy
ends, within the 10 s hold (STALL_HOLD: vt's answered_once_written on the
lent path, video_host's hold_stalled_landing on the cache path, each
counted and logged as a held stall). Past the hold the process dies at a
fault of the decode, so the guest's VM ends. On the rt platform no wait
fails, and only a wait rt refuses (on its completion thread, or in a
scheduled handler) returns unfinished, which no run of the video's paths
reaches; a lost device ends the copy in an error, which the wait returns
on.

Tests: the fake leg's copied mode loses a copy's wait (the fake platform's
waitUntilCompleted raising, as a lost device's does) at a seeded frame, and
at two frames, after which the session's GPU copies end and the rest land
in place; a video host test lands a picture through the copier's cache
path with its wait lost, and sees no signal until the copy ends; a unit
test of the copier holds the keep and its release, for a failed wait and an
unfinished one. Red: job m3-max-86148, the seeded test without the keep:
seed 1's surface 3 went back at 6.700 s while the copy into it ran to
7.000 s, and was written after it went back; and m3-max-86214, all four
tests on this tree without the keep, the video host's with its decode
signalled while the copy ran.

(cherry picked from commit 1fbe2f6c56d6fb9ede407fe5384019565ce24ecf)
(cherry picked from commit 6a0920959008443505bb5c654090b49cc83f165c)
2026-12-03 17:28:32 -08:00
Anees Iqbal 838f5cf74a ✅ Land fake-leg pictures through the VA arm's GPU copy
The video harness's fake leg could not reach the VA arm's GPU copy
(ScratchCopier): its arm wrote each picture into the lent surface by its
device, and the fake platform made a dma-buf buffer with no memory and
exported none, so the copier refused its scratch. The copy's fixes (one
failed copy's buffers kept out of use, a wait that returns unfinished taken
as failed) had only the card leg and the copier's unit tests behind them.

The testkit: a world that is asked to (World::give_dma_buf_memory, off by
default) backs each dma-buf buffer, on Linux, with a memfd's shared mapping
of its own whatever its storage, and its export_dma_buf hands out the memfd,
so that a write through the export lands in the bytes a stand-in reads.
World::runs_stand_in says whether a committed command buffer holds a
stand-in's dispatch. A stand-in now reads a buffer over the caller's memory
once and writes back what it wrote once, as each call of the fake address
space syncs every alias byte by byte. A command buffer's status now reads
completed only once its stand-ins have written, as its comment said: it was
set first, so a poll of the status could see the copy done before its
writes. The new unsafe is in guest_ram.rs, under its grant: memfd_create,
ftruncate, mmap and munmap of RawRegion::shared.

The copier takes a picture of any source (ScratchSource): VA-API's frame,
as before, or the fake arm's. Both of its paths take one: the copy into an
x86-64 guest's device caches (GpuCopier::copy, copy_picture) and the copy
into a surface an arm64 guest lent (GpuCopier::copy_into_lent,
copy_picture_into_lent). The fake arm's copied mode, on Linux, takes the
lent path as VaGuestDecoder does, through the buffer the session makes over
the surface at its ask: it writes each picture into the copier's scratch
through its dma-buf, and the copier copies it into the surface by
videoEncodeFill's stand-in; a thread of the fake GPU completes the copy
once Point::WriteWait's delay has passed. Its fault is a copy that ends in
an error. The cache path, which shares the scratch, the kernel and the
waits, is not reached; its refusal of a plane in the guest's pages is held
by a unit test of its own.

With the copier's wait removed, every copied-mode test fails (job
m3-max-86105, before the rebase onto the lent path; and m3-max-86177 on this
tree). Nothing changes for the guest or the host: the copier does what it
did, and the rest is test code.

(cherry picked from commit 2b67496b6e2f70a36aa318fc321f7e3726344853)
(cherry picked from commit bec676a665ac6fb4bbbc7f796b78dc5bf07a9108)
2026-12-03 17:28:32 -08:00
Anees Iqbal 1880243f85 📝 Register a drop on the cursor and macOS's drag past [ci skip]
The window's register says what the previous commit changed: on X11 and
Windows the drop of a drag gone past a shared edge puts the host's pointer
over the guest's cursor, on Wayland it cannot, and on macOS a drag goes on
past an edge where the guest placed another display, and ⌃⌥⌘ lets it go.
The entries name the tests that guard them.

(cherry picked from commit a5884ed2661df67265af48e35811ed50a15b62bf)
(cherry picked from commit 0729018e74776fffb1bc2cbbfd6ffbf7113760fc)
2026-12-03 17:28:32 -08:00
Anees Iqbal 0469a256bd 🆕 Carry a drag past the edge on macOS and drop it on the cursor
On Linux and Windows a drag gone past a shared edge onto another display and
ended there left the host's pointer where the window had held it, at the
edge it left, while the guest's cursor was on the other display, so the next
move took the cursor back. The desktop is now told the drag dropped
(PointerBeyond::dropped), and the window of the display the guest's cursor is
on puts the host's pointer over the cursor (SDL's warp: X11, XWayland and
Windows). Wayland lets a client place the pointer only over the surface it is
over, so there the pointer stays where it was, and the window logs why.

On macOS a drag stayed held at the image's edge. It now goes on past an edge
where the guest placed another display, as on Linux: the window holds the
host's pointer still (CGAssociateMouseAndMouseCursorPosition) and hides its
cursor, the drag events' deltas move the guest's cursor, and the drop puts
the pointer over the cursor (CGWarpMouseCursorPosition), documented calls
that ask for no permission. The release chord, the keyboard lost and closing
let the drag go where the pointer was held, as on Linux.

The drag-end tests of beyond and of the SDL input now expect the desktop
told that the drag dropped, and are renamed for it.

(cherry picked from commit aec994f8478a371352dbedde03b1b67cdc44ec69)
(cherry picked from commit c4a3fedfdfeb9bf884cd2756a4558a8b896ef41c)
2026-12-03 17:28:32 -08:00
Anees Iqbal 1f049d30a0 🐛 Make the windows' UI thread's jobs steps of the exit gate
A QEMU realized paused (-S) and quit 3 s later ended in SIGSEGV (potluck
m3-max-86030, an AMD host with NVIDIA's driver installed): QEMU's cleanup
quiesced the library, the quiesce answered that the process may exit, and
exit() ran the exit handlers while reims-vgpu.ui was still in the window's
opening, where SDL_CreateWindow with SDL_WINDOW_VULKAN had the Vulkan loader
start NVIDIA's driver. The UI thread's jobs were no steps of the exit gate, so
the quiesce did not wait for them.

SDL's video start and each job posted to the UI thread on Linux and Windows
are steps now, each job's begun where it was posted. For the host: a quit
that comes during a window's opening waits for it, and where the opening
outlasts the quiesce's bound (QEMU's 5 s) QEMU ends with _exit, so the
driver's exit handlers never run beside it; a job taken after the gate closed
parks the UI thread unrun.

The test runs the UI thread's job loop in a child process, an opening held
300 ms with a job queued behind it. Before the change a close of the gate
with a 50 ms deadline answered true during the opening and the job behind it
ran (red on Linux, potluck m3-max-86131); after it, 158 of 158 of the window
crate's tests pass there (m3-max-86135).

(cherry picked from commit 2454db1085bb74e8dfc147726e1c268d1811386f)
(cherry picked from commit 0a2738f8586555273a76b2f22f45103aa4beacd4)
2026-12-03 17:28:32 -08:00
Anees Iqbal 3fb4e7ac18 ⬆️ Build on metal2vulkan development 865592b96b
Pin W, from 133c992dad (V): 33 commits, among them the bless commits
b4d134337b and d70e728f4c. SEMANTICS_VERSION 2370, ARTIFACT_FORMAT 609,
RUNTIME_VERSION 2571.

What changes for the guest:
- A kernel's [[stage_in]] attribute read by thread position through a
  layout of MTLBufferLayoutStrideDynamic now makes its compute pipeline
  state and is fetched at the stride its buffer's bind gives
  (setBuffers:offsets:attributeStrides:withRange:,
  setBufferOffset:attributeStride:atIndex:, and the guest's
  setBuffer:offset:attributeStride:atIndex: and
  setBytes:length:attributeStride:atIndex:, which arrive as those). Before,
  the state was nil with an NSError, counted as StageIn-DynamicStride. A
  bind without a stride binds a stride of 0, as an M3 Max read it, where
  Metal documents no answer.
- A viewport depth range past [0, 1] is taken: draws where nothing reads
  the window z draw. A draw under such a range into a pass with a depth
  attachment, or through a fragment function that reads [[position]]'s z
  or w, is refused at the draw (Gap::Draw, Draw-Viewport). Before, rt
  refused the viewport itself where it was set, wherever it covered a
  pixel.
- VK_EXT_extended_dynamic_state is enabled where the device lists it.
- The translator's sparse path is gone: a texture's residency query answers
  resident.

What changes on our side:
- rt_platform::compute binds the attribute-stride calls with their strides
  (set_buffer_with_attribute_stride and
  set_buffer_offset_with_attribute_stride); before, they bound as the calls
  without them. a_kernel_s_stage_in_is_fetched_by_the_stage_in_region_on_vulkan
  now fetches a dynamic layout at strides 8 and 12, where it held the
  refusal.
- diag no longer names StageInKind::DynamicStride, which metal2vulkan
  deleted; refusals_count_by_kind counts the one stage-in form left.
- The accuracy ledger's stage-in paragraph says so, and render's module doc
  names the draw-time Draw-Viewport refusal.

(cherry picked from commit b3c30fb80d6c12304626815c7e76707c012074fc)
2026-12-03 17:21:45 -08:00
Anees Iqbal 40252bcbd6 🐛 Move QEMU to pool pieces that a passed-through device can't end
A VM with a PCI device on vfio-pci beside reims-graphics-pci ended as the
guest's graphics driver took its first Shared pool piece: vfio's listener
maps every RAM section into the IOMMU for the passed-through device's DMA,
the kernel refused the map of a piece (a block of the GPU's memory), and
QEMU stops with "vfio: DMA mapping failed, unable to continue" when that
happens to plain RAM at run time (issue 213). The reporter's working build
was 11-15's (its kext set hashes to 96272e8b4d's), before the pool came in on
11-17.

vendor/qemu d20c59a1 -> f073adfb (325206b3 on 215's fork commits): each pool
piece is now a RAM device, whose
refused map vfio reports once as a warning. Nothing else changes for the
guest or the host: KVM, WHPX and HVF map a RAM device as memory, and TCG and
other devices' DMA reach it directly, as before. A refused map does mean the
passed-through device can't DMA into a piece, which it couldn't before
either: QEMU stopped instead. docs/qemu.md's fork table has the commit, and
docs/lessons.md has the trap.

(cherry picked from commit efd9844268cb001b31a5d08b83916ee96004551a)
(cherry picked from commit 01384f8ee30b37491eea9cd2fc998c2e7e916c9b)
2026-12-03 17:05:48 -08:00
Anees Iqbal f4520cb4f8 ✅ Move vendor/qemu to its install-tree test's fix
vendor/qemu moves to d20c59a1, whose tests/symlink-install-tree takes the
script's whole path: run from the source tree with a relative one, every
case failed, as it runs the script in a build directory of its own.

(cherry picked from commit 7bb7e1eefb65f873055b2ddc38173ba1432672ed)
(cherry picked from commit 8cb12aeb45b842c3b63b46aa80a060a0c5a050b3)
2026-12-03 17:05:41 -08:00
Anees Iqbal 190df5e42a 🐛 Configure QEMU where Windows refuses a symbolic link
vendor/qemu moves to 82840252. On a Windows host without Developer Mode or
an administrator's rights, scripts\install.ps1 stopped at "Configuring
QEMU": QEMU's scripts/symlink-install-tree.py links each installed file
into the build's qemu-bundle, os.symlink fails there with WinError 1314,
and the script raised on every error but EEXIST.

Where the link is refused, the script now copies the entry instead, and
leaves out an entry built after the configure step, with one line saying
how many of each. The bundle serves only a run from the build tree;
install-ctl.sh installs QEMU with ninja install, which installs from the
build, so the installed QEMU does not change. The fork's
tests/symlink-install-tree runs the script with os.symlink refused, and
where the host makes links.

docs/qemu.md carries the fork's row.

(cherry picked from commit 08a083580552a9f019fa23836e76123ee0cd9f54)
(cherry picked from commit 103d1f1e1c444aee38fd84941f80fdeefa90fe09)
2026-12-03 17:05:41 -08:00
Anees Iqbal 3dbf9d9fc9 ✅ Find both cards past a manifest in the twins test
The test's second probe found one card through RADV's i686 manifest, but the
list keeps a GPU another manifest of another file name reaches (RADV and
AMDVLK on one card, both listed and marked as sharing IDs), so the list held
three entries and the test failed. A 64-bit probe loads no i686 driver; what
finds a GPU again is a probe that went past its manifest, here lavapipe's,
which the list drops for each card it already holds at that address.

Also lays out mark_shared and the doctor test as rustfmt does.

(cherry picked from commit 706cf65112149eae0f74efd8cb6c1a8a399b6df1)
(cherry picked from commit 0e2be5c7088f530b073fb60f431a4dd1a5defd99)
2026-12-03 17:05:41 -08:00
Anees Iqbal 63284bb99c 🎨 Lay out the reflink fallback's tests as rustfmt and clippy ask
rustfmt keeps keep_disk_for_eacs_with's signature on one line and splits the
copy test's first refusal; clippy's type_complexity refuses the refusals'
array type. The array now names its fn type, Refusal, and the first refusal
is a closure of that type, which rustfmt leaves on one line.

(cherry picked from commit 7e218104dea23875a972321f22fa097374ddb7d0)
(cherry picked from commit 2498d0174e3a760c1b486e1b2f596ba47fe423ce)
2026-12-03 17:05:41 -08:00
Anees Iqbal fbf8ac628f 🆕 Refuse to make an x86-64 macOS 26 VM on a CPU without AVX2
A user ran macOS 26.7.3 on a Xeon E5 v2 (Ivy Bridge-EP), which has no
AVX2: under reims-ctl's CPU model the guest stopped with an
invalid-instruction fault at OpenCore's handoff to its kernel, after an
install of hours. That report is the only evidence of which macOS needs
AVX2; nothing on file says an earlier one does, so the bound is macOS 26
and widens only on evidence.

A create of an x86-64 VM of macOS 26 on a host whose CPU has no AVX2 is
refused, naming AVX2 and the CPU: before the download where the asked
version names its release (a number, a release, a name or latest by
reims-util's list), and after it for a build number, which only the
download names. doctor fails its new cpu line on such a host. A start
refuses nothing: that user runs macOS 26 on such a host with CPU arguments
and kexts of their own, which a refusal at start would break, so a VM of
macOS 26 made elsewhere and moved to such a host still stops at the
handoff with no message of ours, and doctor is what names the cause.

(cherry picked from commit 8ccae1f6d7658c3732c1abea20b6ea2ce8f62afc)
(cherry picked from commit 68775589213b0ebbfe035105a3c13d80ee8d3d9f)
2026-12-03 17:05:41 -08:00
Anees Iqbal 706a913bea 🐛 List two GPUs of one model apart, and pick each by its address
A user's host with two FirePro D700s (1002:6798) listed one GPU in
`reims-ctl gpus`: the list took two GPUs of the same IDs, name and
manifest for one GPU reached twice, and a VM's settings name a GPU by its
IDs, which name the first of the two. The second card could be given to a
VM only through a variable of the user's own.

The probe now reads each GPU's PCI address where its driver lists
VK_EXT_pci_bus_info, and the list keeps GPUs at two addresses apart. A GPU
whose IDs another GPU of the list has is labelled and picked by its
address: its settings keep it (`pci`), and its VM's QEMU gets
DRI_PRIME=pci-DOMAIN_BUS_DEVICE_FUNCTION, which Mesa's device-select layer
reads and the library's device choice reads on every OS, with its IDs to
the loader and no MESA_VK_DEVICE_SELECT, which the library reads first. A
GPU alone of its IDs, and two whose driver gives no address, are named as
before.

(cherry picked from commit b1564dde68bafa546f671feec8772f35a688c143)
(cherry picked from commit 448ead196b8c6ec2d1e4cefcb27c48d5e979c7bd)
2026-12-03 17:05:41 -08:00
Anees Iqbal e46ed72450 ✅ Hold a refused reflink's fall back to a full copy
A user asked for a plain copy where the file system makes no reflinks,
as ext4. reims-ctl's disk and image copies and the restore's kept disk
already fall back to a full, sparse copy on any refusal of a reflink or
clone, whatever its error (since cc1b8a6c7d), but the tests held that
only where the test host's own temporary directory makes none, tmpfs on
the Linux hosts: the Mac's check, on APFS, never took the full copy.

The copy and the restore's disk keep now take their clone as an argument,
and a test of each refuses it, with a file system's "makes none" error,
another error and no OS error at all, on whatever file system the test
runs on. What either does is unchanged.

(cherry picked from commit 235e1ac2593ee782b3742f4be49a117b99ba8908)
(cherry picked from commit 36acd7a5fa7a9f12270b474de55558858d0eee70)
2026-12-03 17:05:41 -08:00
Anees Iqbal aa4eacee6e 📝 List the Mac host's encoders in the formats table [ci skip]
The encode docs left formats.md as it was before the Mac host's encoders: its
arm64 table's encode cells for the M3 still said N2, and N2 still called the
encoders not built. The H.264 and HEVC Main and Main 10 cells now name the
guest runs that required the hardware encoder and decoded each frame back
(m3-max-85341, 85616); Main 4:2:2 10, which the arm offers, has no run on file;
4:4:4, 12 bits and SCC are none listed, as the arm offers none of them. The
sources name encoder_offers and its job, and guest_encoders.

(cherry picked from commit b8c84171bd15e33e30472b93657d5389ad98e2d6)
2026-12-03 16:49:13 -08:00
Anees Iqbal afd4f730e2 📝 Say why a host of HEVC Main alone gets no encoder nub [ci skip]
The Main-only try (main 12-03) published the nub with Main alone on an RX 550
host: a Main session was made on the hardware encoder and its stream decoded,
but Main 10 sessions were made there too and emitted none of their frames, with
no error, where VideoToolbox encodes them in software without the nub. The
row closes with the rule kept: both profiles, or no nub.

(cherry picked from commit 456f352add62cf5f4df79dea1bf45eea354db375)
2026-12-03 16:49:13 -08:00
Anees Iqbal 82fa800e6e 🎨 Drop the close tests' second import of the runtime trait
The tests' module has Runtime in scope through its parent's, which clippy finds
the extra import unused beside.

(cherry picked from commit 6c8e36aea7e141a8ccc1cdec25de2b72b2275fbf)
2026-12-03 16:49:13 -08:00
Anees Iqbal 92f47db493 🎨 Time the close tests on the runtime's clock, rustfmt's layout
clippy disallows Instant::now in the video crate: the tests read StdRuntime's
clock instead, and a wait's Err is checked with is_err.

(cherry picked from commit 06abfa8ba8f096e3f59867f92389d8d8eb601d3f)
2026-12-03 16:49:13 -08:00
Anees Iqbal c1788757f2 🐛 Close every session at the paravirtual host's teardown
The class of the guest's close: the host's teardown, at the device's release,
dropped its sessions without closing them, so a session waiting for the guest
waited out its request and the emit behind it past the device's end. The host
now closes each as the reset does. Host implements Drop for it, so its
constructors set its fields rather than update a default's.

(cherry picked from commit b65293ecd33e8e940b8e1f645f2c02ec7b1e9636)
2026-12-03 16:49:13 -08:00
Anees Iqbal 75f0f33fe4 🐛 Close a session the guest closes, as the device's reset does
A guest's close of a session (-dec, -enc, -mep, -uui; every session at -all)
and a create that replaces a session of its UUID dropped the session without
closing it. Its thread then waited out a request to a guest that had let the
session go, sent it the frame's failure and waited out the emit, and carried out
the jobs queued behind. An arm64 guest's HEVC player that quit with a frame in
flight showed it: the kext's -uui for the dead client came while the session
waited for a buffer, and the frame took 11.1 s, with two buffer requests
timed out.

Each such session is now closed as the reset closes it: its requests waiting
for the guest end at once, it sends the guest nothing more, and its thread
carries out no message past the one in hand. For the guest: no Dbuf, Demt or
other message of a session after its close, and none of a replaced session that
would reach the new one under the same UUID.

(cherry picked from commit 105632302ed93dba1c5a4cd98c5452cecb9b3a11)
2026-12-03 16:49:13 -08:00
Anees Iqbal 522eee4447 ✅ Pin that a guest's close ends a session's buffer wait
Red: the host's close of a session (-dec, and the kext's -uui for each session
of a client that died) dropped the session without closing it, so its thread
waited out a buffer request (1.1 s) the guest would never answer, sent the
frame's failure to a guest that had closed the session and waited out its emit
(10 s), then asked a buffer for the frame queued behind it. An arm64 guest's
HEVC player that quit with a frame in flight showed it: one frame of 11.1 s
and two buffer requests timed out.

(cherry picked from commit 638152d250303185b129118e5cd0b489d0371c36)
2026-12-03 16:49:13 -08:00
Anees Iqbal 09dab515d5 📝 Name the window's Linux-only items without links on Windows
rustdoc for x86_64-pc-windows-gnullvm (lint leg 2, m3-max-86047) failed on
two intra-doc links in module docs every target builds: sdl.rs's to
Input::keyboard_taken and ui.rs's to x11_event, both items of Linux's alone.
Each is named as code without the link, as the docs name other items of
one OS.
2026-12-03 16:42:35 -08:00
Anees Iqbal 86e0342f8a 📝 Say KWin's Overview under XWayland is no X grab [ci skip]
The X11 rows on gem10 (potluck m3-max-85904, KWin 6.8.3 through XWayland)
showed the guest's Command key held down for 3.8 s after the release chord
and Super+W, until the Overview closed, with the window's hook of SDL's X11
events in place. The hook fires on FocusOut in NotifyGrab mode, which the run
logged at a click away and at the window's own grab, but KWin's Overview takes
the keyboard in the compositor and sent the window no such event.

The register, the input and SDL modules' comments named the Overview as the
grab the hook lifts keys for. They now say the hook covers another X client's
keyboard grab, and that the Overview sends no event: the key comes up as the
Overview closes. The hook stays. lessons.md records the trap: a fix built on
the event a protocol says a grab sends, where the grab is not made through
that protocol.
2026-12-03 16:42:35 -08:00
Anees Iqbal b0b1a2a996 📝 Say GNOME's Super+Escape gives the shell its keys back [ci skip]
GNOME's own Super+Escape, the key its inhibit question names, makes the
window's shortcuts inhibitor inactive until the window is focused again, as
the GNOME rows showed. SDL 3.4.18 passes over the inhibitor's inactive event,
so the title keeps naming the release chord meanwhile. The keyboard grab's
entry in the window's register says so, with the GNOME row in its manual
guard; the window has no help text that names the chord.
2026-12-03 16:42:35 -08:00
Anees Iqbal 9625002c62 🐛 Keep the app's delegate field without a dead-code error
With Release Input gone, nothing reads AppState's delegate: the menu's target
was the last reader. The field still keeps the delegate alive, since the
application holds it weakly, so it stays, marked as held and never read.
clippy -D warnings on macOS failed on it (potluck m3-max-85812).
2026-12-03 16:42:35 -08:00
Anees Iqbal 2f0734118c 📝 Describe the windows without capture [ci skip]
The windows have no capture any more: they grab the keyboard whenever they
have it, and hold the host's pointer only for a game's lock or a drag that
goes on past the image's edge onto another display. The docs and comments
that still described a captured pointer or input now say what the code does:

- api.md: REIMS_VGPU_WINDOW_CAPTURE's row and its line among the variables
  that change what the guest observes are gone.
- architecture.md: the window crate's grab, game and beyond modules replace
  capture, and macOS's hotkeys.rs is gone.
- design.md: a drag, not a captured pointer, crosses onto another display,
  and its last button up lets the host's pointer go where it is; the game's
  pointer runs while the window has the keyboard and the pointer is over the
  image; the release chord, not Release Input, leaves a hide to the tablet.
  Measurement records that ran with capture stay as they were.
- known-issues.md: the game entry's way out has no Release Input, and
  switching away and back stands for clicking back in.
- lessons.md: the X11 pointer grab lesson names the code as gone, and a new
  lesson covers SDL's Alt+Tab and Alt+F4 policies under the keyboard grab,
  as measured in potluck jobs m3-max-85442, 85443, 85483, 85459 and 85554.
- Comments in reims-vgpu and reims-vgpu-graphics: a drag's pointer, or the
  window's pointer, for "captured pointer". wire.rs's two such lines are left,
  since its docs go into reims_graphics_wire.h, which the guest's kexts and
  the option ROM compile, and a change there rebuilds both prebuilt sets.
2026-12-03 16:42:35 -08:00
Anees Iqbal 7b549308ed 🆕 Write an app entry for the VMs' windows at install on Linux
The windows grab the keyboard whenever they have it, and on GNOME that grab
is the shortcuts inhibitor, which GNOME Shell lets an app take only once the
person answers its "Allow inhibiting shortcuts" question. The shell keeps the
answer in its permission store for the app the window maps to; a window that
maps to no installed app is asked again at every focus (read from GNOME
Shell's inhibitShortcutsDialog.js).

So on Linux scripts/install-ctl.sh now writes
$XDG_DATA_HOME/applications/reims-vgpu.desktop (~/.local/share/applications
where XDG_DATA_HOME is unset or not absolute), named for the windows' app ID,
reims-vgpu (SDL_APP_ID), with StartupWMClass=reims-vgpu for X11. It is hidden
from the menus (NoDisplay=true), and its Exec is the installed reims-ctl's
absolute path, in a terminal. Every install and update rewrites it. A file
there without the install's marker line is someone else's: it is left as it
is, and the install says so. A failure to write it is a warning, since
reims-ctl is installed by then and works without it. The install's closing
lines name the file, and so does the README's install paragraph.

Nothing writes it at run time, and macOS and Windows get none.
2026-12-03 16:42:35 -08:00
Anees Iqbal 24409c75c1 🔥 Drop the VMs' capture input setting
The library's windows no longer capture: each grabs the keyboard whenever it
has the keyboard, with no click and no setting, and never holds the pointer
but for a game's lock. So a VM's [display] capture, its "Capture input"
toggle in the edit form, `reims-ctl set --capture` and the
REIMS_VGPU_WINDOW_CAPTURE=0 reims-ctl gave QEMU go with it. An arm64 VM's
form is its CPUs and memory again.

A VM an older reims-ctl saved with capture on or off loads with no error, and
the field is left out of its next save
(a_saved_capture_is_read_past_and_left_out). `set --capture` is now an
unknown option.

The README's section on the window says what it does now: the shortcuts go
to the guest while the window has the keyboard, Ctrl+Alt+Super gives the
host its shortcuts back until the next switch to the window, the mouse is
never held, and the keys the system keeps (Ctrl+Alt+Del and Win+L on
Windows; Cmd-Space, Cmd-Tab, Mission Control and the screenshot keys on a
Mac) never reach the guest.
2026-12-03 16:42:35 -08:00
Anees Iqbal 179821ecee ✅ Move a not-key pointer test to a whole-mapping point
the_tablet_s_events_are_unchanged_outside_a_game moved the pointer to 590
points, half way across a guest pixel boundary in exact arithmetic, and
expected pixel 980; 490/960 of 1920 floors to 979 in f64. The move now goes
to 640 points, which maps to pixel 1080 exactly.
2026-12-03 16:42:35 -08:00
Anees Iqbal 6daba044b1 🎨 Grab the keyboard whenever the window has it; drop capture
The planner ruled (B) for the window's input: one behaviour, no setting. On
Linux and Windows the window asks for the keyboard grab as it opens, so the
compositor's own shortcuts (Super alone, Super+V, Q, W, A, Tab, Alt+Tab,
Alt+F4) reach the guest whenever the window has the keyboard, titled,
borderless and full screen alike. Measured on KWin 6.8.3 with the grab, 12
chords of 12 reached the guest (m3-max-85442, 85443). There is no capturing
click, and the window never holds the pointer: it stays resizable, and one
click elsewhere leaves. The release chord (Ctrl+Alt+Super, Ctrl+Alt+Win)
gives the shell its shortcuts back until the window next gains the
keyboard, and the title names it while the grab or a game's lock holds.

What changes for the person at the host:
- The click that focuses the window is the guest's on every host.
- The pointer reaches the guest over the image alone, and outside it only in
  a drag, which ends in the guest.
- A game's lock begins while the window has the keyboard and the pointer is
  over the image, not after a capturing click. No guest-kernel signal tells
  a lock apart from a hide (m3-max-85480), so the 50 ms hide rule stays.
- SDL_ALLOW_ALT_TAB_WHILE_GRABBED is 0: SDL minimized a full screen window
  holding the grab at Alt+Tab (4 of 4 on KWin, 6 of 6 on Windows 11).
- On Windows SDL_WINDOWS_CLOSE_ON_ALT_F4 follows the grab of the window
  with the keyboard: Alt+F4 is the guest's under the grab, and closes the
  window after the release chord.
- On X11 another client's grab of the keyboard (FocusOut in NotifyGrab
  mode, which SDL passes over: KWin's Overview after Super+W) lifts every
  key held. Super+W through XWayland left the guest's command key down
  (m3-max-85443).
- macOS keeps what capture off gave: every key is the guest's, command
  shortcuts included, the system's own stay the host's, and the window holds
  neither the hot keys (SkyLight's undocumented call, hotkeys.rs, goes)
  nor the pointer, nor its size. The view takes the first mouse. The
  release chord ends a game's lock alone, and Window > Release Input goes,
  as nothing it released can be reached while a lock holds the pointer.
- The SDL window on macOS now applies its input's holds after each event,
  so a game's lock is let go as the window loses the keyboard.

REIMS_VGPU_WINDOW_CAPTURE and capture.rs are gone; grab.rs holds the grab,
the chord and the titles. features.md's Capture and Capture off sections
become "The keyboard and the pointer" and the Linux grab entry, the Window
menu loses Release Input, and every guard names the tests that hold the new
behaviour.
2026-12-03 16:42:35 -08:00
Anees Iqbal 59cc314742 🎨 Carry a drag onto the next display, not a captured pointer
The pointer's crossing onto another of the guest's displays (beyond.rs) started
for a captured pointer. Capture goes in the next commit, so the crossing now
starts in a drag: a button the guest was told is down, moving toward an edge
another display meets, within reach of it. A move with no button held stays
the window's, held at nothing.

The drag's last button up while it is away now ends the lock where the host's
pointer is, moving it nowhere (Hold::Free, Beyond::dropped), and the guest's
cursor stays where the drag left it. Before, the lock held until the pointer
came back over the window's display. Ending the hold without a warp leaves the
host's pointer free for whatever places it next, so a warp to the guest's
cursor on the other display's window is not undone.

Coming back over the window's display, out of reach of the edge, and letting
go (the release chord, the keyboard lost, the window's end) are as before.
2026-12-03 16:42:35 -08:00
Anees Iqbal 8f3ca9df99 ✅ Let the fake platform run named kernels on the CPU
The fake platform ran no shader, so a dispatch wrote nothing, and a test of a
GPU copy or fill could check its arguments but never its bytes. A test now
registers a stand-in for a function's name (World::stand_in). A fake compute
encoder then takes each dispatch it records of a pipeline made from that
function, with the buffers bound then and their offsets. The stand-in runs on
the CPU as the command buffer completes, before its events, waiters and
completed handlers. A command buffer that ends in an error runs none. Its
buffers are read and written through the fake's own memory, or through the fake
address space for a buffer over the caller's memory, so no unsafe is needed.

videoEncodeFill gets the first stand-in (fill.rs, cfg(test)). A copy from a
scratch on the fake now writes the kernel's bytes, and the last word of a
1366-wide row keeps the output's bytes past the row. The encoder's fill can use
the same stand-in. This is the fake leg's first step toward expressing the VA
arm's GPU copy (main 12-03).

All of it is in the testkit, which core builds only for tests and under the
testkit feature, and the fill's stand-in is cfg(test). The library's builds
hold none of it.

(cherry picked from commit 7ecbc10a9cfd50ee53f118a1f4dc69621639c024)
2026-12-03 16:15:59 -08:00
Anees Iqbal 3bb5f597aa 🎨 Format the walks test's timeouts check
As rustfmt lays it out (cargo fmt --check, m3-max-86015).

(cherry picked from commit e5169b96157c761341174ae3ea1dd98d77002e08)
2026-12-03 16:15:59 -08:00
Anees Iqbal 0c4b03013e ✅ Wait for a test's thread on the clock, not a sleep
A test that slept 20 ms for its waiter to reach a wait on the virtual clock
hung on the Windows mini (p89, m3-max-85598): the waiter began after the test
had begun a walk it must not count, and waited for that walk, which the test
ends only after the join. Where a late thread misses a check instead, the test
passed without testing anything.

The testkit's clock now counts the timed waits made on it and the timeouts an
advance delivers, and waits for a count (VirtualClock::timed_waits, timeouts,
wait_for_timed_waits); the testkit's settle counts its own waits
(World::settle_waits). The walks tests, the platform's settle test, the reset
tests that advance past a settle's wait or read the sessions, and the surface
order's CPU wait test wait for those counts instead of sleeping.

Test and testkit code only: the library is unchanged for the guest and the
host.

(cherry picked from commit d17b625050aa3b26a27372cde0b416c6baea5957)
2026-12-03 16:15:59 -08:00
Anees Iqbal 1216175216 ✅ Run the installer's tests in the bash PATH names
On Windows, Command::new("bash") looks in System32 before PATH, and where WSL
is installed it takes WSL's launcher, not MSYS2's bash, which the installer
runs in. GitHub's Windows runners have WSL with no distribution, and eight of
install.rs's tests failed there with the launcher's message. The tests now
start the first bash.exe on PATH, MSYS2's in its shell; elsewhere, bash as
before.
2026-12-03 15:48:28 -08:00
Anees Iqbal 837b29e48b ✅ Run the update test's copy of sleep as sleep
linux_names_a_replaced_running_binary_deleted copies /bin/sleep and runs the
copy. Where /bin/sleep is uutils' one binary of every utility, as on Ubuntu
26.04, it picks the utility by argv[0], and as `sleeper` it slept not at all:
on GitHub's ubuntu-26.04 runner the child was gone before the test read its
/proc entry. argv[0] is now `sleep`, which GNU's sleep ignores.
2026-12-03 15:48:28 -08:00
Anees Iqbal 344b120f6e 🐛 Find a running QEMU where readlink is uutils'
The installer's prune keeps a QEMU build while a process executes it, and
read the executables with one readlink over every /proc/PID/exe. uutils'
readlink, Ubuntu 26.04's coreutils, stops at the first operand it cannot
read, /proc/1/exe for a user, and printed nothing: on GitHub's ubuntu-26.04
runner the prune test saw the running build removed. One readlink a process
reads every executable whichever readlink the host has.
2026-12-03 15:48:28 -08:00
Anees Iqbal 7d016acc9c ⬆️ Build on metal2vulkan development 133c992dad
Pin V, from b531238180 (U): 117 commits, among them the bless commits
d2f8f386c0 and 292331c613 and the merge of the native mesh runtime.
SEMANTICS_VERSION 2367, RUNTIME_VERSION 2569.

What changes for the guest:
- A sampler state of Metal's undeclared filter 2 (cubic) is made and
  filters as nearest, as an x86 Mac's does. Before, it was nil, counted as
  rt-refused-gap (Gap::CubicSampler).
- A kernel whose partial threadgroup writes an imageblock slice every
  invocation shares now compiles: Metal's threads write the slice's cells,
  and a cell none of them stored holds zero. Before, rt refused it
  (SharedSliceWrite).
- A sequentially consistent fence or atomic operation is ordered through a
  fence word the device shares, so seq_cst fences are totally ordered.
- A blit copy between a buffer and a multisample texture's stencil or
  16-bit depth samples is carried out by the runtime's own draw and kernel.
- A 1D texture's bicubic sample compiles under the identity domains.
- On a device without unified memory, a Shared heap's texture is an image
  of its own in device memory, its range in the heap left unused. Before,
  rt refused it (Gap::HeapTexture).
- An argument buffer's texture read through a sampler takes its border
  texels from its resource ID's word.
- Mesh pipelines take the native task and mesh runtime, with bounded
  indirect grids.
- Anisotropy is the device's own filter (samplerAnisotropy is in rt's
  floor); the emulation is gone.
- Uploads the host waits for that use shared memory go as a part of their
  own, ahead of a held group.
- Refusals of imageblocks and of the partial-threadgroups variant name
  their cause, so a refusal's key may carry a cause name it did not.

What changes on our side:
- rt_platform::state's states_on_vulkan: a cubic filter is now a sampler
  state with no gap counted, and the module doc says so.
- diag's refusals_count_by_kind no longer names Gap::CubicSampler, which
  metal2vulkan is deleting.
- A pass attachment's slice past its texture's (Refusal::AttachmentPlace)
  is now counted as Metal's refusal (rt-refused-metal), not rt's own
  (rt-refused-ours): metal2vulkan's e730fbddbb gives it the basis of
  Metal's validation layer, measured on the M3 Max. The guest still gets
  nil. render's a_layered_pass_renders_each_slice_on_vulkan counts it so,
  and the accuracy ledger lists it among Metal's rules.

(cherry picked from commit 85812cc20208d035eb836c6efbde5935e44f420d)
(cherry picked from commit 9102cb63fe4aeace1377f8be7bf81ef68987c477)
2026-12-03 15:24:12 -08:00
Anees Iqbal 6ac79a2986 ✅ Give the Mac card leg's rig the luma offset field
The Mac card leg (video_harness::card_vt) was written beside a harness
whose Rig had no luma_at, which the arm64 GPU copy's work added in the same
batch, so its test build failed on the Mac. The leg lays each surface's
luma at its first byte, as the Linux card leg and the fake leg do.
2026-12-03 15:23:23 -08:00
Anees Iqbal 7789aed16e ✅ Play the video harness on a Mac host's VT arm
The harness's card leg ran only on Linux, over VA-API and NVDEC, and the Mac
host's arm (graphics::videotoolbox), which decodes in VideoToolbox's hardware
and copies each picture into the guest's lent surface on the GPU, had no run
of the harness's rules: no surface back before its write is done, nothing
written into a surface the guest has back, every picture the stream's.

card_vt is that leg on a Mac: the rt platform, the guest's RAM as anonymous
memory, VideoToolbox's arm, and x264's H.264 High stream of testsrc2 with
ffmpeg's MD5 of each frame's NV12 planes, since VideoToolbox decodes no VP9.
Both tests are #[ignore]d, run on a Mac holding its GPU: every picture lands
by a GPU copy and matches, and each delay point's seeded runs keep the rules.

The arm's GPU copy now waits at Point::WriteWait after its commit, so a
test's slow device holds the copy done longer; no other build has a delay.
The arm's wait has no deadline, so the stall tests of the Linux leg have no
case here. The stream, its format description and its host's decoder list
follow the stream's codec, and the RAM reader moves to the harness for both
card legs.

(cherry picked from commit 290eca335c255cb02adb82944d6349b804808375)
2026-12-03 15:14:13 -08:00
Anees Iqbal ec4486cdab 📝 Say the Iris copies 1366-wide pictures by the GPU [ci skip]
The Iris Xe card leg of the scratch row fix, m3-max-85799: every picture of the
suite's streams copied into a device cache and into a lent surface, and every
4:4:4 picture written by the XYUV route, equal to the CPU's, none declined,
the 1366-wide ones among them, which the scratches declined before
(m3-max-85609).

(cherry picked from commit d0baeb4b31785d24fd73dc5f0841dbc3cbf92e5b)
2026-12-03 15:14:09 -08:00
Anees Iqbal 398b60a494 🎨 Lay out the scratch row tests' asserts as rustfmt does
rustfmt wraps four asserts of 08aa25ded2's tests that run past its call width.

(cherry picked from commit 5d6ec9dacb1b7a3f6c2036589135e8930e585622)
2026-12-03 15:13:56 -08:00
Anees Iqbal edaaf452c6 🐎 Let the GPU's scratches take rows iHD writes out to 64 bytes
iHD's video processing writes a row of samples that is not whole 64 bytes out
to the next 64, the bytes past the samples zeroed, so zero copy declined any
such frame, whatever it wrote into. That is right for a guest's buffer or
cache, whose padding is the guest's to read, and wrong for the scratches the
graphics arm's GPU copies from, whose pitch (the even width's bytes rounded up
to 256) holds the row so written and whose padding no one reads. On the Iris
Xe the GPU copy of the commit before this declined a 1366-wide picture at its
scratch as the lent surface had, and its arm64 VideoToolbox pictures of that
width were still copied by the CPU: the claim of 062a9a3cb1 that such pictures
land by the GPU's copy holds from this commit on. The x86-64 path's scratch
(hand-over row 18), whose x86-64 guests' 1366-wide pictures the CPU copied on
iHD, gains the same, and so does the 4:4:4 route's scratch, which declined a
1366-wide 4:4:4 picture's rows of 5464 bytes.

A target now says its rows' padding is the host's and read by no one
(with_padding_unobserved on GuestTarget and PackedTarget, which only those
scratches say), and zero copy writes rows of other samples into it where each
plane's pitch holds them written out to the next alignment (rows_declined). A
guest's buffer and cache are declined such rows as before. The guest sees the
same bytes: the GPU copies and gathers the crop alone. The card tests of both
routes now fail on a scratch declined for its rows.

(cherry picked from commit 0ed277a0e086b37ec41fbaead83628ff87f57057)
2026-12-03 15:13:56 -08:00
Anees Iqbal 8dd6ae9f89 📝 Number the arm64 GPU copy's row D36 [ci skip]
Development's bugs.md now holds D33 and D34, the two kvz streams a Mac's
VideoToolbox fails, and D35 is the encode row landing beside this branch, so
the row for the arm64 GPU copy takes the next number. Hand-over rows 32 and 33
stay as they are: development's table ends at row 31, and rows 1, 3, 29 and
30, which they cite, read the same there.

(cherry picked from commit 12d5a9d94de107b5159c7b1c1d1a99857910328b)
2026-12-03 15:13:45 -08:00
Anees Iqbal b7ee1e5c23 🐎 Copy arm64 pictures the driver declines in place on the GPU
On Linux an arm64 guest's VideoToolbox picture lands in the surface the guest
lent by VA-API's video processing, in place, where the driver's import check
takes the surface's layout. Where the driver declined it, the picture was read
back and copied by the CPU, its reason logged once a decoder and no picture
counted. The guest's buffers are now asked of a layout radeonsi and iHD write
in place, and what is left is what the driver's own import declines: iHD's
rows of samples that are not whole 64 bytes, a 1366-wide picture's among them.

Such a 4:2:0 picture now lands as an x86-64 guest's picture lands in a device
cache the driver declined: the session's GPU copier (gpu_copy's
ScratchCopier) has the driver's video processing write it into a scratch of
its own, and the GPU copy its crop into the surface through a Shared buffer
of the device's over the surface's pages. The import's own refusal at run
time chooses the route, never a card or driver name, and the CPU's copy stays
last. The buffer over the surface is made at a picture's ask alone
(GuestOutput::buffer_on_ask, kept with the surface's view in vt.rs), so no
surface whose pictures land in place has one.

Each picture is counted: video-vt-pictures-gpu-copied, with its rows' KiB as
video-vt-gpu-copied-kib, and video-vt-pictures-cpu-copied for the CPU's copy,
which was logged and not counted before; each reason is logged once a
decoder. The three codes move from videotoolbox.rs to vt.rs, which the Mac
arm shares. The guest sees the same bytes: the copy writes the rows the CPU's
copy wrote, the crop alone.

Tests: lent_planes' rows, the kernel's rt test over a lent layout, the VA
host's copy into a lent surface against the CPU's copy (on the 780M, 297
pictures of 93 streams, each byte-equal, none declined), and the harness's
card leg over a surface whose luma lies 32 bytes in, which no driver writes in
place: each picture by the GPU's copy, none by the CPU. The fake leg has no
such test: the copy is the VA arm's own, from a dma-buf scratch the driver
writes, and the fake leg's arm is no VA arm, nor does the fake platform make
a dma-buf. The hand-overs table gains rows 32 and 33, and bugs.md D33 records
the copy a Mac does not make.

(cherry picked from commit ced49c6b257438adaaf3aacb16973eed228c1e23)
2026-12-03 15:13:29 -08:00
Anees Iqbal 96874e62f6 🎨 Name the coded size and shown rectangle pair in encoder tests
clippy's type_complexity refused the helper's return type.

(cherry picked from commit 1070baa647b41e9141c5ac5980b51d871a5ea361)
(cherry picked from commit 0a70c3f80cb994197cba286b34406157a7b35916)
2026-12-03 15:11:29 -08:00
Anees Iqbal 7b44b9f06f 🐛 Code VA-API pictures at the alignment the driver states
va.h's VASurfaceAttribAlignmentSize is "an add-on requirement to surface_width
and surface_height", and the encoder sized its surfaces and SPS by the codec's
block alone. radeonsi states 64x16 for HEVC; its UVD encoder (an RX 550) writes
its own SPS of the size rounded up to that, with the window ours carried, so a
guest's 1080p HEVC recording came out 1920x1088 and a 1366x768 one 1406x768.

The coded size is now a multiple of the codec's block and of the driver's
stated alignment, the wider in each dimension, on every VA-API driver; the SPS's
window or crop takes the rest off, and the surfaces and imported inputs are of
that size with their margin filled by repeating the last column and row, as
before. For the guest: on an RX 550, HEVC streams show the asked size. On a
Radeon 780M the stream's SPS is as before (VCN already rounded and added the
window); on an Iris Xe, whose iHD states no alignment, nothing changes. NVENC
is untouched. The planner granted the form (one query, no driver name read);
ffmpeg's hevc_vaapi does the same.

(cherry picked from commit 3eb666623a97f83435cb5c12a4f2ae172073825e)
(cherry picked from commit 4fa2bbcdddb3cc39376a86be3c11885073c255bd)
2026-12-03 15:11:29 -08:00
Anees Iqbal d1dc03fe3a ✅ Hold each VA-API driver's SPS to the asked rectangle
A card test: on each profile the driver encodes from uploads, at 1920x1080 and
1366x766, the SPS the driver wrote into the samples' configuration record must
show the asked rectangle to a decoder's parser. On an RX 550 it fails here:
radeonsi's UVD encoder writes its own SPS of the size rounded up to 64x16, the
alignment it states, with the window we gave it, so HEVC at 1920x1080 shows
1920x1088 (m3-max-85342, m3-max-85404) and at 1366x768 1406x768 (m3-max-85439).
The fix follows.

(cherry picked from commit 1f96dca0ee6e756bf888b0d72199034af57d7b77)
(cherry picked from commit dee4b7dc54d40e7e98ccdc455565e399ba6de2d3)
2026-12-03 15:11:29 -08:00
Anees Iqbal e41f74dcfd 📝 Describe the Mac host's encoders in the video docs [ci skip]
devices.md and backends.md say what the Mac host's encoders offer and how a
frame reaches them; hand-overs.md gains rows 34 and 35, the GPU and CPU
copies into VideoToolbox's pool buffer; bugs.md gains D35, the copy a Mac
does not make, and U38, the M3's HEVC encoder that hangs when allowed to
reorder. D30 now names why a shape the guest renders into is copied on the
M3: KosmicKrisp's image-format query offers no linear image with
colour-attachment usage, with host memory or without (m3-max-85644).

(cherry picked from commit e9736c78278293d2de7ce109bfb3ab32295bb593)
(cherry picked from commit 40b91aabfa1e97016f06bda7527a20cf6458b869)
2026-12-03 15:11:29 -08:00
Anees Iqbal f7a7d1ccb9 🆕 Encode an arm64 guest's frames on a Mac host's VideoToolbox
An arm64 guest on a Mac host now gets the host's hardware H.264 and HEVC
encoders: each codec whose profile VideoToolbox's hardware encoder offers
(the session's own supported-property dictionary is the query, with no chip
table) is listed to the guest's paravirtual encoder, and each guest session
is a VTCompressionSession that requires the hardware encoder, made with the
properties the guest set.

Each frame reaches VideoToolbox by one GPU copy from the Shared buffer over
the guest's lent pages into a pixel buffer of the session's pool, an
IOSurface, counted with its KiB; the CPU's copy is the fallback, counted
with its reason logged once. A pixel buffer over the guest's pages with no
IOSurface encodes, but costs more wall time and CPU than the copy (D35).
No frame is reordered, and MaxFrameDelayCount 0 is asked where a session
takes it: the M3 Max lists it and refuses every value (-12900).

The tests encode from a lent surface by each route and decode back, judging
values (38 dB or more, a mean within half a level), sizes and counts, with
the samples past the first byte for byte; the measurement test lists the
host's sizes, latencies and the planar route against the pool.

(cherry picked from commit b7a3a3cbbfbe129e52912c9a2199c35b92272334)
(cherry picked from commit 1f199afeceb01ecb55f53f19d4383401cdd3ce5c)
2026-12-03 15:11:29 -08:00
Anees Iqbal d9a47e584e 🆕 Convert a disk of another format to qcow2 at a create
A create given a disk QEMU reads as neither qcow2 nor raw (a VDI, VMDK, VHD
or VHDX among them) refused it, printing the qemu-img command that converts
it. It now runs that conversion itself: `qemu-img convert -f <format> -O
qcow2`, with the qemu-img beside the profile's QEMU, into the VM's directory,
and the VM runs on the copy. The original is only read, so a disk given to
use in place is converted all the same, and the create says so in one line:
the original stays as it is, and the VM runs on the copy.

As the other full copies do, it says the size first (qemu-img measure),
refuses before anything is made where the VM's file system has less room
free, says how far it is, and writes to a .part renamed over at the end.
Ctrl-C (the CLI takes it for such a create) and the interface quitting stop
qemu-img, and the create removes what it made. The DMG conversion shares
the progress loop.

A disk whose conversion would not be the same disk is refused with the
reason: encrypted, as reims-ctl takes no key; over a backing file, which the
conversion would flatten into it; or holding snapshots, which it would drop.
A start keeps its refusal with the convert line: converting there would
change which file the VM runs on without being asked.

(cherry picked from commit 17abf9a71a4e73f31bf314492fa175496181f4fd)
2026-12-03 15:08:54 -08:00
Anees Iqbal 4373e0ca5c 🐛 Move a lent surface's shape in place at its unlock's begin
e9db7ca883 held a shape's move in place after a guest's CPU write "until the
REFILL use shows its unlock, whose fill takes the newer bytes first", and made
the move at a later begin. That guarded a move while the guest might still hold
the read-write lock that moved the surface's generation, writing the pages: the
move takes the pages as holding every byte the cache holds, and a make that
copies the pages' bytes out and back loses a write made inside it.

A surface the guest lends each frame never reached that later begin. The kext's
lend takes a read-write lock and unlocks it, so every frame moved the
generation: the REFILL use's own begin checked its moves before that use
settled its generation, and by the next begin the next lend had moved it again.
In m3-max-85387 the 457 move checks of one block all found it unsettled (its
pages named, nothing dirty, no hold), and the block downloaded 458 times;
rt-shape-downloads-refused-no-pages counted 3686 over the boot.

Once the unlock is seen the hazard is gone. REFILL at generation N says the
guest saw the unlock of the lock that moved the surface to N, and the kext moves
the generation at each read-write lock as it is taken, so while the block's
header still holds N no lock has been taken since, and none is held. The pages
then hold the guest's last write, which the image in place reads, as the REFILL
fill would have copied it. So a begin settles each of its uses that carries
REFILL before its moves, and the shape moves at that begin.

A lock retaken since the unlock is the hazard that remains, so not being held
stays a gate: a begin moves nothing of a block whose header holds a generation
other than its use's, checked before the move's make. The hold fence still
checks the generation again inside a make that copies the pages out and back.

What the guest sees: no byte changes. A lent surface's shape lies in place over
its pages from its first use that shows a lend's unlock, and its downloads copy
nothing out of the cache.

Tests: the two tests that held the old rule now move at the unlock's begin
(a guest's write after the download; a shape an unsettled surface refused in
place), and a use at the new generation without REFILL still moves nothing; a
lock retaken since the unlock holds the move at its begin; a surface lent each
frame moves once and makes no straight download after; and the bytes a CPU
writes under a lend are what the moved image reads, and a GPU write after the
move is in the pages.

(cherry picked from commit 46da2cd35bef02323d7de89ede7d36821990da07)
(cherry picked from commit 6a21438c83b1e13c7ba8fa78fc5b38505c618f26)
2026-12-03 15:02:10 -08:00
Anees Iqbal 4e91a9490d 🐛 Let each video arm answer its output buffers' alignments
f52fb8e793 made every decoder session's Dpba and TDrs ask the guest's output
buffers for rows of 512 to 4096 bytes and planes on a page, the layout radeonsi
and iHD write a picture into in place. VideoToolbox's arm on a Mac host writes
no picture in place: its own GPU copy lands each one in the lent pages at any
pitch. There the drivers' rows only cost: with the 2048-byte rows of a 1080p
8-bit picture, rt refused 92 of the guest's textures over the lent pages in
place for their pitch and made 22 in place in a boot (m3-max-85387), where with
64-byte rows the same streams made 118 in place and none was refused for its
pitch (m3-max-85316).

The paravirtual decoder's Backend now answers the alignments its sessions ask
(output_alignment, tile_alignment), by default f52fb8e793's
(OutputAlignment::in_place_of_drivers, TILES_IN_PLACE_OF_DRIVERS). reims-vgpu's
VtBackend takes its arm's answer (GraphicsVideo::guest_output_alignment and
guest_tile_alignment): the VA-API and NVDEC arms keep the default, and the
VideoToolbox arm answers rows of 64 bytes and planes of 256
(OutputAlignment::PICTURES_OWN).

What the guest sees: on a Mac host, Dpba and TDrs ask rows of 64 and planes of
256 again; on Linux and Windows hosts nothing changes. Tests pin each answer: a
fake arm asking the pictures' own gets them in Dpba and TDrs, the default's
tests keep 512 and 4096, VtBackend passes on the default and an arm's own, and
the VideoToolbox arm answers 64 and 256 at every size and depth.

(cherry picked from commit adda4c343529c3c7682df844d23c75e740b1e47b)
(cherry picked from commit a1ee6ea804af04e3b4304706c902c30833e5f1e5)
2026-12-03 15:02:10 -08:00
Anees Iqbal 15e9659269 🐛 Start each whole-rows strip's chroma plane at a page
Where the driver writes rows of whole alignments (iHD), zero copy cuts a
large buffer into strips, each but the last a multiple of the rows after
which a luma row starts a page again. A strip's chroma starts half its luma
rows in, so at rows of 3840 a strip 16 luma rows in started its chroma 8
rows in, half a page; in its dma-buf the chroma then lay past the luma's
pages, not whole rows after the luma, and the frame was copied by the CPU.
The unit now also makes the chroma rows start a page: 32 rows at 3840.

(cherry picked from commit 47497be6a5ffaf5862b194658eb0af4c83015c65)
(cherry picked from commit 2c4bc663acd03dfe6c9f6269c70cb44af858426b)
(cherry picked from commit e4dc5d2b50201694ba22352075f540c8c5e60958)
2026-12-03 15:02:10 -08:00
Anees Iqbal fb4ebe6127 🐎 Ask arm64 guests for output buffers drivers write in place
What changes for the guest: a VideoToolbox decoder session's Dpba now asks
for planes on a page (PlaneAlignment 4096) and rows of the least of 512,
1024, 2048 and 4096 bytes that makes the luma plane's rows whole pages
(BytesPerRowAlignment), where it asked 64 and 256; a tile session's TDrs
asks for planes on a page and rows of 512, and its MaximumCanvasRowBytes is
rounded to 512.

With 64 and 256, the guest's CoreVideo put the luma plane 512 bytes into
the buffer's first page (measured in an arm64 macOS 26 guest, m3-max-84840).
iHD writes a luma plane only at its dma-buf's first byte, so on the Iris Xe
every picture of a hardware decode was copied by the CPU: all 240 of
H.264 1080p and HEVC 1080p and 4K at 8 and 10 bits, in 4 of 4 sessions.
radeonsi copied 1920-wide 8-bit pictures, whose rows are not a multiple of
256. With the new keys, the same guest lays the luma at the buffer's second
page and the chroma right after the luma's rows, whole pages, which both
drivers write in place.

Cost: rows over the 64-byte rows asked before. 3840x2160 at 8 bits takes
rows of 4096 for 3840, 6.7% more; nothing passes twice from 540 rows up;
small pictures whose height has few factors of 2 cost the most, the worst
240x135 at 8 bits, 16 times, 810 KiB a buffer for 50 KiB (the rule's doc
lists them).

(cherry picked from commit 5f23e17e1b198ec91624d023a231602bf2e07204)
(cherry picked from commit f52fb8e7938365dd653335235cdfa3ff7f638fca)
(cherry picked from commit 36af84f5d8754879ab58c3fefbddcc6c5ae7fe73)
2026-12-03 15:02:10 -08:00
Anees Iqbal 5cb932953e 🎨 Lay out the start's disk format check as rustfmt does
(cherry picked from commit 0366f5099553bdbf306868b9d221065cf30e768d)
2026-12-03 14:35:01 -08:00
Anees Iqbal 7104681aef 🐛 Refuse a disk QEMU reads as neither qcow2 nor raw
reims-ctl took any disk image without qcow2's magic for raw, and QEMU was
given it as format=raw: a VDI, VMDK, VHD or DMG reached the guest as the
image's own bytes, a disk with no partitions it knows. An installer told to
erase that empty disk overwrote the image, which, used in place, is the
user's original VM.

A create now asks qemu-img info for an existing disk's format, copied or used
in place, and refuses any but qcow2 and raw before anything is copied or
made, giving the qemu-img convert command. A start checks every VM's disk the
same way, since a VM made before this or edited by hand can hold such a disk.
QEMU's probe answers; where qemu-img is missing or can't open the image, the
disk goes on as its magic reads, as before. create --help names the two.

Whether a copied disk is another VM's (its copy is then a Mac of its own) now
goes through other_using, as the in-use guards do, and is asked before the
copy: it refuses where the list of VMs can't be read, or where a VM whose
settings don't read runs. A list that isn't there names none.

(cherry picked from commit 0ca7715179efaae6f2b306b141836dc75f96fe93)
2026-12-03 14:35:01 -08:00
Anees Iqbal a287e9a6d5 ✅ Pin that a disk behind a USB hub is on its own device
A disk's sysfs path passes every port above its USB device, a hub's among
them: 2-3 for a device at 2-3.4. disks_on matches the device's port as a
whole path component, so such a disk is on its device alone, and not on
another device on the same hub, as a match on the hub's port would make
it. The in-use test now holds a disk behind a hub and a device beside it.

(cherry picked from commit 4a33d88df9902be3282b1ea75d6b7fe2b9d79a37)
2026-12-03 14:35:01 -08:00
Anees Iqbal 14f7e7a922 🐛 Refuse a snapshot where the list of VMs can't be read
stopped() read the list of VMs and each running VM's settings with `if let Ok`, so
a take, restore or delete went ahead where the list, or a running VM's
settings, couldn't be read: over files another running VM may use in place.
It now asks runtime::other_using, as the in-use guards do, and refuses naming
the error. A test writes an unreadable list and checks that all three refuse,
with the snapshots as they were, and that a list that isn't there names none.
2026-12-03 14:27:35 -08:00
Anees Iqbal f68f1052d6 🐛 Give each snapshot save and journal write a temp file of its own
The snapshot code wrote a record, a rename, the settings a restore puts
back (the live vm.toml among them) and the restore's journal through fixed
temp names beside each file: <file>.toml.tmp and <journal>.tmp. Two
reims-ctl writing the same file at once wrote into one temp file, each
truncating the other, and the first rename could install a mix of the two.

write_whole now goes through record::replace, and write_journal takes its
temp name from record::beside, removes it where the write or the rename
fails, and still syncs the file and its directory. The tests' leftovers
check now includes what record::left_beside finds beside the VM's settings,
the journal and each snapshot's record, so every take, rename and restore
the tests run shows that none is left.

(cherry picked from commit e73a25dc1ca04ba38973fc0db4d0a94aa9dc0b53)
2026-12-03 14:24:59 -08:00
Anees Iqbal f1231263e6 🐛 Refuse a snapshot while the migrations record can't be read
A snapshot keeps the level of reims-ctl's migrations, and the restore of
one from before a migration records the VM in migrations.toml so that the
migrations run on it at its next start. With that record unreadable, a take
recorded level 0 and a restore recorded nothing, as the save over the record
is refused. Once the record could be read again, that VM never re-ran the
migrations its older snapshot lacked.

A take and a restore, the re-run of a cut-off one included, now read the
level before they change anything, and are refused while the record can't
be read: "<vm>: snapshots wait until reims-ctl can read the record of its
updates to its VMs", then the read error naming the file, as the update of
the VMs already waits. A restore records the deferral before it removes its
journal, so a failure there leaves it to finish when run again.

(cherry picked from commit ae2abb33b887ef9b8a27907744e6e959fe3d42b7)
2026-12-03 14:24:59 -08:00
Anees Iqbal 8727056a16 🎨 Read snapshot records through record::old_text
The snapshot module carried its own copy of the read rule the audit gave
reims-ctl's records: only a file that is not there is none, and one this
build can't read is refused, naming it. record::old_text is that rule, so
the list, a rename, a restore's settings and the restore journal now read
through it, and the copy goes. What each of them does is unchanged.

(cherry picked from commit 8905e0360b752b6f98f5d9e7317245448ba9464e)
2026-12-03 14:24:59 -08:00
Anees Iqbal dd5afdf2c9 🎨 Keep snapshot records as reims-ctl keeps its other records
Development now writes vm.toml, the registry and reims-ctl's other records
through record::text_over, which keeps what another build wrote and refuses a
file it can't keep. A snapshot's record and its copy of vm.toml are such
records, so their writes go through it too: a rename edits the name in place,
and a restore writes the copy's settings with the VM's name and installer now,
dropping the keys a save drops (vm::RETIRED). The edit of the snapshot's own
was its own form of the same; it goes.

Their reads follow the rule the audit gives the four saves: only a file that
is not there is none, and one this build can't read is refused, naming it.
A record that reads but not as a snapshot, as a newer build may write, still
leaves its snapshot out of the list, but tidy now goes by the snapshots'
directories rather than the records it could read, so it no longer deletes
such a snapshot's internal snapshot as stray.

The test of the interface's delete question now asserts that it names a
restore that was cut off.

(cherry picked from commit 1d996e78ce926969088f5973c6d5a1197a1a21e3)
2026-12-03 14:24:59 -08:00
Anees Iqbal 81527940d7 🆕 Finish a snapshot restore that was cut off part way
A restore that fails or is stopped puts the VM back as it was, but one cut off
by a power cut or a killed process left it part restored, with nothing saying
so: a disk taken back, some files swapped, the undo snapshot still inside the
image, and a later tidy free to delete that undo snapshot.

A restore now writes a journal, snapshots/.restoring, before it changes
anything, again as each step starts, synced to the disk each time, and removes
it as its last act. While it is there the VM does not start, from the CLI or
the interface, the update's migrations and OpenCore renewals wait, every other
snapshot command refuses with "a restore of NAME was cut off; run it again to
finish it", tidy keeps the undo snapshot, and deleting the VM's files asks
first, naming that restore. Run again, the restore finishes: from its start
where no disk's data had changed, else from the disks' going back on, each step
safe to run twice. The test cuts a restore after each step and its second run
once more, and checks the refusals and the end state.

A take, restore or delete cut off inside qemu-img can leave clusters in use
that no table refers to. Where the next take or delete finds what such a cut
left, or a cut-off restore finishes, qemu-img check -r leaks frees them, and
reims-ctl says how many.

(cherry picked from commit fdce3d197a86cdb10ece5a226a6b4138b3be29ba)
2026-12-03 14:24:59 -08:00
Anees Iqbal 58449885de 🆕 Snapshot a VM's disks, firmware variables and settings
The owner asked for a snapshot manager in reims-ctl, per VM. A snapshot keeps
what a stopped VM keeps between its runs, under a name, to go back to: each disk
of its own, its firmware's files (an x86-64 VM's OVMF variables and OpenCore
image, an arm64 VM's auxiliary storage) and its settings. It keeps no memory or
device state, so take and restore refuse a running VM and say to shut it down.

A qcow2 disk keeps it as an internal snapshot that the qemu-img reims-ctl runs
makes, at once on every file system. Its tag is a fixed id and its name lives
in the snapshot's record, as qemu-img renames no snapshot. A raw disk, every
arm64 VM's, is kept as a file of its own: a reflink or clone where the file
system makes one, else a full copy of its data alone. That copy is said first
with its size and why, refused with both numbers where the free space is short
of it, asked about once in the interface, shown as it goes, and a stop leaves no
part of it. The small files are copies beside. The list gives each snapshot's
space as what deleting it frees, and names the disks no snapshot keeps: one
used in place, and the host's disks.

A take or restore that fails or is stopped part way leaves the VM as it was,
which the tests check by failing the second of two disks. A record, and the
copy of vm.toml, keep what a newer reims-ctl wrote in them: a rename edits the
name in place, and a restore puts the copy's bytes back. Deleting a VM deletes
its snapshots, and an import that copies a qcow2 disk drops the snapshots
reims-ctl took of it for its VM, saying so.

The CLI's snapshot commands and the interface's snapshots view (S) both call
one module, src/snapshot.rs, and their help says what it does in plain words.

(cherry picked from commit c5fb0f0332db6d0ed7e2698055adc58ddb05e68e)
2026-12-03 14:24:47 -08:00
Anees Iqbal 6d8a9c48f3 🎨 Lay out the USB in-use check and its test as rustfmt does
rustfmt splits the disk lookup's chain and the test's three disk calls.

(cherry picked from commit 2e144e828d4eafdb0d8b487acffd9b19434e24ad)
2026-12-03 14:12:41 -08:00
Anees Iqbal 1a2aa5af3f 🐛 Refuse a USB device that holds a disk the host uses
QEMU's usb-host takes a passed-through device from the host's drivers as it
opens it (libusb_detach_kernel_driver). A USB stick the desktop mounted, and
the user copied files onto, lost its disk mid-use as it was given to a VM:
what the host had not written to it yet was lost, and its file system was
left unclean before macOS mounted it. disks.rs refuses this for whole disks;
USB passthrough asked nothing.

usb.rs now maps a USB device to the host's disks on it, each disk whose
sysfs device lies below the device's port, and refuses it while the host
uses one (mounted, swap, part of another device), in disks.rs's refusal's
form: as it is chosen (apply, which the TUI's toggle and reims-ctl usb
--add use) and at each start (runtime::preflight).

A chosen device plugged in while its VM runs is QEMU's to take, within 2 s
(usb_host_auto_check), whether or not the desktop has mounted it by then;
reims-ctl does not see that plug. docs/qemu.md says so, and to take a
device back from the VM before using it on the host.

(cherry picked from commit 2494c903b0706871c45ff4f36388cb4a8ad0b697)
2026-12-03 14:12:41 -08:00
Anees Iqbal 04b14bf847 ✅ Clone the qcow2 image the in-place case reuses
The FAT test's copy case moved the image's path, which the in-place case
copies from after it; it takes a clone.

(cherry picked from commit a0fb0bd14a25739fb74dea221b72ca6c03002ef8)
2026-12-03 14:12:41 -08:00
Anees Iqbal d13cdadb45 🐛 Refuse a qcow2 disk used in place on FAT that grows past 4 GiB
A create can use an existing disk in place (--disk-mode in-place, or the
form's "Using it in place"), and a VM's directory can be moved by hand. A
qcow2 image grows as the guest writes, so one on FAT whose guest's disk is
over 4 GiB fails its writes once it grows past what FAT holds in a file, and
QEMU gives the guest those failures. A raw image is as long as its guest's
disk already, so it never grows past.

create.rs's check_image_fits refuses such a qcow2 image, by its header's
guest size, where its own directory is on FAT: at a create that uses it in
place, and at each start (runtime::preflight), for any VM's disk. An image
whose header doesn't read is left to QEMU to refuse.

(cherry picked from commit 5dc1ea2118baff018d3eebf4dfbef11268e22aa6)
2026-12-03 14:12:36 -08:00
Anees Iqbal cf422511ee 🎨 Lay out the FAT tests as rustfmt does
rustfmt splits the exFAT row's list and the copy's expected message.

(cherry picked from commit 92301406f1e5345ce84f8cc58c0982da7f2a8463)
2026-12-03 14:12:36 -08:00
Anees Iqbal 4baf7ecbbc 🐛 Refuse a VM directory or a download FAT can't hold
A FAT file system holds no file of 4 GiB or more. On one, an x86-64 VM's new
qcow2 disk is made small and grows past 4 GiB part way through macOS's
install. QEMU stops a VM only where a write finds the disk full
(werror=enospc) and gives the guest any other write's failure, so the
installer fails with I/O errors and nothing names the file system. An arm64
create on FAT fails only after its IPSW's download, at the restore's sizing
of disk.img, and an IPSW or offline installer downloading into an
installers directory on FAT fails at 4 GiB.

A create now refuses before any download or write:
- a VM directory on FAT for a new disk past 4 GiB, or a copied disk that can
  grow past it (a qcow2 image to its guest's size);
- an IPSW, or an offline installer (13 to 20 GB, as the create form says),
  downloading into an installers directory on FAT.
A DMG's raw copy past 4 GiB is refused before qemu-img writes it, at create
and at set-installer. The message names the directory, its file system, the
cap, the file and its size, and what to do. FAT is the host's vfat, msdos or
fat on Linux, msdos on macOS, FAT or FAT32 on Windows. exFAT holds any file
and is never refused; a test pins it.

(cherry picked from commit 8ab7dd287163d9c9f35ca40f13722e7ab305b2f0)
2026-12-03 14:12:35 -08:00
Anees Iqbal 536dc64fee 🐛 Refuse a VM's in-use checks where the list of VMs can't be read
Three checks keep a VM's files from another VM that uses them: a start's,
against a second VM on an in-place disk ("Two VMs on one disk corrupt it"), an
OpenCore image change's, against replacing the image another running VM boots
from, and a download delete's, against deleting an installer a VM boots from.
Each read the list of VMs with `.ok()?` and skipped a VM whose settings don't
read, so where the list couldn't be read, or the other VM's vm.toml didn't,
the action went ahead. On macOS QEMU takes no lock on an image (locking=auto
locks only with OFD locks), so two VMs could then write one disk.

The three now ask runtime::other_using, which refuses where it can't tell, as
the claim guard does: an unreadable list is refused with its read error
named, and a list that isn't there names none. A VM whose settings don't read
holds a check back only while its pid file names a running QEMU, as
delete_vm reads it. A VM found is named as the list names it.

(cherry picked from commit d478820a695ebae5d0844a02371376e6a9197fe0)
2026-12-03 14:12:35 -08:00
Anees Iqbal 7c3bd2d299 🐛 Put the guest's cursor in a display's last pixel
vendor/qemu moves to 2f7c68a7, past a contributor's PR 24 and the two
commits that fix it forward. reims-graphics-pci now sends a window's
pointer at its display's last column or row as the tablet's maximum, on
every display and both axes, with no property: QEMU scales [0, size] over
the tablet, and the pixel itself, size - 1, put a macOS 26 guest's cursor
at 2014.92 of 2016 pixels and 1258.94 of 1260, never in the last column or
row; the maximum puts it at 2015.98 and 1259.98, still on its own display
with another beside it.

The PR's opt-in properties go: tablet-right-edge-head gave the maximum to
one display's x alone, and dock-pressure, with its second, motion-only
usb-mouse, showed no hidden Dock the tablet did not. An x86-64 26.7.2
guest's tablet shows a hidden Dock at the bottom, right and left on Linux
and Windows hosts, and an arm64 26 guest under TCG shows it at the right
and left and, with or without the pulses, not at the bottom. reims-ctl's
command does not change.

docs/qemu.md carries the fork's row and the measurements, with their
potluck jobs, and docs/lessons.md the trap.

(cherry picked from commit 634ce5f359c096e0c2456f28537b97a6ebb355a5)
2026-12-03 13:48:08 -08:00
Anees Iqbal 5013b22787 📝 Register the focusing click as the guest's, capture off [ci skip]
The register said, on every host, that the click bringing a window forward
is not the guest's, and that with capture off a click goes to the guest but
captures nothing. The commit before sends the focusing click to the guest
with capture off, on Linux, Windows and macOS, since with nothing to capture
no click needs spending on bringing the window forward.

The macOS entry for the focusing click, the Capture off entry and the SDL
window's Pointer entry say so, with the new tests as guards; the Capture off
walk adds a click from another window opening the guest's menu.

(cherry picked from commit 0156c77b8a513fa8cc0222036596f84bb2ffe0af)
2026-12-03 13:48:08 -08:00
Anees Iqbal 26cd9e35d2 🐛 Send the click that focuses a window to the guest with capture off
With capture off, a click into a window that did not have the keyboard only
brought it forward: on Linux and Windows the input dropped it as the click
that focuses the window, and on macOS the view did not take it. So after
switching back from another window, the first click meant for the guest
(opening a menu, pressing a button) did nothing, and the person had to click
again. That click is spent only so that bringing the window forward does not
capture, and with capture off nothing captures.

With capture off the focusing click now reaches the guest as any click does,
down and up, and still captures nothing, as pull request 219 proposed: the
input sends it on Linux and Windows, the AppKit view takes it
(acceptsFirstMouse: is YES with capture off), and SDL's window on macOS
gives it to the input. With capture on nothing changes. The capture-off
tests that held the old behaviour now expect the click sent, and each route
has a test of its own.

(cherry picked from commit 88863da177f4710d0be9827644bcdfe07600b17a)
2026-12-03 13:48:08 -08:00
Anees Iqbal e6ced3067b 📝 Say a Mac fails every kvz-720p-tiles-col64 picture [ci skip]
kvz-720p-tiles-col64's tile columns of 64 luma samples are under the 128 the
HEVC decoder takes (MIN_TILE_COLUMN_WIDTH), since radeonsi decodes such columns
wrongly with no error, and the stream is refused at its PPS. An M3 Max's
VideoToolbox hardware decoder decodes none of its 10 pictures (-12909 each;
m3-max-85421 and m3-max-85450). D34 records the refusal, why it is there, the
Mac's answer, and what would lift it.

(cherry picked from commit ce41732699e196b7e086d6c64870cea286fd1519)
2026-12-03 13:48:08 -08:00
Anees Iqbal 54f66c2925 📝 Say a Mac fails kvz-720p-ref15 where VA-API refuses it [ci skip]
kvz-720p-ref15's tenth picture names 9 current references: the VA accelerator
refuses it, and the guest's video driver never schedules one. An M3 Max's
VideoToolbox hardware decoder decodes the stream's first 9 pictures as ffmpeg's
software decoder does and none from the tenth on (-12909, then -17694 for the
pictures after it; m3-max-85421 and m3-max-85450). D33 records the refusal, why
it is there, and that a Mac's limit is the same 8, with what would lift it.

(cherry picked from commit 7d7e06b02797b0138bfb3cded98647099f4a40c7)
2026-12-03 13:48:08 -08:00
Anees Iqbal 890a306830 ✅ Leave out 4:4:4 pictures the XYUV route declines
The XYUV route's fault tests counted their first XYUV picture as one the GPU
writes. On the Iris Xe, iHD's video processing writes whole rows of 64 bytes
alone, so the route declines a 1366-wide 4:4:4 picture's rows of 5464 bytes, and
with the conformance streams' 1366-wide 4:4:4 stream both tests failed at their
first picture, at this commit's parent as at its child. Leave such a picture
out, uncounted, and arm a failure only where none waits for a pass, as the
gatherer counts them.

(cherry picked from commit 184276833921a920c8075855242e12a036fba7bd)
2026-12-03 13:48:08 -08:00
Anees Iqbal 196acc6641 ✅ Count torn reads and failed saves in one assert
The test asserted the failed saves first, so a red run never said how
many reads were torn. One assertion now says both counts, with the first
of each, and each thread saves 100 times, not 300, which a fixed temp
name still fails in every run (20 of 20 on Linux and on the Mac at 300).

(cherry picked from commit 95442318193112392ead3eecca7fa61ce3b9b9e6)
2026-12-03 13:48:08 -08:00
Anees Iqbal 4ca8945cfe 🎨 Write the other temp-then-rename files through record's helpers
Ambrosia's write, the aux storage's trim and the prebuilt set's ROM and
kexts each named their own temp file beside the place and renamed it
over, as record::replace now does for the records. They take its
helpers: the same writes, renames, removals on failure and errors, with
a temp name of each writer's own (.<name>.<pid>-<n>.tmp) for every one.

(cherry picked from commit bbf9b56d8b9534497243ef0ddbd2a765564479b5)
2026-12-03 13:48:08 -08:00
Anees Iqbal 4bc7c06948 🐛 Give each save of a record a temp file of its own
Vm::save, Registry::save and Install::save wrote the record's text into
a temp file of one fixed name beside it, then renamed that over it. Two
saves at once (two reims-ctl open) opened that one file with O_TRUNC,
each cutting what the other wrote, and the first rename put the file in
place while the second still wrote into it: the record could be left
torn, a list of VMs or a VM's settings that no longer parse, and the
second save failed at its rename.

record::replace now writes through a file of the writer's own beside the
record, .<name>.<pid>-<n>.tmp (n counting the names the process gave, as
two threads can share a clock's tick), and removes it where the write or
the rename fails. The last rename wins whole; the update the other save
made is still lost, which the two-writer row keeps.

(cherry picked from commit 4d1115cc7f2d13590b5742b17043bafed5a648d2)
2026-12-03 13:48:08 -08:00
Anees Iqbal c6897af3f6 📝 Say the draw test drew real frames by their deadlines [ci skip]
The hand-overs table said no run had drawn a real decoded frame by its frame's
deadline, the Windows host holding no streams. The draw test now has, over
the conformance streams on the UHD 630 (m3-max-85249): 4,971 pictures of 75
streams, each equal to vaGetImage's read back.

(cherry picked from commit 85c6457f9e79bf903d7c92c8b0cbb9a7754ea35d)
2026-12-03 13:32:27 -08:00
Anees Iqbal 20ed152eb2 📝 Say no real stream predicts a slice header's set from the SPS [ci skip]
The planner ordered the slice-header rewrite that would work around U38 only
on evidence. Over the suite's 57 streams hevc-craft did not write and the 5 the
arm64 guests' walks decode, no SPS carries a set, so no header can predict one.
Record the count, that our own encoder writes no such header, and the first
real stream that does as the trigger.

(cherry picked from commit b3ff826b39b6283fc789992db3cceb5faca0dac3)
2026-12-03 13:32:27 -08:00
Anees Iqbal 5361f9e2e8 🎨 Write the reservation counts' closure as rustfmt keeps it
(cherry picked from commit 71ca99c68b453913e4c006885d3ade89fce2c559)
2026-12-03 13:32:27 -08:00
Anees Iqbal 9a767d267b ✅ Compare only the codes a reservation can count
the_device_and_its_answers_on_vulkan held every degradation count
unchanged across reserve_resource_indices, but the gauges' look counts
on a thread of its own once a device is made: tD's AMD leg (85216) saw
rt-pipeline-cache-bytes-most land in between, and the test passed alone.

It now compares the codes the reservation can count, rt's refusals by
kind and its unbuilt pieces', and counts another code itself between
the reads, as that thread does.

(cherry picked from commit ea507d39df6cceffc92478eab209cb8815bea011)
2026-12-03 13:32:27 -08:00
Anees Iqbal 742e8e22a8 🎨 Write the claim guard's refusal and its test as rustfmt keeps them
(cherry picked from commit 2762b4ac25fa977d614e4915bcd9c0f5eafc171f)
2026-12-03 13:32:27 -08:00
Anees Iqbal f26b425fb8 🎨 Write the list of VMs' comparison as rustfmt keeps it
(cherry picked from commit 61d231951e5ababf0403134f0dd1ee4f53f3559b)
2026-12-03 13:32:27 -08:00
Anees Iqbal da508d54a6 🐛 Name the list of VMs' read error where it holds a leftover back
A directory whose leftover marker the list of VMs might name, where the
list can't be read, is refused; the refusal now says why, with the
read's error, and which VM the list names where it names one. A list
that doesn't exist, as on a host's first create, names no VM: the claim
test now holds that a true leftover is taken back then, and a new test
that an unreadable list refuses it, the disk as it was.

(cherry picked from commit 3f4f565e5a434394b2498cdee67664eb30c0e2c3)
2026-12-03 13:32:27 -08:00
Anees Iqbal 93fd5cbe5e 🐛 Never take a directory that holds a VM for a create's leftover
A claim emptied any directory holding a marker no create holds. A create
that finished but failed to remove its marker (finish ignored that
error), or a VM put in the directory afterwards, left such a directory
with a made VM in it, and a later create naming it would have deleted
the VM.

A directory that holds a vm.toml, or that the registry names (or whose
registry can't be read), is now refused as not empty, the refusal naming
the left marker. finish says so where it fails to remove its marker on
success, rather than ignoring it. The claim tests hold an Env, as a claim
now reads the registry.

(cherry picked from commit 978df3dff6f8b3067a164e9c4e07c64aa891573c)
2026-12-03 13:32:27 -08:00
Anees Iqbal dbd9b2e94f 🎨 Lay out the suite lists' reader and its users as rustfmt does
rustfmt's layout of the conformance crate's marks, its tests and the VA-API
arm's each_picture.

(cherry picked from commit e555f0a0abf2d93326dd2af9021e198914129d45)
2026-12-03 13:32:27 -08:00
Anees Iqbal 60e4e22af0 ✅ Hold the VA-API arm's stream tests to the suite's lists
reims-vgpu's VA-API tests that decode the conformance streams (each_picture,
under the arm's dma-buf, GPU copy and 4:4:4 tests) skipped every stream the
decoder refused, so a stream that decoded and starts being refused passed
them. They now hold each stream's decode to the lists the suite's scripts
write beside the streams, as the Direct3D 11 draw test does: a stream
refused.txt names must be refused as it says, after the pictures it says;
any other refusal fails the test, and so does a named stream that decodes
past its refusal. The range extensions' streams are left out where the
caller lands Main and Main 10 pictures alone; where it lands them too, one
is refused, naming its profile, only where the arm's own check finds the
driver decodes none of its pictures (declines_range_extensions), and must
decode where it finds it does.

The lists' reader and its rules are shared, in the conformance crate's
marks (Marks::read, Marks::judge), with unit tests of each rule; the draw
test now reads them through it too.

(cherry picked from commit 18a52cde60894af467349bf87f0959cc2cd6e6ba)
2026-12-03 13:32:27 -08:00
Anees Iqbal d54ebcf541 🎨 Lay out the draw test's list reading as rustfmt does
rustfmt's layout of two lines of the draw test's reading of refused.txt.

(cherry picked from commit 00a40e75832e867b159e3ffb10c79a236426a418)
2026-12-03 13:32:27 -08:00
Anees Iqbal 20757b0e35 ✅ Skip the streams the suite marks refused in the draw test
The Windows leg's run of the Direct3D 11 draw test over the conformance
streams (winleg p84) drew every picture of the first streams by the frame's
deadline, then failed at a stream h264-check.sh makes to be refused: its
interlaced streams, refused with Bitstream(Interlaced). The test expected
every stream to decode.

The suite's scripts now write, beside the streams, what they mark: each
script's refused.txt names the streams the decoder refuses on every host,
with the pictures each decodes first and what its refusal says (the
interlaced and fake-interlaced H.264 streams; kvazaar's 64-sample tile
columns, and its 15 references after 9 pictures), and hevc-check.sh's
range-extensions.txt names the range extensions' streams. The test reads
both from the streams' directories. A stream on refused.txt must be refused
as it says, after its pictures, which are drawn; it is then named and
counted. The range extensions' streams are left out, named and counted,
since the test's decoders land Main and Main 10 pictures alone. Any other
refusal still fails the test, a stream on the list that decodes whole fails
it, and a run with no picture drawn fails it. A leading picture the HEVC
decoder skips is no refusal, as in reims-vgpu's VA-API tests.

The streams that switch size or depth (switch-720p-1080p,
switch-main-main10) get new targets at the switch, where the test asserted
one size a stream.

(cherry picked from commit 9e99424b5489e3677402e7b13b4111203f864a63)
2026-12-03 13:32:27 -08:00
Anees Iqbal 6d5949736d 📝 Say radeonsi on UVD decodes headers' predicted sets wrong [ci skip]
On an RX 550, six of hevc-check.sh's crafted HEVC streams decode wrong from
their first inter picture, every call succeeding, through ffmpeg's own VA-API
decoder as through ours. They are the streams whose slice headers predict their
own short-term sets from the SPS's. Our parameters equal ffmpeg's in every
reference field, and Mesa gives UVD no bit count for a header's own set and no
NumDeltaPocsOfRefRpsIdx, which VA-API has no field for. Record it as an
upstream bug with its evidence, and that nothing within VA-API's fields is ours
to fix.

(cherry picked from commit 9addecdd4151d05f038e3317563de073000ab783)
2026-12-03 13:32:27 -08:00
Anees Iqbal 62df027393 📝 Say why B102's copy stays, from the SDK's headers [ci skip]
The planner asked whether the GPU copy of each decoded picture could go. No
documented call lets VideoToolbox decode into memory we choose: its pool is
read-only, a decode takes no destination, and an IOSurface names no memory.
So the copy stays, counted, and B102 says why.

(cherry picked from commit 162478693b1027973c6307550467cca1972861b6)
2026-12-03 13:32:27 -08:00
Anees Iqbal 84c97125d4 📝 Split B102's gap by the traced pass's phases [ci skip]
The traced boot m3-max-85280 timed each phase of a guest's 4K decode: the
host's decode equals its own one-at-a-time decode, the GPU copy into the
lent pages takes 0.8 to 0.9 ms, nearly all of it the wait after the commit,
and the Dbuf and Demt round trips 0.3 to 0.5 ms together. The probe's
0.06 to 0.19 ms was Metal's GPU span of the blit, not that wall time. The
fix is now the pipelined decode alone.

(cherry picked from commit b53104a956c216ca5c574975651b3f86a3ec3ce9)
2026-12-03 13:32:27 -08:00
Anees Iqbal 36e8eecdca 📝 Register the X11 grab that holds the captured pointer [ci skip]
The register's Capture entry said XFixes barriers keep the pointer's hold
on X11. Under a Wayland compositor they hold nothing: a mouse and a tablet
both went past them on um790. The entry now says SDL's mouse grab holds the
pointer in the whole window on X11, names the grab's test, and asks the
manual walk to push a mouse and an absolute device at each edge and corner.
lessons.md records the trap: a hold SDL keeps by one window system's means
need not hold where another window system stands in for it.

(cherry picked from commit 45bd3d0a3e684922c5c1873d1e74832f039a7a27)
2026-12-03 13:32:27 -08:00
Anees Iqbal 90e397c58b 🐛 Hold the captured pointer in the window on X11 with SDL's grab
On a Linux host where the window opens through SDL's X11 driver (XWayland
under a Wayland compositor), capture did not hold the pointer. A mouse moved
on past the window's edges to the screen's, and its top left corner opened
KWin's overview, which then took the keyboard, so the release chord no
longer reached the window. A tablet or other absolute device went anywhere.
SDL keeps an X11 window's mouse rect with XFixes pointer barriers, and
XWayland holds no pointer at them.

On X11 the window now also takes SDL's mouse grab while captured, an
XGrabPointer confined to the window, which XWayland turns into the
compositor's pointer confinement. Measured on um790 under KWin 6.8.3: with
such a grab a relative mouse and an absolute device both stay inside the
window. Wayland, Windows and macOS keep the rect alone, as before.

(cherry picked from commit 65872eb9ccebbf90ead5d66b4fa9287b06ba31b7)
2026-12-03 13:32:27 -08:00
Anees Iqbal ac1e3b1a44 🎨 Write the block pages' test helper as rustfmt keeps it
(cherry picked from commit 5b0b9d2f3735a75e3a33910836eb61cd065fba6b)
2026-12-03 13:32:27 -08:00
Anees Iqbal 5f28d89bd0 🐛 Refuse an NVDEC write past what its registration pinned
CUDA's registrations of guest memory are kept by the memory's identity,
made for the mapping of it first met. A later mapping of the identity
that is longer (a region block granted afresh at an offset whose life was
kept, as before the device's reset ended them) reached the kept
registration, and the write checked its planes against the memory's
length alone: the GPU's copy ran past the pinned pages.

write_into now checks each plane's end against the bytes the
registration pinned as well, and refuses the picture before any copy
(Unwritten::past_registration). The arm counts it as
video-pictures-past-registration, logs its first, and copies the
picture by the CPU, so the guest still gets it.

(cherry picked from commit a44d7a88c367178ab0043c5c6ec67f6344c2c2ab)
2026-12-03 13:32:27 -08:00
Anees Iqbal bda2822d6e 🐛 End the region blocks' video lives at the device's reset
A decode's plane in a block of the region takes the block's life, kept by
the block's offset, which the host's video devices key their imports by. It
ended at the block's BLOCK_RELEASE alone. The device's reset took the views
and the device caches, which own their lives, but kept these, so after a
guest's restart a block the new kext granted at the same offset, of another
size, took the old identity: NVIDIA's registration kept for it covered the
old block's pages alone, and a plane past them was copied beyond what CUDA
pinned.

The reset now ends every such life, as it ends the views' and the caches':
the devices drop what they made of the old blocks, and a block granted
after is a new mapping of its own size. A test makes a block's pages, resets
the decoder and grants a larger block at the offset. The lesson goes in
docs/lessons.md.

(cherry picked from commit c25d51831f3f54a6c6293423e794922a3d09e7a6)
2026-12-03 13:32:27 -08:00
Anees Iqbal 1e958f2ee9 📝 Say one-at-a-time decode is part of B102's gap, not all [ci skip]
The control run m3-max-85199 decoded the same clips on the host one frame
at a time, as the VideoToolbox arm does: that costs the host's own decode
36 to 50% of its rate, and the guest runs at 51 to 64% of it, so 1.7 to
2.2 ms a frame stay unattributed until a traced pass splits them.

(cherry picked from commit 6abf5bcaa82e8aeb185aa16ec9f59efb4747c274)
2026-12-03 13:32:27 -08:00
Anees Iqbal 210d5d2e09 📝 Log a Mac host guest's 4K decode at a third of the host's rate [ci skip]
The rate against native, measured once after the decode re-proof (3447):
the guest decodes 4K60 H.264 and HEVC at 31 to 35% of the host's own rate,
reading from code one access unit at a time where the host's own decode
keeps frames in flight. Logged as B102 until the planner rules on it.

(cherry picked from commit 267977432532211e5a6a04e2abf8af41928231c1)
2026-12-03 13:32:27 -08:00
Anees Iqbal 858191b148 📝 Say how many IOSurfaces a VideoToolbox session's pool lends [ci skip]
The re-proof boots counted one import made a decoder session, 13 for 13
sessions in each, and the rest of their pictures kept: the kept set of
eight holds the pool, and evicts nothing.

(cherry picked from commit d4ed7362ddf4384ac96bddc3be6852b609cef661)
2026-12-03 13:32:27 -08:00
Anees Iqbal 050643d2f5 ✅ Size the pair test's textures to the surface's rows
The surface the rig names has rows of 128 bytes, so an RGBA16Float or
RGBA32Float texture 32 texels wide does not fit it and is made over the
buffer, unshaped, and the test found no view of a shape for it. The pair
test makes each pair's textures as wide as the rows hold.

(cherry picked from commit 104bc95b0ddbbc345391dcfb3b61debf3d64c3a4)
2026-12-03 13:32:27 -08:00
Anees Iqbal f838aedec7 📝 Say why a promotion never copies between two formats [ci skip]
Metal's texture copy takes one pixel format on both sides, and a copy between
two formats of one texel's size is undefined across Macs: a UHD 630 completes
it and leaves the destination unwritten, an M3's validation stops it, and a
5300M copies the bytes. The promotion's doc and its choice of target say so.

(cherry picked from commit 2f82c478c05b05398492ee1cd18ba96e233240f8)
2026-12-03 13:32:27 -08:00
Anees Iqbal 8a66e5463a 🐛 Compare a promotion's view format as a u64 and keep formats in use
(cherry picked from commit f65798645a4912c40192c07a08cf2c9f78c8aebb)
2026-12-03 13:32:26 -08:00
Anees Iqbal 003338e1b4 🐛 Promote a plain shape across formats through a view
A promotion copies the plain image into the storage image where the storage
shape owes its fill and the plain one does not. The storage image is in the
format of the texture that made it, so the copy could be between two formats:
boot m3-max-85063 promoted an R8Unorm plain shape into an R8Uint storage one.
metal2vulkan-runtime refuses a copy between two textures of two formats
(Refusal::TextureCopyMismatch), so the promotion was refused, rule 1 kept both
shapes current, and every frame after copied between them (902 order copies,
1.4 GB). The copy only happens when the promotion meets a storage shape not
filled yet, which is timing, so earlier boots promoted with nothing copied.

The copy now goes into a view of the storage image in the plain image's
format, within one format (promotion_target): a storage image is of the Unknown
usage, which Metal views in any colour format of its texel's size, or its sRGB
sibling. A storage shape moved in place now also takes PixelFormatView for the
formats of the plain shape it would promote (ShapeTable::view_formats), so its
image takes the view and its promotion's retarget too. No pair of formats the
shapes table makes is left to a copy between two formats, or to a refusal for
its formats.

This changes which path the host takes, not what the guest observes: the
storage image takes the same bytes. The tests hold the pair of the boot, one
pair a texel size and an sRGB sibling through a whole promotion, every pair of
colour formats of one texel size against the choice, and the formats a moved
storage image is viewed in.

(cherry picked from commit fef686a5d68d662020961185b33c820dc1ffe798)
2026-12-03 13:32:26 -08:00
Anees Iqbal a34e93e4fa 🐛 Wait out a forked child's hold on the download locks too
The case 26e921bbd1 fixed for a create's marker holds for every lock
reims-ctl and reims-restore take as a running holder's: a download's
lock is held on by a child its process forked before the download let
go of it, until the child execs. A download started in that window said
another download of the file runs, and a delete of a part said it is
being downloaded now; the downloads test that lets go of a lock and
deletes at once failed the same way as the claim test.

The wait is now reims-restore's try_lock_let_go, up to LOCK_LET_GO (1 s),
which the create's marker, a download's lock and the delete's probe all
take. The installers directory's lock already waits for its holder.

(cherry picked from commit a46ccddd908f06aa11005c1cc5ccb9e1c58d47f8)
2026-12-03 12:47:42 -08:00
Anees Iqbal 6a69d8e5f0 🐛 Wait out a forked child's hold on an ended create's marker lock
flock's lock is the open file's, and a fork shares it: a child that
another thread forked before a claim ended holds the marker's lock on
until it execs. A create that checked the directory in that window took
the ended create's leftover for a running create's and refused it as
not empty. The test run's forking test, whose children wait 1 ms before
they exec, made the claim test fail on a busy Mac; a user meets it when
a create starts as another process's create ends.

The check now waits up to a second for a held lock before it refuses, so
a running create's directory is refused that much later.

(cherry picked from commit 26e921bbd1dcb4af79804bfac3c579dcb693804d)
2026-12-03 12:47:42 -08:00
Anees Iqbal 8d027e3db0 📝 List the surface order's waits among the long waits [ci skip]
core::long_waits's doc is the list of the waits the host's summary of each
ten seconds names, and the summary's doc sends its reader there. Three
names the surface order's begins time their waits under were not in it:
surface-order-begin (a begin's wait for unwalked buffers its SURFACE_ORDER
names to be committed), and surface-order-decode and surface-order-planes
(a begin held behind the decodes it comes after: their buffers' commits,
then their planes said written). Every other name in the list is one the
code times, and every name the code times is now in it.

(cherry picked from commit fba6ecd133d8c9324737e4d1e395440ae48a41ec)
2026-12-03 12:03:54 -08:00
Anees Iqbal 3fe72d5eeb 📝 Name the environment the library reads in api.md [ci skip]
The table of the variables the library reads named REIMS_VGPU_WINDOW_REFRESH,
which 3395fa9975 deleted with the window's apple-gfx mode list: no code reads
it, and the offered mode's rate is the screen's, which SCREENS picks. It left
out the three variables the Vulkan platform's device choice reads to pick the
host's GPU, MESA_VK_DEVICE_SELECT, DRI_PRIME and VK_LOADER_DEVICE_SELECT. And
its note on which variables the guest or host observes named STRICT and the
screen's alone: the GPU pick answers every query the guest makes, and the
capture switch decides which keys and pointer moves reach the window's key and
pointer callbacks.

(cherry picked from commit 4d80c12e1d708380ff876db1348854fc8c070be0)
2026-12-03 12:03:54 -08:00
Anees Iqbal d6c611faaa 🐛 Take back the directory an interrupted create left
A create marks the VM's directory as it takes it, and removes what it made
only where it returns. An x86-64 create ended by Ctrl-C, the interface's
quit or a kill, during its installer's conversion or a disk's copy, which
take minutes, left the marker and its files, gigabytes, in a directory no
VM is registered for. The next create of the VM was refused, "is not empty:
choose a new or empty directory", where the quit dialog said a create again
picks up its download; only deleting the directory by hand got past it.

The claim now holds a lock on the marker (flock on Unix, LockFileEx on
Windows) until the create ends, so a marker no create holds is an
interrupted create's. The next create says so, empties the directory, which
held nothing else, as a claim takes only a new or empty one, and takes it.
A marker a running create holds, and a directory with no marker, are
refused as before. A finished create removes the marker while it holds it.
Downloads are not in the directory but in the installers' one, so the next
create's download carries on from its part, as a test checks.

(cherry picked from commit 7d3aa72b134c4d576b40b9e124d76e2f2d3d4cdb)
2026-12-03 12:03:54 -08:00
Anees Iqbal b37f2a9c50 🎨 Write the install load's parse as rustfmt keeps it
rustfmt broke the parse's one-line chain in Install::load over three lines;
it is now two statements, which rustfmt leaves as they are.

(cherry picked from commit ac6f29341b0fb481219c71bb50530af14ee82057)
2026-12-03 12:03:54 -08:00
Anees Iqbal 4e02c575e2 🐛 Take no install record for none where this build can't read it
The install's load read the data directory's record with read_to_string,
falling back on any error to an earlier reims-ctl's record in the config
directory, and took a record it couldn't parse for none. So a record that
is there but can't be read (not UTF-8, a permission or an I/O error) gave an
earlier install's in its place, and one this build can't read as the record
gave none: `update` said there was no install, and so did the TUI and
doctor.

Only a file that is not there now moves on to the config directory's, or to
none. Any other read error, or one of the record's text, is an error naming
the file: `update` fails with it, the TUI says it, doctor's checkout line and
the logs report show it. Its test: a data directory's record that isn't
UTF-8, and one that isn't the record, each fail the load, naming the file,
with an earlier record in the config directory beside them, and are left
byte for byte.

(cherry picked from commit 508722ee05636c556a1b20071531c19e366fedf8)
2026-12-03 12:03:54 -08:00
Anees Iqbal 9bbf351704 🐛 Run no migration over a migrations record this build can't read
The migrations' load read migrations.toml with read_to_string(..).ok() and
toml::from_str(..).ok(), so a record that is there but can't be read (not
UTF-8, a permission or an I/O error) or can't be read as the record was
taken for none run: every migration ran again on every VM, at each run of
reims-ctl, since the record's save is now refused over that file.

Only a file that is not there now means none run. Any other read error, or
one of the record's text, is an error: the run says the update of the VMs
waits, naming the file, as it does where the registry can't be read, and
runs none; a VM's start runs no deferred migration. Its test: a record
that isn't UTF-8, and one whose `done` isn't a number, each run none, are
told, and are left byte for byte.

(cherry picked from commit e17d3a75fd5a97815bde9ca3d14327b0fb02cb74)
2026-12-03 12:03:54 -08:00
Anees Iqbal 6a8dcea463 🐛 Refuse a record's save over a file this build can't read
reims-ctl's four saves (vm.toml, the registry, the install's record and the
migrations') read the file as it is with read_to_string(..).ok(), so a file
that is there but can't be read, one that isn't UTF-8 or that a permission
or an I/O error keeps from reims-ctl, was taken for no file and written over
with this build's own text: what it held was dropped, which the saves edit
the file in place to keep.

record::old_text now reads it: only a file that is not there is no file, and
any other read error refuses the save (record::Refused, naming the file),
which leaves the file as it is. Each save reads through it, and each has a
test (record::assert_unreadable_refused): a file that isn't UTF-8, and on
Unix one its mode keeps from the user, is refused and left byte for byte.

(cherry picked from commit e52e13e51e67b42f23676d04747215303f433c71)
2026-12-03 12:03:54 -08:00
Anees Iqbal e7bc9850ba 🐛 Build the close's dialog module on Linux and within the lints
The Linux check found what the Windows tests could not see: zenity's
version reader returned a borrow from a closure, which does not compile, so
the window crate did not build on Linux at all. Its tests also timed with
Instant::now and started threads with std::thread::spawn, which the lints
refuse (Clock, and named threads), and the module's doc linked zenity's
function, which Windows' rustdoc cannot resolve.

The reader is a nested function now, the tests read the crate's clock and
start named threads, and the doc names zenity's function without a link.
Nothing changes for the guest or the host.

(cherry picked from commit d8e31afe66c608bc56992efe99d1f6afeb1c4dda)
2026-12-03 12:03:54 -08:00
Anees Iqbal ad33f61b27 📝 Register the close's dialog on a thread of its own [ci skip]
The Leaving entry said that while a dialog is up the UI thread waits for it,
and that Windows asks in a task dialog. Since the question's dialog moved to
a thread of its own (the commit before), zenity's question and Windows'
message box leave the UI thread running: another display's window takes its
input and the guest's cursor and modes reach the windows while either is up.
Only SDL's own X11 dialog, where zenity is missing or fails, still holds the
UI thread. On Windows the question is now the system's message box, its OK
named Turn Off, left of Cancel, and the display's end cancels it, as it
does zenity's.

The entry says so, names the new tests as its guards, and its manual walk
adds a second display's window on Windows while the question is up.

(cherry picked from commit d4a4f560e4e3d42bfc86f859c1088765ae76aece)
2026-12-03 12:03:54 -08:00
Anees Iqbal ef5ddb22ec 🐛 Ask a close's question in a dialog off the UI thread
On a Windows host every close asked its question in SDL's message box, and
on Linux a window that draws no more asked in zenity's through SDL. Either
ran on the library's UI thread and held it until the person answered: the
frames kept drawing, but the other windows' input and changes, and the work
posted to the UI thread (the guest's cursor, its modes), waited for the
answer.

The dialog now shows on a thread of its own, reims-vgpu.question, and its
answer is posted back to the UI thread, which runs on meanwhile:
- On Windows it is the system's message box, which the window owns: its OK
  named Turn Off as it activates (a CBT hook of that thread's own), left of
  Cancel, the default for Return and Escape, under the same words. Before,
  SDL showed its own dialog, as QEMU's process finds no TaskDialogIndirect
  (UI Automation listed its icon, text and buttons as child windows on the
  mini, 11-25).
- On Linux zenity runs as SDL ran it (SDL 3.4.18's arguments, its version
  read for the icon flag), as a child of the library's own.
Where that dialog does not show (no zenity, zenity failing, the message box
failing), SDL's message box on the UI thread asks as before: on Linux SDL's
own X11 dialog, which still holds the UI thread.

The display's end ends the dialog as Cancel: Windows' box gets its Cancel,
and zenity, now a known child, its SIGTERM by pid instead of a scan of
/proc for children named zenity. A dialog not shown yet ends as it shows.
features.md's guards follow the tests that moved: the zenity test is now in
the dialog module, and the /proc parser's is gone with it.

(cherry picked from commit 53edcf3d464e19f8a7d47bf852b6127a7c39691e)
2026-12-03 12:03:53 -08:00
Anees Iqbal 35cea45c0e 📝 Say how a kind drops its values, and the logger's cap [ci skip]
The rule said a kind is the cause's text up to its first digit, quote or
`;`, but not what that is for, that rt's error text can carry a value before
any of those, nor that the kinds the logger tells apart are capped. It now
says a number or an address makes no kind of its own, that where the code
holds rt's error the kind is its class (unbuilt::class and classed), and
that the logger tells apart the first 256 kinds (logging::KINDS_KEPT), the
lines of kinds past them written at debug and counted together.

(cherry picked from commit 68a51193973bf4207f37e2a4b5c3ee4f44b6a768)
2026-12-03 11:27:16 -08:00
Anees Iqbal ee2e050935 🐛 Name rt's error in a heap texture's raise by its class first
A heap texture's size and alignment that rt refused raises Metal's exception
with rt's error text in its detail, and the decoder logs the raise with its
text as its kind. That text can carry a pixel format before any digit, so one
cause made a WARN line per format. The raise's detail now says rt's error
with its class first (unbuilt::classed), so the kind of a line that names the
raise is its class; the detail still says the error.

Its test raises for two heap textures rt refuses that differ by a pixel
format: the logger's class of the two raises' texts is one, and the class.

(cherry picked from commit 497b00af40b6743f3e116f9df26dd70f952db741)
2026-12-03 11:27:16 -08:00
Anees Iqbal 5f8d683dfb 🐛 Name rt's window refusals by their class, without their values
A window image's acquire, clear or frame that rt refused was logged with rt's
error's debug as its kind, and its debug carries values before any digit,
such as a pixel format, so one cause could make a WARN line per value. The
kind is now the error's class (unbuilt::class); the line still says the
error. A frame whose command buffer ended in error with no error of rt's is
the kind "a status of Error". A drawable texture rt refused is said with its
class first in the swapchain's refusal, which the window's line takes as its
kind (unbuilt::classed).

No test drives these sites: each needs a window's swapchain. The class's own
test (an_rt_error_s_class_holds_none_of_its_values) holds what they name.

(cherry picked from commit 717f9a5f3111709d47c3a3d3f4ae150dac4c0c5e)
2026-12-03 11:27:16 -08:00
Anees Iqbal 84b284ad90 🐛 Name rt's Direct3D 11 surface refusals by their class, alone
A surface over Direct3D 11 textures that rt refused was logged with rt's
error text as its kind, and that text can carry a pixel format before any
digit, so one cause made a WARN line per format. The refusal is now said with
its class first (unbuilt::classed), which is its kind; the line still says
the error.

Its test refuses two surfaces for one class of rt's error that differ by a
pixel format: one WARN line, two counts. The module is Windows' alone: the
Mac's and Linux's checks clippy it, and its test runs on the Windows host.

(cherry picked from commit 90fd6bce92f22e25bed18c394026ce922cdc6249)
2026-12-03 11:27:16 -08:00
Anees Iqbal ee09afafd7 🐛 Name rt's export refusals by their class, without their values
An exportable buffer rt refused was logged with rt's error text as its kind,
and that text can carry a value before any digit, such as the handle asked
for, so one cause made a WARN line per value. The refusal is now said with
its class first (unbuilt::classed), which is its kind; the line still says
the error. So is rt's refusal of the block's ready wait in the export's error
text, which the host's video logs.

Its test refuses two buffers for one class of rt's error that differ by the
handle: one WARN line, two counts.

(cherry picked from commit 1608d2b6e35f6db57e073f4ff13f37b0ef46bf62)
2026-12-03 11:27:16 -08:00
Anees Iqbal fb0fc9b9c1 🐛 Name rt's surface refusals by their class, without their values
An exported surface rt refused was logged with rt's error text as its kind,
and that text can carry a pixel format before any digit, so one cause made
a WARN line per format. The refusal is now said with its class first
(unbuilt::classed), which is its kind; the line still says the error. So is
rt's refusal of a surface's ready wait in the export's error text, which the
host's video logs.

Its test refuses two surfaces for one class of rt's error that differ by a
pixel format: one WARN line, two counts.

(cherry picked from commit 74923cc1ea365c78d2aa900e5534a1dc56d0f30f)
2026-12-03 11:27:15 -08:00
Anees Iqbal 72398e2732 🆕 Give rt's errors a class without their values, for log kinds
A warn line's kind is its call site and the logger's class of its cause's
text: the text up to its first digit, quote or `;`. That class drops numbers
and addresses, but rt's error texts can carry a value before any digit: a
pixel format, a handle type, a texture type. "no texture of BGRA8Unorm" and
"no texture of Depth32Float" are then two kinds where they are one cause.

unbuilt::class names rt's error without its values: its name in the boot
diagnostics (diag::refusal_name), a failed Vulkan call's call and result, or
the error's variant. unbuilt::classed says the error as its class, then `; `
and the error as `said` gives it, so a line whose kind is that text has the
class alone as its kind and still says the values. The sites that name rt's
errors as kinds take it in the commits after this one.

(cherry picked from commit 3b28be492b82c3987dcf289775b9b1cd685a3d40)
2026-12-03 11:27:15 -08:00
Anees Iqbal 9c0629428a 🐛 End a walk's wait for its makes ahead as a reset begins
A command buffer's walk ends by waiting for its pre-pass's makes still
running on the compile threads, with the reset's gate held. A reset cut
short every other wait a walk sits in, but not this one, and the host's
settle gives walks begun before it 30 s, past which the process dies. So
a reset during an in-process make of 30 s or more ended the process, and
any shorter one held the reset for the make.

Decoders::resetting now wakes each walk's end waiting so (prepass::Closes),
and the wait ends where a reset is under way or came since it began, on
the decoder's reset count, as the commit order's waits do. The makes still
running go on on their threads, as a compile the reset does not wait for.

For the host: a reset no longer waits for a make ahead, and cannot die on
one. The new test, a_reset_ends_a_walk_s_end_s_wait_for_a_make_ahead,
holds a make ahead while the walk's end waits for it, and the reset returns
inside its bound.

(cherry picked from commit 9d0591baf2baa526e6a52318d48579dc6f48dadf)
2026-12-03 11:27:15 -08:00
charlysound 1913fcbc15 Merge pull request #220 from charlysound/contrib/native-mesh-bridge 2026-12-03 11:23:34 -08:00
charlysound 80ca2097e5 Merge pull request #219 from charlysound/contrib/uncaptured-first-click 2026-12-03 11:23:34 -08:00
charlysound 33c1853fca Merge pull request #218 from charlysound/contrib/hevc-visible-window 2026-12-03 11:23:34 -08:00
charlysound 04932a2392 Merge pull request #161 from charlysound/steelbrain/linux-seamless-pointer 2026-12-03 11:23:34 -08:00
Anees Iqbal 465a4aaa14 📝 Say no run drew a decoded frame by its deadline yet [ci skip]
The hand-over table's row 20 lists the Direct3D 11 draw's tests, which run on
the Windows host. The one test that draws a decoded frame by that frame's
deadline (Frame::deadline) decodes the conformance suite's streams named by
RVG_VA_STREAMS, and the Windows host held none of them, so that path has had no
run. The row now says so, until the Windows leg runs it with the streams.
2026-12-03 11:21:37 -08:00
Anees Iqbal a988f1b0d1 🐛 Carry a frame's one deadline through its Direct3D 11 draw
A Windows host's landing of a decoded picture into a video cache's planes
waited for the decode's sync by the frame's deadline, DEVICE_WAIT from its
first wait, and then gave the draw a fresh DEVICE_WAIT and STALL_HOLD from the
draw's own start. What the host saw: a landing could take 15 to 20 s, past
the 15 s from the frame's first wait that a failure's post's wait for its
work (HAND_OFF_WAIT) and a session's end (TEARDOWN_WAIT) assume, so either
could stop waiting on a landing still running.

The draws now take a due. Frame::deadline, the frame's one deadline, which
the decode's sync waits by, is the deadline of the draw and of a clear after
a draw that failed, with the draws' hold (DRAW_HOLD, STALL_HOLD) past it. A
clear at a commit, which lands no frame, takes DEVICE_WAIT from its start
(PlaneDraw::due_from_now). So a drawn landing ends within DRAWN_LANDING,
DEVICE_WAIT and DRAW_HOLD, of its frame's first wait, and a const assertion
beside HAND_OFF_WAIT's keeps that within HAND_OFF_WAIT and TEARDOWN_WAIT.

What the host sees now: a landing whose decode's sync took time and whose
draw then stalls ends the process 15 s from the frame's first wait, not 15 s
after the sync; a draw whose GPU finishes by then lands as before.

The held-signal test gives each draw and clear a frame whose first wait came
2 s before it. Before, the draw was unwaited 17.0 s after its frame's first
wait (mini job m3-max-84830); now at 15 s. Hand-over row 20 says the draw
waits by the frame's deadline, and loses the line that said a landing could
take 15 to 20 s.

(cherry picked from commit f918f22d26aeb950eba004ca75834b23c68183fa)
2026-12-03 11:02:36 -08:00
Anees Iqbal 61255060cb 🐛 Keep the window's title ASCII so X11 shows it whole
On a Linux host under X11, the window's title showed stray characters
where its dash was ("Reims vGPU — click to capture input" read
with garbage where its em dash was). SDL sets an X11 window's WM_NAME through
XmbTextListToTextProperty in the process's locale, which is C under
QEMU, and our title suffixes began with an em dash, which that locale
cannot carry. Where a locale has no such character at all, SDL sets
neither WM_NAME nor _NET_WM_NAME, and the title does not change.

The suffixes now begin with a plain hyphen on every host, so the title
is ASCII on Linux and Windows and reaches the window manager as it is.
macOS keeps its release chord's glyphs: AppKit, and SDL's window on
macOS, take the title as UTF-8. A test checks every title the window
sets, for each port form and capture state, and the window's features
register, README and the macOS walk quote the new title.

(cherry picked from commit 43f455743457174f64efd1e852cc038c683ee213)
2026-12-03 11:02:36 -08:00
Anees Iqbal 0e1c77523b 🐛 Keep a newer build's keys in reims-ctl's other records too
The registry (vms.toml), the install's record (install.toml) and the
migrations' record (migrations.toml) were still written by serializing this
build's struct over the file. An older reims-ctl's save dropped whatever a
newer one had added there, as vm.toml's did before 7308b42c6f: the registry's
at a create, a delete or a migration, the install's at an install of an older
channel, the migrations' at an older build's first run.

Each now writes through record::text_over, as vm.toml does: a key this build
doesn't know keeps its place and form, and only what changes is written. A
file this build can't keep the keys of is refused with record::Refused and
left as it is (953ebce592). Migrations already tell of a record they couldn't
write and run again next time, and the registry and the install's record pass
the error on to the command or the installer. The install's record is now
written beside its file and renamed over it, as the others are, so a write cut
short can no longer leave a truncated record behind for the refusal to stop
at.

(cherry picked from commit 078b06eb3a11ce386542a2bc183d63ca5f4c8a39)
2026-12-03 11:02:36 -08:00
Anees Iqbal 1a522bc0f5 🐛 Refuse a save over a record this build can't keep, not drop it
7308b42c6f fell back to the plain write wherever its in-place edit couldn't
run, and the plain write drops every key this build doesn't know: the bug it
fixed, by another door. Three inputs reached the fallback:
- a file that isn't TOML this build parses, such as one a newer toml writer
  formats in a way this parser rejects, or one edited by hand between a load
  and a save;
- TOML this build can't read as the record, such as a newer build's new
  graphics device or a key whose type it changed (vm.toml's load fails first,
  so only a file changed after the load gets here);
- an edit that wouldn't read back as the record. No record of ours reaches
  this: it takes a key this build reads under a second name (a serde alias on
  a field), which none has.

Each is now refused with record::Refused, a typed error that names the file,
says why, and says to update or restart reims-ctl or move the file aside. The
file stays as it is. With no file, the record's own text is still written.
The tests pin each case, the alias one with a record of their own, and that a
VM's save over a newer build's settings this build can't read leaves them
byte for byte.

(cherry picked from commit 953ebce592c2ba5ee010f33cd276e79e46650b47)
2026-12-03 11:02:36 -08:00
Anees Iqbal dc650323a0 🐛 Lock the memchr that winnow takes under toml_edit's features
7308b42c6f added toml_edit to reims-ctl's lock without the memchr dependency
that the winnow features toml_edit asks for add, so cargo install --locked, as
scripts/install-ctl.sh runs it, refused the lock. This is the entry cargo
writes for the tree.

(cherry picked from commit b4613721c0fe871353a34f6f49ccbd6e5d7c4940)
2026-12-03 11:02:36 -08:00
Anees Iqbal 4ed987953a 🐛 Keep what a newer build wrote in vm.toml when this one saves it
A VM's settings were saved by serializing this build's own struct over its
vm.toml. A reims-ctl older than the file's last writer, such as an interface
left open across an update or a build a channel switch installed, dropped
every setting it didn't know at its first save of the VM: an edit, a USB or
disk toggle, a start that found the GPU's driver moved, a migration. The newer
build then read its defaults for them.

Vm::save now edits the file as it is, with toml_edit (record.rs). A key this
build doesn't know keeps its place and its form, and so does a known key whose
value is unchanged. A changed value is written in the old one's place and
spacing, a cleared setting's key goes, and a new key is added at the end of its
table. [[usb]] and [[host_disk]] tables are matched by what this build reads of
them, so one left as it was keeps its other keys. The keys older builds wrote
and this one retired still go, as before: video_acceleration, display.hidpi,
display.refresh, q35.installer_kind and q35.osk. Where the file isn't TOML this
build reads, or the edit wouldn't read back as the settings being saved, the
save writes the settings' own text, as before. record::text_over takes any
record that serializes to TOML.

toml_edit 0.25.17 is the toml crate's own in-place editor, on the same
toml_datetime, toml_parser, toml_writer and winnow: the lock gains it, and
the next commit adds the memchr line winnow takes under its features.

(cherry picked from commit 7308b42c6fab0e7158c13f2ba952c1b3b58ac2d7)
2026-12-03 11:02:36 -08:00
Anees Iqbal 76e6c90369 📝 Say a Windows landing can take 15 to 20 s for now [ci skip]
The Direct3D 11 draws' wait into a video cache's planes is bounded at
DEVICE_WAIT and then STALL_HOLD from the draw's own start, after the decode's
sync, itself bounded at DEVICE_WAIT. So a Windows landing can take 15 to 20 s,
past the 15 s from the frame's first wait that TEARDOWN_WAIT and HAND_OFF_WAIT
assume. Row 20 says so until the fix that carries one deadline from the
frame's first wait through the sync and the draw lands.
2026-12-03 10:46:57 -08:00
Anees Iqbal 845641e32c 🐛 Hold a stalled Direct3D 11 draw for STALL_HOLD before its death
Since the draws' wait was bounded (#81), a Windows host ended the process at
a draw or a clear into a video cache's planes whose GPU work ran past
DEVICE_WAIT, 5 s, with its fence still answering. What the host saw: a stall
of 6 s, which used to land late, ended the VM. The unix arms hold a stalled
write for STALL_HOLD, 10 s more, before their death: 15 s from the wait's
start.

The draws now take a hold at their make (PlaneDraw::new), and reims-vgpu
gives them STALL_HOLD. Each wait, on the fence's event, by polling the fence
or by polling the event query, asks until DEVICE_WAIT and, where it has no
answer by then, up to the hold more, the first stall of each way logged. A
wait answered in the hold says so (Waited::held), counted as
video-drawn-waits-held. Past the hold the draw is Unwaited, and the process
ends with the same named fatal. A refused signal with a refused event query
still ends the process at once: no wait is left that could answer.

What the host sees now: a draw whose GPU finishes between 5 and 15 s lands,
counted; one not finished by 15 s ends the process with "reims-vgpu: fatal:
platform call the wait for the Direct3D 11 draws into a video cache's
planes: the fence's event did not answer the GPU done with the draws in
15.0 s".

The held-signal test now needs the draw to last the total (red: unwaited at
5.0 s, mini job m3-max-84765). A new test passes the held fence from the CPU
6 s into the draw, which lands held (red: Unwaited at 5.0 s). The refused
signal and query test asserts both end inside DEVICE_WAIT, and the
virtual-clock poll test covers an answer in the hold. The hand-over table's
row 20, docs/conventions.md and answer.rs's counts list follow; answer.rs
now lists the drawn waits' polled and queried codes too, which it lacked.

(cherry picked from commit bde4638ea0af75c8acad992ef31eed82d0974d81)
2026-12-03 10:44:43 -08:00
Anees Iqbal 13947a6410 📝 List the unlisted degradation codes in their register [ci skip]
docs/conventions.md is the register of the degradation codes, but some
counted codes were not in it: the pipeline finish's and the held stage
create's, the dispatch pre-pass's made-on-walk, the read-only pages'
writes, VideoToolbox's surface imports, the encodes' plane fills, the pages
blocks' overlaps, the pool's codes and the rt platform's stage codes. A
reader of a counts line had nowhere to look them up.

answer.rs's list of the kinds counted by code had earlier commits adding
codes to it, so it is meant to be complete; it lacked the codes above and
others already in the register (the surfaces' refusals, the display's
refusals, the slow answers', the pipeline creates' replies, the pictures
handed, the encode quality level, the VideoToolbox lends'). It now has
them, in the register's words, and says that the register is
conventions.md and that the list mirrors it.

(cherry picked from commit 3cbffc6b31ccd962be902d08efbb913df171a258)
2026-12-03 10:44:19 -08:00
Anees Iqbal ce4fdf6f98 🐛 Say each kind of refused copy of the host's own once
A copy of the host's own between a cache, its shapes, its wide home and its
pages that the platform refused a command of was counted and logged with its
code as the line's kind, the same for every copy: the logger said only the
process's first refused copy at warn, and every later one, whatever copy it
was (a fill, a write-back, an early copy, a copy out, a synchronize's), at
debug.

copy_refused now takes the block apart from the copy and makes the copy the
line's kind: the first of each kind of copy is said at warn, whatever block it
is of, the rest at debug and in the repeats line (docs/conventions.md). The
line's text is as before, but for a staged copy out's two lines, reworded so
that their rounds come after what each names, as the kind's class ends at its
first digit. The count is as before. A test plays two kinds of copy of two
blocks each and reads two lines.

(cherry picked from commit 5a30c8383e3320ec33611e26dd6deef3ebeb6656)
2026-12-03 10:44:19 -08:00
Anees Iqbal 83b7118f90 🐛 Say each kind of error a held VideoToolbox decode has once
A VideoToolbox decode that failed while the hardware's write into the guest's
surface ran past its deadline is answered only once the device is done. Its
line's kind was its code, the same for every error, so the logger said only
the process's first at warn and every later one, whatever its error, at debug.

The line takes the decode's error as its kind: the first of each kind is said
at warn, the rest at debug and in the repeats line (docs/conventions.md). The
count is as before. A unit test plays two errors twice each and reads two
lines. A test on the video harness's fake leg plays two sessions whose writes
stall and reads one line at warn and one at debug, with both counted: the
fake's stalls fail with one error alone, so the kinds apart are the unit
test's.

(cherry picked from commit 628710629e9215a64268bdea004e1f8f6b30d070)
2026-12-03 10:44:19 -08:00
Anees Iqbal 49dafd4dc1 🐛 Say each kind of staging end and held landing stall once
An x86-64 session whose second copy to or from a device cache had a failed
wait stops staging, and a picture that failed to land while the hardware's
work ran past its deadline is held until the device is done. Each line's kind
was its code, the same for every reason or error, so the logger said only the
process's first at warn and every later one, whatever its reason or error, at
debug.

The staging end, now in staging_ended, takes its reason as its kind, and the
held stall takes the picture's error: the first of each kind is said at warn,
the rest at debug and in the repeats line (docs/conventions.md). The counts are
as before. A test plays two reasons and two errors twice each, each stall's
work let go a moment into its hold, and reads two lines of each.

(cherry picked from commit e9bc3a083ce4edd59b4975b13854bb3aaafa1ab8)
2026-12-03 10:44:19 -08:00
Anees Iqbal 2a7a6b25dd 🐛 Say each kind of reason a VA-API XYUV route ends once
A VideoToolbox decoder on VA-API's XYUV route whose second 4:4:4 picture's
write may still run ends the route, its later 4:4:4 pictures split by the CPU.
Its line's kind was its code, the same for every reason, so the logger said
only the process's first decoder's reason at warn and every later decoder's,
whatever its reason, at debug.

The line, now in route_ended, takes the reason as its kind: the first of each
kind is said at warn, the rest at debug and in the repeats line
(docs/conventions.md). The count is as before. A test plays two reasons twice
each and reads two lines.

(cherry picked from commit 3f05bf264e6736a4729c6558f5d0ba269e46944c)
2026-12-03 10:44:19 -08:00
Anees Iqbal d499e0fe3f 🐛 Say each kind of reason NVDEC's 4:4:4 writes end once
A VideoToolbox decoder on NVDEC whose second 4:4:4 pass's wait failed ends its
GPU writes, its later 4:4:4 pictures copied by the CPU. Its line's kind was its
code, the same for every reason, so the logger said only the process's first
decoder's reason at warn and every later decoder's, whatever its reason, at
debug.

The line, now in gathers_ended, takes the reason as its kind: the first of each
kind is said at warn, the rest at debug and in the repeats line
(docs/conventions.md). The count is as before. A test plays two reasons twice
each and reads two lines.

(cherry picked from commit 1bcf6ec4343e79c45b1573f30b79474b12a56d0d)
2026-12-03 10:44:19 -08:00
Anees Iqbal d395c8b9b6 🐛 Say each kind of VideoToolbox CPU copy once, whatever decoder
On a Mac host, a VideoToolbox picture copied by the CPU kept a list of the
reasons each decoder had said, and wrote each new one with its code as its
kind. Every reason then had the same kind, so the logger said only the first
reason of the process at warn, and the rest of every decoder at debug, while
each decoder's list kept growing with the reasons it met.

The decoder keeps no list now: copied_by_cpu sends every copy to the logger
with the reason as its kind, so the first of each kind is said at warn,
whatever decoder copied it, and the rest at debug and in the repeats line
(docs/conventions.md). The count is as before. A test plays two reasons twice
each and reads two lines, and the tests that read a decoder's list read the
count of the CPU's copies instead.

(cherry picked from commit ec17bfa170862c5d06af8b4906205c890c57cfe7)
2026-12-03 10:44:19 -08:00
Anees Iqbal d0b87ba05e 🐛 Say each kind of reason a block's cache is copied once
A block named cached whose pages the host made no view of, or no buffer over,
takes its device cache with its pages copied by the CPU. Its line was written
only for the process's first such block: a static AtomicBool kept every later
one from the logger, so a second reason (no buffer, a run not mapped, no room
for the view, a raise) was never said, even at debug, and the logger's repeats
line never counted them. The line's kind was its code, the same for every
reason.

The line, now in pages_copied, goes to the logger every time with the reason
as its kind: the first of each kind is said at warn, the rest at debug and in
the repeats line (docs/conventions.md). The count is as before. A test plays
two reasons twice each and reads two lines.

(cherry picked from commit 51b0fcaf0ed6c6d02f774ed835a50602f921ca3a)
2026-12-03 10:44:19 -08:00
Anees Iqbal acd09cd4be 🐛 Say each kind of rt's Direct3D 11 surface refusal once
On Windows, a surface over Direct3D 11 textures that rt refused wrote its line
only for the process's first: a static AtomicBool kept every later one from the
logger, so a second kind of rt's error was never said, even at debug, and the
logger's repeats line never counted them. The line's kind was its code, the
same for every cause.

The line now goes to the logger every time with rt's error as its kind: the
first of each kind is said at warn, the rest at debug and in the repeats line
(docs/conventions.md). The count is as before. A test plays two errors twice
each and reads two lines; it runs on Windows hosts.

(cherry picked from commit 1559ad3754d597d9a586a4d9d33fedb43b562f94)
2026-12-03 10:44:19 -08:00
Anees Iqbal 652610ac11 🐛 Say each kind of rt's exportable buffer refusal once
A buffer rt refused to make exportable wrote its line only for the process's
first: a static AtomicBool kept every later one from the logger, so a second
kind of rt's error was never said, even at debug, and the logger's repeats line
never counted them. The line's kind was its code, the same for every cause.

The line now goes to the logger every time with rt's error as its kind: the
first of each kind is said at warn, the rest at debug and in the repeats line
(docs/conventions.md). The count is as before. A test plays two errors twice
each and reads two lines.

(cherry picked from commit b44aa2d44a4fdcb7ebb8728ce87dcd6b0172a495)
2026-12-03 10:44:19 -08:00
Anees Iqbal 1d03a49a3f 🐛 Say each kind of rt's surface refusal and copy form once
An exported surface rt refused, and one it made in the copy form, each wrote
its line only for the process's first: a static AtomicBool kept every later one
from the logger, so a second kind of rt's error, or a second copy reason, was
never said, even at debug, and the logger's repeats line never counted them.
The lines' kind was their code, the same for every cause.

Each line now goes to the logger every time with rt's error, or the copy's
reason, as its kind: the first of each kind is said at warn, the rest at debug
and in the repeats line (docs/conventions.md). The counts are as before. A test
plays two errors and two reasons, twice each, and reads two lines of each.

(cherry picked from commit 07171f6534b412f70c8a41daa7edcbafba028f63)
2026-12-03 10:44:19 -08:00
Anees Iqbal 64b0c720af 📝 Park B101 with the two boots that found no field for its limit [ci skip]
Two boots of a macOS 26.7.2 guest on an RTX 3090 host (2026-12-03) looked
for where AppleGVA's AMD path hands the driver a data rate limit. They found
nothing.
- With the limit and without, the H.264 streams and the frames' QPs were the
  same. No word of the per-frame records held the limit or the rate, and the
  encoder's two context parameters held no rate (m3-max-84444).
- Filling, in turn, each length-record word the driver leaves at 0 with the
  frame's bits changed no stream. That spends the lead the row named
  (m3-max-84639).
The row keeps its measurements and waits for a user report of a data rate
limit not held.

(cherry picked from commit ac74252372a53f15692d82009ae8e28929b75116)
2026-12-03 10:44:16 -08:00
Anees Iqbal bbde1b21b9 📝 Stop saying AMD's driver answers an unknown context parameter
GetContextParameter's comment said that a parameter the driver does not know
is left as it came, with success, "as AMD's driver answers it". Nothing
measured AMD's answer. The comment now says what the code does, says that
AMD's answer is not measured, and says that no guest was seen asking: in an
x86-64 macOS 26.7.2 guest on an RTX 3090 host (m3-max-84639, 2026-12-03), 63
H.264 encode sessions and the decodes of their streams asked no
GetContextParameter at all. The test's comment drops the same claim.

The sets' records take the source's new hash; no built byte is meant to
change.

(cherry picked from commit c729ed99d792a547d22f208f7c4e2f13d4a89ebf)
2026-12-03 10:44:16 -08:00
Anees Iqbal ba4810e81e 🐛 Refuse what pairs a stale reims-ctl's drivers with a newer QEMU
An interface left open while reims-ctl was updated from another terminal
(reims-ctl update, scripts/install-ctl.sh or scripts\install.ps1) carries the
guest's kexts and the device's option ROM of its own build, while the QEMU
and library it runs are the install's. Since 467a108fe0 its start was
refused, but only after the start's preparation had made the VM's OpenCore
image again with its own build's kexts. U (a new OpenCore image), the edit
form's change of graphics or boot selection, a create, and the QEMU command
c shows and writes as launch.sh still used them without a word: the command
paired this build's option ROM with the newer QEMU, and the images held
drivers that don't match it.

Each of them is now refused with the start's line before anything is
written: a start's preparation leaves the VM as it is, a create refuses
before its download, the edit form before its settings are saved, and every
OpenCore image made with the kexts, and every printed command, is refused
where it is made. In the interface, s, n, c and U offer to restart reims-ctl
instead: Restart, the default, runs the installed reims-ctl in this one's
place, as an update from the interface does. The interface's help and
reims-ctl update --help say so. The line now says the drivers don't match
the installed QEMU rather than calling them older, since a channel switch
can install an older build.

(cherry picked from commit fb707dae031cc94828f2f9850bced7da27ad9275)
2026-12-03 10:44:16 -08:00
Anees Iqbal f5d3f08144 📦 Build the guest's kext sets again with the location refusal
Both sets, guest/prebuilt and guest/prebuilt-arm64e, rebuilt on the M3 from
6dd45d4e28 (m3-max-84683: make -C guest prebuilt, prebuilt-arm64e, then
prebuilt-check, which passed), so that RgfxGate's Metal bundle refuses a
function whose values leave an argument's location undecided, as Metal does.
Only RgfxGate's binary and the sets' records change.

(cherry picked from commit 793600cc939cbbfd354205137a96044cebaaae26)
2026-12-03 10:27:43 -08:00
Anees Iqbal 431df0e39c 📝 Note the known use difference at reflection's answer [ci skip]
The one statement of the known difference in an argument's use was a test's
doc (shell_tests.mm, the predicated arguments' test). Where the values give no
value of a constant the function requires, undefined in Metal, Metal can answer
an argument unused that the AIR reader answers used: v_pred made with kB alone,
its positions, on the oracle (macbook-pro-2019, macOS 26.7.1, the AMD Radeon
Pro 5300M). The comment now sits at the code that answers isUsed and isActive,
naming the case as closed and not emulated: no guest-visible failure traces to
it.

(cherry picked from commit 6dd45d4e28f164405f238049348f119ab8456b09)
2026-12-03 10:27:43 -08:00
Anees Iqbal 4204342f69 📝 Mark uses under unset required constants as ours [ci skip]
Where a function's values give no value of a constant it requires, which
MTLFunctionConstant's `required` makes undefined in Metal, the reflection's
isUsed and isActive are the AIR reader's, and can differ from Metal's: the
oracle (macbook-pro-2019, macOS 26.7.1, the AMD Radeon Pro 5300M) answered
v_pred, made with kB alone, positions unused and tint used. No guest-visible
failure traces to these flags, so they are not emulated (the contract leaves
undefined Metal behaviour out). The documented cases match Metal: every
required constant given, an optional one without a value among them (v_dflt's
kA, required 0).

(cherry picked from commit 860fffe624f3d45ed203649a43454ced8ebe43e0)
2026-12-03 10:27:32 -08:00
Anees Iqbal 788597e094 🐛 Refuse a function whose values leave an argument's location open
A function made with values that lack a constant an argument's binding index
reads (`[[buffer(kIdx)]]`, kIdx given no value) was made, the bundle taking the
missing required constant as 0: the argument sat at index 0, beside the
kernel's buffer 0 or alone, where Metal refuses the function.

What Metal answers, measured by an oracle probe of our own on macbook-pro-2019,
macOS 26.7.1 (25G241), the AMD Radeon Pro 5300M (m3-max-84515/84516), and on
the M3 Max, macOS 27.0.1 (m3-max-84627), the same 110 answers: nil and
MTLLibraryErrorDomain code 3, its description alone, a line for each such
argument in argument order, "error: texture argument ts has invalid location
(<_ZL32__metal_implicit_attr_int_expr_2,2>) in k_texarr\n", the global the
module stores the index in by name and the count. Buffers, threadgroup memory,
textures, arrays of textures and samplers alike, kernels, vertex and fragment
functions alike, used or not. Such an argument takes no location, so a later
one at the same index is no overlap; overlap lines keep their form, in the
same order. An argument whose predicate the values leave undecided is left out,
and an index of a default (`is_function_constant_defined(k) ? k : 3`) is made.

What the guest sees now: newFunctionWithName:constantValues:error:, and every
way that reaches it (descriptors, completion handlers), answers nil with
Metal's error and words for such values, and never takes 0 for the missing
index. The refusal of overlapping locations, RgfxOverlappingArgumentError, is
now RgfxInvalidLocationError: it runs the module's initialisers with the values
given, and, where a global they do not decide is read, again with a 0 for each
declared constant the values lack; a global only that run decides is one the
values leave undecided. The AIR reader keeps the names of an argument's index
and count globals. Functions given every constant answer as before.

test_undecided_locations_refused_as_metal holds the oracle's words for
tests/undecided_locations.metal (the probe's source), first two arguments at
one undecided index, and compares every function under each of the probe's
takings, by values set by name, by index and in a descriptor, with this Mac's
own Metal.

(cherry picked from commit cbae8ac8df3ba63894826c2ef1d631f00881acf9)
2026-12-03 10:27:32 -08:00
Anees Iqbal b6bc00b047 ✅ Pin that every video session answers a shared event
wait_for_hand_offs waits on the CPU, on the session's event, for the work a
failed walk handed a video session; a plain event it cannot wait on, and it
lets the failure go with a warning. No session the host makes answers one:
VA-API's and NVDEC's decode sessions are video_host's HostVideoSession, and
VA-API's and NVENC's encode sessions its HostEncodeSession (Windows' VA-API
arm the same), both holding a shared event and answering EventRef::Shared.
On a Mac, VideoToolbox makes no such session, and the arm64 guests'
paravirtual sessions are another device's.

These tests pin each type's answer, and the plain-event arm says that only a
test fake reaches it. Nothing changes for the guest.

(cherry picked from commit 99fd81e18f46f14673ca34848557158892a5d8fc)
2026-12-03 10:27:32 -08:00
Anees Iqbal cde66860cc 🎨 Name the H.264 rate record's words at +0x24 and +0x28 by offset
The video driver read the words at +0x24 and +0x28 of AppleGVA's H.264
rate control record (P+0x328) as the frame rate's numerator and denominator,
and named them so (kRateFrameRate), but nothing states that meaning: the
commit that named it says the record's other fields are not read yet, and
the driver's check writes the words itself. Under the record's mode 0 both
read 0 in every frame of a 1080p session at 30 frames a second, with a data
rate limit and without (a scratch boot, macOS 26.7.2 guest on an RTX 3090
host, 2026-12-03), so the host has had no frame rate from them.

They are now kRateField24 and kRateField28, with that measurement in their
doc; the driver forwards them as before. Both guest sets were rebuilt from
the sources: no binary byte changed, only sources.toml's hash of
RgfxVideoDriver.cpp. Nothing changes for the guest or the host.

(cherry picked from commit b5440d073bb4109fa6b2be4a84cd2920bbc3dd63)
2026-12-03 10:27:32 -08:00
Anees Iqbal cf46e14d3a 📝 List the Direct3D 11 draws' wait codes in answer.rs [ci skip]
The draws' bounded wait counts video-drawn-waits-polled and
video-drawn-waits-queried, and docs/conventions.md lists both, but the list of
counted codes in answer.rs's doc had neither. It now names both, with what each
counts: a draw or a clear whose wait polled the fence's value, the wait on its
event failed, and one that waited on an event query, its signal of the fence
refused.

(cherry picked from commit a3a9e335c66046c4f7baa80c43a48ced78fa628d)
2026-12-03 10:27:32 -08:00
Anees Iqbal a567bb348d ✅ Play both reasons an unmade function handle names
The once-a-kind test of a function handle the platform makes none of played
one reason only, a function its library makes none of, so it passed with the
line's kind taken out (red job m3-max-84654): one reason makes one WARN line
with a kind or without. The line names two reasons: that one, and a library
whose make was refused while the create waited for it.

The test now plays both, two creates of each, and asserts four counted and one
WARN line of each reason; with the kind taken out the second reason goes to
debug and the test fails. A create meets the second reason only when it takes
the library as being made before its make is refused, so a test-only helper,
LibraryJob::refuse_in_place, gives the library's slot the refusal and leaves it
being made.

(cherry picked from commit 4fc3eac50b6563e85a2709821070c0157c7522ab)
2026-12-03 10:27:32 -08:00
Anees Iqbal 102c307eee 📝 Re-quote the Direct3D 11 draws' row for their bound [ci skip]
Row 20 of the hand-over table, a Windows host's draw of VA-API's picture into
a cache's planes over Direct3D 11 textures, still said the wait on the draws'
fence had no bound of its own, and that a failed wait or a refused signal had
none, leaving the CPU's copy to land the picture while the draws might still
write the textures. The three commits before the table's in this batch closed
that path: the wait is bounded at DEVICE_WAIT, a failed call of it polls the
fence (video-drawn-waits-polled), a refused signal flushes the draws and polls
an event query (video-drawn-waits-queried), and past the bound the process
ends at the draw with a named death.

The row now says so, quotes the d3d11 module doc's bound and query sentences
and graphics::drawn's death, and names the tests those commits added. Its
first quote is unchanged and still in the file.
2026-12-03 10:09:01 -08:00
Anees Iqbal 99efe8e647 📝 Add the hand-over of a cache's picture into its pages [ci skip]
A device cache's picture reaches the guest's CPU through the host's copy into
the surface's pages, at a CPU lock's SURFACE_DOWNLOAD, a release, a
SURFACE_PAGES that names the pages again, and a guest's synchronize. The table
had no row for it. Row 31 names the copy's command buffer as its one wait, with
B1's rule that a copy whose command buffer ended in an error lands nothing more
and is answered failed, and B1's four tests that hold it.

(cherry picked from commit 6fb8578fcd1ac41b12e5bb1e9a26dae59e6dd233)
2026-12-03 10:03:29 -08:00
Anees Iqbal 93021ddec3 📝 List the log class's new codes and three unlisted ones [ci skip]
Every code counted in a boot's degradation counts is listed in
docs/conventions.md and in answer.rs's degradation_counts doc. The log class's
fixes count thirteen new codes (vt-decode-failed, vt-encode-failed,
vt-encoder-open-failed, uploads-written-dropped, managed-texture-two-copies,
refused-object-named, dynamic-library-create-failed, vt-message-refused,
function-handle-unmade, vt-message-unread, vt-encoder-property-refused,
video-cache-acquire-refused, video-nvenc-copy-refused), and three codes counted
before were listed in neither place: vt-decode-stall-held,
video-landing-stall-held and video-landing-failure-untold.

(cherry picked from commit 63182562aebe6352f0711a54bce7ea2e7c156ff6)
2026-12-03 10:03:29 -08:00
Anees Iqbal 0f0d8290b9 🐛 Count each NVENC input copy the platform refuses, by kind
A frame whose GPU copy into NVENC's input the platform refused was logged the
first time in each encode session, with no kind, and counted only in that
session's info line at its end: a second reason was unseen, and none showed in
a boot's degradation counts.

Each refusal now reaches the logger with its reason as its kind, so each kind
is said once a boot at WARN and the rest at debug, and each frame is counted
as video-nvenc-copy-refused (docs/conventions.md, "Each degradation is logged
once per boot, then counted"). The frame's CPU upload is unchanged.

(cherry picked from commit 31a15d3582d3c819e7c61a078381ee4aa41f50b6)
2026-12-03 10:03:29 -08:00
Anees Iqbal 0a7647a03e 🐛 Count each refused cache acquire of a failed picture, by kind
A picture that failed to land whose device cache's acquire the platform then
refused was logged with no kind and never counted: a second reason was said
only at debug, and none showed in a boot's degradation counts.

Its line now names the refusal as its kind, so each kind is said once a boot
at WARN and the rest at debug, and each plane is counted as
video-cache-acquire-refused (docs/conventions.md, "Each degradation is logged
once per boot, then counted"). The landing's failure is unchanged.

(cherry picked from commit b638f9c07488f9966d43f5371bea1d2daf1414bb)
2026-12-03 10:03:29 -08:00
Anees Iqbal f4504493d3 🐛 Count unread VideoToolbox messages and refused encoder sets by kind
A VideoToolbox message a paravirtual session could not read, and a property
set the running encoder could not take, were logged with no kind and never
counted: a second kind of wrong, or a second property, was said only at
debug, and neither showed in a boot's degradation counts.

Their lines now name the wire error, or the property, as their kind, so each
kind is said once a boot at WARN and the rest at debug. The sessions count
each on their link, Link::count, which the device's link adds to its
degradation counts as vt-message-unread and vt-encoder-property-refused
(docs/conventions.md, "Each degradation is logged once per boot, then
counted"). What the guest sees is unchanged.

(cherry picked from commit 0b4768c51e3f5e5667efce490209fbe3017cce3d)
2026-12-03 10:03:29 -08:00
Anees Iqbal fc298f4e68 🐛 Count each function handle the platform makes none of, by kind
A FUNCTION_HANDLE_CREATE whose function the platform made none of was logged
with no kind and never counted: a second reason (a refused library, a function
the library makes none of) was said only at debug, and none showed in a boot's
degradation counts.

Its line now names its reason as its kind, so each kind is said once a boot at
WARN and the rest at debug, and each is counted as function-handle-unmade
(docs/conventions.md, "Each degradation is logged once per boot, then
counted"). The guest's answer, refused, is unchanged.

(cherry picked from commit f8ba0acf36df559ace838b9d7d19814305d2f249)
2026-12-03 10:03:29 -08:00
Anees Iqbal e0c05f6708 🐛 Count failed dynamic libraries and refused VT_MESSAGEs by kind
A dynamic library's create answered other than OK, and a VT_MESSAGE the device
refused, were logged with no kind and never counted: a second status or reason
was said only at debug, and neither showed in a boot's degradation counts.

The library's line now names its status (INVALID_ARGUMENT, NOT_FOUND, REFUSED)
as its kind, and the message's its reason, so each kind is said once a boot at
WARN and the rest at debug, and each is counted, as
dynamic-library-create-failed and vt-message-refused (docs/conventions.md,
"Each degradation is logged once per boot, then counted"). The guest's answers
are unchanged.

(cherry picked from commit 8cf4b098cdcb8035cff718ad5d67af50d627f8f7)
2026-12-03 10:03:29 -08:00
Anees Iqbal bc17434d55 🐛 Count each VideoToolbox encoder the arm makes none of, by kind
An encoder session the arm made no encoder for was logged with no kind and
never counted: a second reason was said only at debug, and none showed in a
boot's degradation counts.

Its line now names the arm's error as its kind, so each kind of reason is said
once a boot at WARN and the rest at debug, and each is counted as
vt-encoder-open-failed (docs/conventions.md, "Each degradation is logged once
per boot, then counted"). The guest's statuses are unchanged.

(cherry picked from commit 8c4095068faa029fe629e9cf62d9bcf9195340ff)
2026-12-03 10:03:29 -08:00
Anees Iqbal 7581ada0e6 🐛 Count each use of a refused object, logged once a boot
A use of an object whose posted create the host refused was logged the first
time for each such object and never counted: every later use of it, and what
it dropped, was unseen, and none showed in a boot's degradation counts.

Each use now reaches the logger, said once a boot at WARN and the rest at
debug, and is counted as refused-object-named (docs/conventions.md, "Each
degradation is logged once per boot, then counted"). What the guest sees is
unchanged.

(cherry picked from commit a001fd2ba8e8c5e373eed6a4f1c6708b738d6b88)
2026-12-03 10:03:29 -08:00
Anees Iqbal 909d89d326 🐛 Count dropped upload records and two-copy Managed textures
An UPLOADS_WRITTEN record the host drops, and a Managed texture made two copies
on unified memory, were each logged the first time in the process and never
again, and never counted: every later one, a different wrong among them, was
unseen, and neither showed in a boot's degradation counts.

Each now reaches the logger, the dropped record with what it does wrong as its
kind, so each kind is said once a boot at WARN and the rest at debug, and each
is counted, as uploads-written-dropped and managed-texture-two-copies
(docs/conventions.md, "Each degradation is logged once per boot, then
counted"). What the guest sees is unchanged.

(cherry picked from commit 72dfca93766cf3136ce5c04bf6dd8e7ebdcb277f)
2026-12-03 10:03:29 -08:00
Anees Iqbal e9aff18ad3 🐛 Count each failed VideoToolbox decode and encode, logged by kind
A VideoToolbox decode or encode that failed was logged once a decoder (or
encoder) for each reason, and never counted: its repeats within a session never
reached the logger, and with no kind on the line a second reason was said only
at debug. Neither showed in a boot's degradation counts.

Each failure now reaches the logger with its reason as the kind, so each kind
of reason is said once a boot at WARN and the rest at debug, and each is
counted as vt-decode-failed or vt-encode-failed (docs/conventions.md, "Each
degradation is logged once per boot, then counted"). The guest's statuses are
unchanged.

The video harness checks it on a stalled write's session: on its fake leg, the
stalled decode and the two the arm then fails are counted, said at WARN once
for each of their two classes; on a card (ignored), each failed decode is
counted and has its line.

(cherry picked from commit 9793eae6ece600fc89881199f754c1521d17d04a)
2026-12-03 10:03:29 -08:00
Anees Iqbal 028e64b1d3 🐛 Bound the draws' wait on their fence's event at the device wait
A draw into a video cache's planes over Direct3D 11 waited on its fence's
event with no bound (WaitForSingleObject with INFINITE). What the host saw
before: a stuck GPU hung the draw forever, and the thread that made it with
it, with nothing logged. The wait's fallbacks already ended the process past
DEVICE_WAIT; the normal wait did not, the same class as an unbounded wait on
a device elsewhere, which the planner ruled bounded the same way.

The wait now has one deadline, DEVICE_WAIT (5 s) from its start on the
clock of the runtime the draws were made with: the wait on the event times
out at it, and a failed call of that wait polls the fence up to the same
deadline, not a new one. Past it the draw or clear is DrawError::Unwaited,
on which reims-vgpu's drawn planes end the process with the fatal they
already name. What the host sees now, where the GPU never finishes the
draws: the process ends 5 s into the wait with "reims-vgpu: fatal: platform
call the wait for the Direct3D 11 draws into a video cache's planes: the
fence's event did not answer the GPU done with the draws in 5.0 s", where it
hung. A wait past its bound leaves its event open, since the fence may set
it yet. A wait whose GPU finishes in time returns as before.

The test holds the context's signal of the fence back (a seam of the tests),
so the fence never reaches the draws' value. Before, the draw gave no answer
20 s past the bound (mini job m3-max-84618); now the draw and a clear are
each Unwaited at the bound, and a draw after them returns as before.

(cherry picked from commit 1b9a67a51f23a25eff617dd10c575c3c495835d4)
2026-12-03 10:00:36 -08:00
Anees Iqbal f8ff66e79f 🐛 Wait on an event query where the draws' signal is refused
A refused ID3D11DeviceContext4::Signal failed a draw or a clear into a cache's
planes before its flush, leaving its work recorded and not submitted. The
VA-API arm landed the picture by the CPU's copy, and the context's next flush
then ran the draws with no wait for them, writing a cache whose picture the
CPU had already landed, from a pool texture that may by then hold another
picture.

The refused signal now ends an event query made with the draws, the flush
submits the work all the same, and the wait polls the query under the same
5 s bound: Ok once the GPU passed it, counted as video-drawn-waits-queried. A
query refused too is Unwaited, on which the process ends with the named death,
unless the device was removed. PlaneDraw::new now also fails where the device
makes no event query.

Seen on the Windows mini with the signal refused in a test (potluck job
m3-max-84428): the draw returned Err before the GPU ran its context's stream.

(cherry picked from commit c5d2983b8ad9d5ca5dba9551686bf14e804c34cc)
2026-12-03 10:00:36 -08:00
Anees Iqbal 338003dbbb 🐛 Poll the draws' fence where the wait on its event fails
On Windows, a picture's Direct3D 11 draw into a cache's planes waited for its
fence on an event: CreateEventW, SetEventOnCompletion and WaitForSingleObject,
each made after the flush had submitted the draws. Where one failed, as it can
when the host runs short, the draw answered Err while the GPU still ran it.
The VA-API arm then cleared the zeros the textures owed and landed the picture
by the CPU's copy into the same textures, with nothing waiting for the draw,
which could then write over the CPU's picture from a pool texture that may by
then hold another picture. A clear of owed zeros waited the same way.

Such a wait now polls the fence's value instead, for DEVICE_WAIT (5 s), the
video crate's bound of a frame's work, on the draws' runtime's clock, which
PlaneDraw::new now takes. The draw or clear answers Ok once the fence reaches
its value, Failed where the device was removed, as before, and Unwaited past
the bound, on which reims-vgpu ends the process with a named death: nothing
would tell when the GPU is done with the textures. Each wait that polled is
counted as video-drawn-waits-polled, the first failure of each call logged.

Seen on the Windows mini with CreateEventW refused in a test (potluck job
m3-max-84428): the draw returned Err before the GPU ran its context's stream.

(cherry picked from commit 0f4f05e52c92c56cc3ee5f3ca4e0f19d80dc939f)
2026-12-03 10:00:36 -08:00
Anees Iqbal 90325e6a46 ✅ Check that a stalled write's surface waits for it
Audit row S12: a hardware write into a surface the guest lent that runs past
the device's 5 s wait is kept on Lingering, and the session answered the
decode's failure and let the surface go (rels) at the wait's end, while the
write could still land in it after the guest had it back.

The harness's schedule holds the first write 6 s. The test passes where the
surface goes back only once the write is done, and fails in bounded time
(the 6 s and a second of settling, within the run's 20 s and 40 s bounds)
where it goes back at the wait's end, with the run's record. On the fake
leg, in the default suite, the late write lands in the surface on virtual
time; on the card leg (#[ignore]d), the real arm's wait is answered done
6 s after it began, on VA-API or NVDEC.

(cherry picked from commit e18eb6f2fed0f7d37bef4219094c64ae11fd59b3)
2026-12-03 10:00:36 -08:00
Anees Iqbal 949fec4697 ✅ Play VT decoder sessions with seeded delays, no guest
A bug's timing in the host's video was reached only by a boot. This adds a
host-only harness that plays a guest's VideoToolbox decoder session over the
paravirtual host, the device's VtBackend and an arm, with delays at named
points, so that the timing is reached in a test.

- reims_vgpu_video::video_delay: three points, each a class of sites. The
  hardware's write wait (VA-API's video processing and NVDEC's copies into
  guest memory, in the arm's own wait and in what Lingering asks), a
  session's answer (Demt, TDem) and its release (rels). A Schedule, written
  by hand or drawn from a seed, is installed on a runtime's clock and records
  each point reached. Only test builds and the new testkit feature (which
  reims-vgpu's testkit turns on) have them; every other build gets an empty
  inline hook with no lock, atomic or environment read.
- cargo xtask hooks, run by cargo xtask check: the default build of
  reims-vgpu-video for Linux names nothing of video_delay and holds no
  RVG_VIDEO_SEED, and its testkit build names the module.
- graphics::video_harness (tests): plays our own VP9 stream (libvpx's
  vp9p0 and its vpxdec MD5s). It records each message, each point reached
  and each picture's verdict, read back from the surface the guest lent and
  compared with the stream's MD5. A run fails where a surface goes back
  before a write into it is done, where a surface is written after it went
  back, where a picture emitted noErr is not the stream's, or where a frame
  goes unanswered within its real-time bound. A seeded failure prints
  RVG_VIDEO_SEED=<seed>, which replays its schedule.
- Two legs. The fake platform and a fake arm on virtual time, in the
  default suite, with a seeded test per point. VA-API or NVDEC on the rt
  device, #[ignore]d, for the VA-API and NVIDIA hosts.

The paravirt message names are public under testkit, the guest-RAM helpers
of surface_pages::costs are visible to the graphics module, and reims-vgpu
takes reims-vgpu-video-conformance as a dev-dependency for its MD5.

(cherry picked from commit 5b7fb568b557dc6b26a3d8e782ba9c7d18eaed52)
2026-12-03 10:00:36 -08:00
Anees Iqbal cadac770c2 📝 Fill the hand-over rows the stall holds and gap B close [ci skip]
005049a93b and bb8738f7eb hold a stalled write's answer until the device is
done with it, so rows 2, 3 and 10 (an arm64 guest's VideoToolbox decode into
the lent pages, and its message in hand at a reset) and rows 14 and 17 (an
x86-64 guest's landing into its output's pages, and a landing in flight at a
reset) have a wait now, with the tests that hold it; row 13 says a stalled
failure is signalled only then.

Gap B (18a2d29cfc) has a faulted walk's stand-in wait for the work its walk
handed a session, or the failure's post wait for it on the CPU, so row 13
states that wait with its three tests, row 17 the settle's wait through the
stand-in, and rows 21, 22, 24 and 25, which read "none" for the faulted walk,
point at row 13. Row 22 names the encode-wait test (8f3eb42f3b).

(cherry picked from commit ceda663d282c7d0c31f334edb2666577b5574706)
2026-12-03 09:31:09 -08:00
Anees Iqbal 92f2bcce93 🐛 Refuse a download whose copy's command buffer ended in error
After a device loss on rt, a surface lock could answer done with another
surface's texels in its pages. rt ends every command buffer in error once its
device is lost, and a staged download's landing never looked at the error: the
CPU moved the staging piece into the pages whatever the GPU copy did, and the
spare pieces circulate between surfaces, so the pages took the bytes the piece
last held from another surface's copy, and the SURFACE_DOWNLOAD was answered
done. A guest command buffer that synchronized a surface landed its staged
copies the same way, whatever its outcome.

Now a copy out whose command buffer ended in error takes the surface cache's
"Refused copies" path, as one the platform refused a command of does, counted
under surface-copy-refused: a staged copy gives its pieces back without moving
their bytes into the pages, a circulating one stops at the failed round and
commits no later round, a straight one's shapes are dirty again once the copy
is taken back, and the download is answered RGFX_STATUS_REFUSED, so the next
download copies the cache again. A synchronize's staged copies land only where
the guest's command buffer completed with no error; one that ended in error, as
its CB_COMPLETE tells the guest, leaves the pages as they were.

The download now answers refused, which matches the owner's 11-19 ruling that
a lost device is not recovered and each later operation fails.

(cherry picked from commit 0307ea974291ae20687d3dd395af2a6e152daf60)
2026-12-03 09:30:41 -08:00
Anees Iqbal 399ca284b2 🐎 Move a shape in place whose textures take several formats
A move in place makes each guest texture over a shape a view of one image in
place over the pages, made of the textures' usages together. Where a texture
was in another colour format of the texel's size and none declared
PixelFormatView, Metal would view no such image as it, so the move was
declined as retarget and the shape kept its own image and its copies. Metal
itself makes each texture over an IOSurface in the format it names, whatever
its usage. The walks showed it once a boot at the login on the Iris (an
R32Uint storage shape of 512 by 512 that a texture in another format also
took) and on the 780M (m3-max-83207, 83208).

The move's image now takes PixelFormatView beside the textures' usages where
one of them is in another uncompressed colour format of the texel's size, as
Metal's view rule asks (metal2vulkan's views_with_usage), and the in-place
shape keeps that usage, so a later texture in such a format is a view of it
and does not move the shape off it. A format Metal views no image as, of
another size or no colour format, still declines the move as retarget. A
texture in such a format made while the image is made races the move, and a
later begin makes the image with PixelFormatView.

metal2vulkan-runtime at the pin makes that image: a texture of PixelFormatView
usage lists its views' formats and is made mutable (texture.rs Plan::flags,
view_formats), and over a buffer in an import its linear image is asked of
the device's query with those flags and that list for the import's handle
(check_over, linear_extent). Where the device's query does not take it, the
make answers the import's cause, dma-buf or host-memory, and the move is
refused for that why as before.

This changes which path the host takes, not what the guest observes: the
textures read and write the same bytes, now in the pages with no copy. The
test that held the decline now holds the move, its image of usage 0x13, both
views retargeted and a later texture taken; another holds the usage choice
against Metal's view rules.

(cherry picked from commit fda04f1b8bf6b85180d80782485f0a031984d523)
2026-12-03 09:30:41 -08:00
Anees Iqbal f10bd55a14 🐛 Log each kind of a refused move in place once, as its line says
A refused move in place logs its why with the image's pixel format, size and
usage, the first of each such kind, and keeps the first 64 kinds to that end.
The line also named the code as its kind for the library's logger, which
writes an info line that names one once per call site and class of that
text: the text up to its first digit, the code alone. So the logger wrote
the first kind of each why and dropped the others at debug, while each still
spent one of the 64 kinds. On a 780M walk (m3-max-83208), with 150 and more
dma-buf moves refused an arm, the retarget and dma-bufs moves were counted
with no kind logged in any arm, where the Iris walk logged the retarget's.

The line now names no kind for the logger, and a function of its own writes
it for each kind the 64 keep. What the host sees: one info line for each of
the first 64 kinds of refused move, where it saw one a why. The counts are
unchanged. The test holds one line a kind through the library's logger,
none for a kind again, and none past the 64; with the code named as the
line's kind it sees two.

(cherry picked from commit 6c89f5ced4bbc80c1b0012a81da4c9c3e70e4b85)
2026-12-03 09:30:41 -08:00
Anees Iqbal 80bdfad5ab 📦 Build the guest's kext sets again with predicated arguments
Both sets, guest/prebuilt and guest/prebuilt-arm64e, rebuilt on the M3 from
this branch's tree, sQ's bb8738f7eb with the predicated-arguments fix on top
(m3-max-84377: make -C guest prebuilt, prebuilt-arm64e, then prebuilt-check,
which passed). RgfxGate's Metal bundle now reflects arguments under function
constants a function has no value of, as Metal does. Only RgfxGate's binary
and the sets' records change.

(cherry picked from commit 03b1c89aa90e186a41a9d683585e98544f496697)
2026-12-03 09:30:41 -08:00
Anees Iqbal aee1261178 🐛 Reflect arguments under constants a function has no value of
RealityKit's usdz preview on macOS 11.7.11 asks each of its functions for
its own reflection (reflectionWithOptions:). Some of their arguments sit
under function constants the function has no value for. The bundle answered
nil for each such function, logging "an argument's predicate kX is no
constant of the function's values". Quick Look then drew the material cube
of a scene as nothing, and the bare cube in magenta, where Preview drew both.

What Metal answers, measured by an oracle probe of our own (predref) on
macbook-pro-2019, macOS 26.7.1 (25G241), the AMD Radeon Pro 5300M. The same
functions were compiled at run time and built for macOS 11 and 26, and all
three answer alike:
- made by name (no values): no argument under a predicate is listed, not
  even one under `is_function_constant_defined(k) ? k : true`. One at an
  index a constant computes is listed at 0xFFFFFFFF. Every listed argument
  is used.
- made with values that lack k, a required k among them: the argument is
  left out under k, !k, k && true or k || false, and kept under k || true
  or the default above. A pipeline of those values is made, and its
  reflection lists the same arguments.

What the guest sees now: a predicate is evaluated three-valued, with each
constant the function has no value of unknown. The module's initialisers
already decide a select whose arms agree; an integer and with 0 and an or
with all ones now give that whatever the other operand holds. The argument
is kept only where the predicate is true, and left out where it is false or
unknown, where before the whole reflection was nil. A required constant the
process left without a value is unknown to the reflection, though the
host's compile still takes its 0. A function made by name knows no constant
and no constant's being defined. It keeps no argument under a predicate,
lists one at an index constants compute at 0xFFFFFFFF, and its uses are the
AIR's. The stage input attributes of a specialised function follow the same
rule.

Not matched: which arguments the values leave unused. Metal's compiler
removes code that branches on a constant of no value, and the bundle's
reader does not, so it answers those arguments used. Metal refuses a
function whose values lack an index constant; the bundle makes it.

test_function_reflection_of_predicated_arguments holds the oracle's answers
for the probe's functions (tests/predicated_arguments.metal), by name and
with values that lack kA, kB or both. Before this change every one of those
reflections was nil.

(cherry picked from commit 38d6e39e174a19bd81bd86c9b9c269e3bed0c737)
2026-12-03 09:30:41 -08:00
Anees Iqbal f054ad57c1 📝 Re-read the hand-over rows the batch's rules reword [ci skip]
The batch rewrites gpu_copy.rs's module doc (one failed copy's scratch and
arguments kept, the GPU copies ended at a second) and takes a wait that
returns with its command buffer unfinished as a failed one, so row 19 quoted a
sentence the tree no longer holds and the handovers check failed. Row 19 is
re-quoted from the tree and states the one-kept-then-end rule; rows 6, 16 and
23 add the unfinished wait, and the intro says how it is taken. The rows name
the batch's new tests: the gather pass and the caches copy counted or kept on
an unfinished wait, gpu_copy's four, and the encoders' kept fillers (rows 26
and 27), whose sessions upload their later frames.
2026-12-03 09:28:47 -08:00
Anees Iqbal ec6a5c7093 🆕 Count where each decode's picture lands in a video cache, and why
A browser video step on a 780M sent 34 pictures of one H.264 session
through the GPU copier into their caches' buffers at the IOSurface's own
layout, where they would have landed in the caches' surfaces, and nothing
said which came first for those caches: the texture that asks a cache's
surface, or the decode op.

Each decode op over a cache made for the host's video, in the per-shape
form, is now counted by where its picture lands and why: in the surface,
asked by a texture made before or after a decode landed in the buffer; or
in the buffer, the decode's textures not showing both planes whole, the
cache having no two-plane layout, no texture over a plane having taken a
shape of the cache yet, the first such texture having taken another shape
than the plane's whole one, or the surface asked and not made by the op,
refused by the platform, or made and not taken. Each cache's first landing
in its buffer, and its first in its surface after one there, is logged at
debug under reims_vgpu::graphics::video_landing with the cache's planes,
the first texture's shape and order, and the decode's textures' places.

(cherry picked from commit 3dd3a3c845db730028e4e3b66d8e040516107c07)
2026-12-03 09:16:19 -08:00
Anees Iqbal 0a68343102 🐎 Give a kept NVDEC decoder more surfaces as it is taken
A kept decoder served a new session of its format only with surfaces
enough, so a guest's 400x258 HEVC thumbnail, which asks for 8, still made
its decoder in its first session (cuvidCreateDecoder, 43 ms on an RTX 3090)
while the wallpaper's 1024x1024 decoder of 5 surfaces was kept
(m3-max-83451).

A kept 4:2:0 decoder at 8 or 10 bits with fewer surfaces than asked is now
taken and reconfigured to the asked count with the asked size, before its
first decode (Made::fit). NVIDIA's headers document that a reconfiguration
may raise the count: dynlink_nvcuvid.h of ffnvcodec-headers 13.1.15.0,
lines 505-507, on CUVIDPARSERPARAMS::bMemoryOptimize, "use
cuvidReconfigureDecoder() to increase the decode surfaces if needed (perf
may get impacted)", quoted at the take. A reconfiguration NVDEC refuses
destroys the kept decoder and makes one with the asked surfaces, so no
picture is decoded on the old count; a test fails the reconfiguration and
counts the make. The take left out a kept decoder of another GPU by
counting its surfaces as none, which a decoder that adds surfaces would
take; it now leaves it out by its GPU (pick_on_gpu), with a test.

VP9 is left out (adds_surfaces), decided before the take: on an RTX 3090
with driver 620.70.06, a kept VP9 decoder made with 2 surfaces and
reconfigured to the 11 a libvpx stream asks, cuvidReconfigureDecoder
returning success, refused the stream's second sample, a superframe whose
frames take surfaces 1 and 2, with CUDA_ERROR_INVALID_VALUE, where a
decoder made for the stream decodes it (m3-max-83719). VP9 takes only a
kept decoder with surfaces enough, as do monochrome, 4:2:2, 4:4:4 and 12
bits of their own size (D32); a test keeps a 2-surface VP9 decoder and
checks that the stream makes its own and decodes to libvpx's frames.

Measured on an RTX 3090, driver 620.70.06 (m3-max-83840; the same tests pass
on this tree, m3-max-84002): a kept 1024x1024 decoder made with 2 surfaces,
raised to as many as the stream asks, decodes H.264 High, HEVC Main and Main
10 and AV1 streams, every picture held until no surface is free (14, 8 and
8, and 17 each for SVT-AV1's streams at 8 and 10 bits), to the pictures of a
decoder made for them, and is taken for 400x272 with 8 surfaces in 3.4-4.1
ms, its reconfiguration included, against 10.8-12.4 ms for one made. A
400x258 HEVC stream's first picture, from its decoder's start through its
decode and read-back, took 7.1-7.4 ms on a kept 1024x1024 decoder raised
from 5 surfaces, 6.9-7.2 ms on one with surfaces enough and 14.1-15.0 ms on
one made (m3-max-83971, a probe).

What the guest sees: a session of a new size and more surfaces than the
kept decoder of its format has starts without a decoder made. In a macOS
26.7.2 guest's boot with this change's first form, whose HEVC take is this
one (m3-max-83913), the thumbnail's first session, 25.8 s after the GPU's
last work, took the kept 1024x1024 decoder of 5 surfaces and raised it to
8: its first decode call took 11.7 ms (cuvidReconfigureDecoder 11.66 ms)
against 42.8-43.4 ms with cuvidCreateDecoder (m3-max-83275, m3-max-83451),
but its first picture's map took 31.6 ms against under 1 ms, and the
session ended 101.5 ms after its make, against 77.7 and 98.6 ms. A later
session of that boot, 26.7 s after the last work, made and reconfigured
nothing and still took 30.4 ms to land its first picture: after such an
idle the first landing pays about 30 ms unless a make came before it.

(cherry picked from commit 1703dc3b211ade4276049fc1f3a4a066525dde68)
2026-12-03 09:16:09 -08:00
Anees Iqbal d6cf91bc2c 📝 Add the x86-64 guests' last video hand-overs [ci skip]
The table gains the x86-64 guests' remaining hand-overs, 8 rows:
- on Linux, VA-API's scratch copier: the video processing into the scratch,
  and the kernel's copy from it into the output's caches;
- on Windows, the Direct3D 11 draw into a cache's surface;
- the readers of a picture whose command buffer completed at its decode;
- a section for the encode: its source, the staging out of the caches, the
  access unit and the result, and an encode at a reset.
The section both guests share moves to rows 26 to 30, and row 13's test is
named by its whole module path.

Rows that read none, each already with its owner: 20, the draw whose wait's
calls fail once it is submitted or whose signal is refused; 21, 22, 24 and 25
for a walk that faults after the session took its work (row 13's path); and
19's failed wait, which no rt wait takes.

(cherry picked from commit 44d901ed8c5b01bab953d2cad1e1e3305faae3be)
2026-12-03 09:16:09 -08:00
Anees Iqbal 2d3cf99566 ✅ Check the hand-over table against the tree it is in
docs/video/hand-overs.md names a test for each hand-over and quotes the
sentence that documents its wait. Both go stale silently: the table was
checked against one tree, then stacked on two later batches, and a rename of
two tests and a rewrite of a module doc in between left three of its places
wrong with nothing failing.

xtask's handovers test reads the table and fails on each row that names a
test no function of crates/ holds, or quotes a sentence (its [...] cuts apart)
the file named before it does not hold, a doc comment's wrapped lines read as
one. cargo xtask check runs it with the workspace's tests, so a change that
renames a test or rewrites a quoted doc fails until the table follows.

(cherry picked from commit ea6257772ae675f6711a536d88becedc8add9011)
2026-12-03 09:16:09 -08:00
Anees Iqbal ad23d2ec61 📝 Add the video hand-over table [ci skip]
docs/video/hand-overs.md lists each point where one API writes a picture or
an encode's source and another reads it: the writer, the reader, the one wait
between them, the sentence that documents the wait, the test that holds it,
and what the reader gets when nothing landed. A row whose wait reads none has
a path on which the reader can get the picture while the writer may still
write it.

It holds the hand-overs read so far, 22, as the tree is now:
- the arm64 guests' paravirtual decode: the lent surface, NVDEC's copies,
  VA-API's video processing, the 4:4:4 scratches and their gather, a Mac
  host's VideoToolbox picture and its copy, the lend itself, a reset;
- their encode's source, and an encode at a reset;
- the x86-64 guests' decode landings: the session's event, pages, device
  caches, staging, a reset;
- what both guests share: the runtime's copies into NVENC's and VA-API's
  inputs, the CPU's upload, and the CPU's read backs of VA-API's and NVDEC's
  pictures.

On the rt platform no command buffer's wait fails (its wait returns once the
command buffer has ended), so a row's path for a failed wait is the testkit
platform's alone; the table says so once, above the rows.

AGENTS.md's row of the video docs names the new file.

(cherry picked from commit 05ffc21d6bb1b6181b7b219853b710779adadede)
2026-12-03 09:16:09 -08:00
Anees Iqbal 46b88ea6ed ✅ Check failed staged landings log once and count
The planner asked that, in each bounded place, the path a lost device takes on
the rt platform (copies that end in an error, at each later picture, as the
device is not recovered) log the failure once per boot by kind, count it
after, and park nothing, so that nothing grows a picture. For a session's
staging copies, and for the VA-API GPU copier's copies, which fail the same
landing, this held already. No test pinned it through a session.

a_session_whose_copies_end_in_errors_logs_once_counts_each_and_keeps_nothing
runs four staged pictures whose copies all end in an error. It checks:
- each picture fails to land and is counted (video-pictures-handed-failed);
- the landing's line ("a picture did not land: ...", logged with the error's
  class as its kind) reaches the logger's hook once;
- one staging buffer serves every picture, so nothing is kept out of use.
The copier's own error path keeps nothing as well
(a_copy_that_ends_in_an_error_takes_its_scratch_and_arguments_again).

Nothing changes for the guest or the host.

(cherry picked from commit a9f875d919c3eb31bed6a1bb442bbbf85444017d)
2026-12-03 09:16:09 -08:00
Anees Iqbal 5b15fab30a 🐛 Count and log each 4:4:4 GPU pass that ends in an error
On the rt platform a lost device is not recovered: it ends each later command
buffer in an error. For the 4:4:4 gatherer that is a pass whose wait returned
and which ended in an error (Ungathered::Failed). Its picture fails and
nothing is kept out of use. The failure was reported only by the VideoToolbox
decoder's line, "a VideoToolbox decode failed". That line has no kind of its
own, so every decode failure of the boot shared one kind. It was logged once a
decoder a reason, and the later ones were not counted at all.

Gatherer::gather now counts each such pass as video-gpu-gathers-failed. It
also logs a warn whose kind is the error's class, so the library's logger
writes each class's first line and counts the rest. This is a failure path
that a walk reports. The NVDEC and VA-API (XYUV) 4:4:4 routes both go through
it. docs/conventions.md and answer.rs list the code.

What changes for the guest: nothing. Each such picture fails as before.

Test: a_pass_that_ends_in_an_error_is_counted_and_logged_once_a_kind (stand-in
device). Four passes end in an error, with nothing kept out of use and one
arguments buffer for all. The test checks that each is counted and that the
logger's hook sees one line.

(cherry picked from commit 18e18ef8f8e31e617ef166130fff5287a8e70038)
2026-12-03 09:16:09 -08:00
Anees Iqbal 840510da02 🐛 Take a wait that returned unfinished as a failed one
Where rt refuses a command buffer's wait (Refusal::WaitOnOwnThread on its
completion thread, or InScheduledHandler in a scheduled handler, at the pinned
b531238180), RtCommandBuffer::wait_until_completed counts the refusal
(rt-refused-*) and returns Ok at once. The command buffer may still be
unfinished: its status is neither completed nor an error. The three bounded
places read any status but completed as a pass or copy that ended in an error
and is done, and reused its buffers on the next picture. Those are the 4:4:4
gatherer's arguments, a session's staging buffer, and the VA-API GPU copier's
scratch and arguments.

Each place now matches the status after the wait:
- completed: done;
- an error: ended and done, so its buffers are reused, as before;
- anything else: the wait returned before the work finished. The work may
  still run on the GPU, so it is taken as a pass or copy whose wait failed.
  Its buffers are kept out of use (video_host::OutOfUse), and a second such
  one ends the route.
OutOfUse's doc and the three module docs say so.

The testkit's waitUntilCompleted takes a scripted false (Step::value(false)) to
return at once, the command buffer as it stands, standing in for rt's answer
to a refused wait.

What changes for the guest: none of the video's paths waits on rt's
completion thread or in a scheduled handler, so no run reaches this. Where one
did, a picture whose wait returned unfinished would still fail, and the buffers
the GPU may still use would no longer be written for the next picture.

Tests (stand-in device), each with a wait that returns unfinished, then a
second:
- a_pass_whose_wait_returns_unfinished_is_kept_out_of_use_and_a_second_ends_the_gatherer
- a_copy_into_caches_whose_wait_returns_unfinished_is_kept_out_of_use_and_a_second_ends
- a_copy_whose_wait_returns_unfinished_is_kept_out_of_use_and_a_second_ends_the_copies

(cherry picked from commit 226339caf489b4d186bf8022e66cea234ebd922f)
2026-12-03 09:16:09 -08:00
Anees Iqbal 7e2711aa03 🎨 Keep an NVENC session's failed filler, as its docs say
When a frame's copy into NVENC's input failed once submitted,
Fills::encode_filled replaced the session's filler with Err(why). That dropped
the Filler, and with it the input in its `failed` list, while
nvidia/encode/fill.rs's module doc says that input is kept out of use while
the session lives. This has been so since b448dbe667. Fills now keeps that
filler, and its input with it, in `_failed` while the session lives, as the
VA-API arm's Fills does. The session fills no more frames with it, so it
keeps one such filler and one input at most. The docs say so.

From reading the code, the drop freed nothing before the GPU was done with
it:
- rt's command buffer keeps every buffer it uses until it retires
  (metal2vulkan-runtime's CommandBuffer, at the pinned b531238180);
- NVENC holds CUDA's import of each input it registered for the session's life
  (NvencEncoder's device_inputs).
So the drop let go of our handle and, for an input NVENC had not yet
registered, CUDA's import alone. Nothing changes for the host in a run, or
for the guest: the frame fails and the session's later frames are uploaded by
the CPU, as before.

Test: a_frame_whose_copy_fails_fails_and_its_filler_is_kept_on_rt (NVIDIA
host, ignored). With the hook Filler::fail_copies, the second frame's copy
fails once done. The test checks that the frame's result is FAILED, that the
session keeps the filler with frame 0 filled and the failed input, and that
frames 2 and 3 are uploaded and come back OK.

(cherry picked from commit f99a7119155ac95cac570b4d581323e40533fd4d)
2026-12-03 09:16:09 -08:00
Anees Iqbal 8049f041a4 ✅ Check a VA encode session keeps its one failed filler
A VA-API encode session's Fills kept a Vec of the fillers whose write failed
on the GPU. It could only ever hold one: at the first such failure, Fills
swaps its filler for Err(why), pushes the old filler into the list, and never
fills with a filler again. In the same way, DeviceFiller's own list of inputs
whose fill failed holds one at most, because its caller fills no more frames
with it. The S5-1 audit flagged both lists as possibly growing.

Fills now holds the failed filler in an Option, `_failed`, named so because
nothing reads it: it is kept for its drop. The docs say why each holds one
at most.

The guard test
a_frame_whose_fill_fails_fails_and_the_session_uploads_its_later_frames
(VA-API host, ignored) checks this. A filler fails its second frame's fill
once done, using DeviceFills::filler_failing_at, which makes a filler whose
fill fails after a given number of good ones. The test checks that the frame
fails, that the session keeps the filler, and that the session's later frames
are uploaded by the CPU and coded.

Nothing changes for the guest or the host.

(cherry picked from commit 92cb1b59a695dafa5b18fbf2f73bfb45b6bab117)
2026-12-03 09:16:09 -08:00
Anees Iqbal 71f92cd691 🐛 Keep one failed GPU copy's buffers out of use, ending at a second
A VA-API decode session's GPU copier (vaapi/gpu_copy.rs) kept the scratch of
every copy that failed once submitted, whether its wait failed or it ended in
an error, and made a new scratch for the next picture. A GPU that kept failing
grew the list by one dma-buf scratch a picture for the session's life. On rt,
where a lost device ends copies in an error, that was the path taken. Under a
failed wait the copier also wrote its arguments buffer again for the next
copy while the GPU might still be reading it, the same hazard the gatherer had
before 4bb5db49fc.

The copier now follows video_host::OutOfUse:
- A copy whose wait returned and that ended in an error is done on the GPU,
  so the next picture's copy reuses its scratch and arguments.
- A copy whose wait failed has its scratch and its arguments kept out of use
  while the session lives, and the next picture's copy makes new ones.
- At a second copy whose wait failed, the session's GPU copies end. That
  copy's buffers stay where they lie. The ending is counted once as
  video-gpu-copies-ended, which the degradation counts report, and logged
  once a kind. Each later picture is declined, so it lands by the CPU's copy,
  the landing's third way.
rt's wait never fails, so on rt these failed-wait paths are a guard.

What changes for the guest: a picture whose copy failed still fails. After a
second failed wait in a session, its later pictures land by the CPU's copy
instead of going to the GPU. The bytes are the same either way. The VA-API
test that ends a session's copies checks this on each picture declined after
the ending: a new session's copier copies that picture on the GPU, the cache
is read back, and it must match the CPU's copy byte for byte
(ReadBack::copy_coded_into, which the landing's third way runs). The copier's
existing test, now on the same helper (copy_as_the_cpu), checks every copied
picture the same way. On the host, a run of errored copies keeps no scratch
per picture.

The new code is listed in docs/conventions.md, docs/video/vaapi.md and
answer.rs's counted kinds. answer.rs also gains the three codes of 4bb5db49fc,
which it was missing.

Tests:
- On the stand-in device:
  a_copy_whose_wait_fails_keeps_its_scratch_and_arguments_out_of_use,
  a_second_copy_whose_wait_fails_ends_the_session_s_gpu_copies,
  a_copy_that_ends_in_an_error_takes_its_scratch_and_arguments_again.
- On a VA-API host (ignored), with the test hooks fail_next_wait and
  fail_next_copy:
  a_picture_whose_copy_s_wait_fails_fails_and_a_second_ends_the_session_s_gpu_copies,
  a_picture_whose_copy_ends_in_an_error_fails_and_its_scratch_is_taken_again.

(cherry picked from commit 658f749d30426f478cae3568c0270d5dbd8b9517)
2026-12-03 09:16:09 -08:00
Anees Iqbal b12328d344 📝 Say rt's command-buffer waits never fail [ci skip]
The docs of the video arms' kept-out-of-use paths (video_host's OutOfUse,
Stage and STAGING_ENDED_CODE, gather, xyuv, nvidia and videotoolbox) said that
on the rt platform a command buffer's wait fails when the device is lost. No
such wait fails there. RtCommandBuffer::wait_until_completed returns Ok in
every case and counts a wait that rt refuses. rt's own wait
(metal2vulkan-runtime's CommandBuffer::wait_until_completed at the pinned
dfbc157464) loops until the command buffer has finished, and a lost device
ends its command buffers in an error, which that loop returns on. So on rt a
lost device's pass or copy takes the path of one that ended in an error. The
failed-wait paths, and the bound on what they keep, run only on the testkit's
stand-in device; on rt they are a guard.

The docs now say this: OutOfUse's at length, the others by pointing at it.
xyuv's stalled driver write (the VA crate's Error::Stalled) is a bounded wait
of VA-API's, not a command buffer's, so its wording stays.

Nothing changes for the guest or the host.

(cherry picked from commit 2425c5f7c1069f6e4dcb0f8194ea946aaa2a8e29)
2026-12-03 09:16:09 -08:00
Anees Iqbal 8f3eb42f3b ✅ Check that an encode's buffer waits for its session
encode_op hands the frame to the session, which reads the source in place,
and then has the command buffer wait for the session's event to reach the
encode's value, so that the buffer completes, and the guest writes the source
again, only after the session is done with it. No test held that wait: a
decode's is checked (a_video_encoder_hands_its_session_each_decode), an
encode's was not. This test walks an encode on the fake platform and checks
that encodeWaitForEvent:value: on the encode session's event, at the value
the encode answered, is encoded before the buffer's commit. Nothing changes
for the guest.

(cherry picked from commit 0b740157c80589378936562ef4e429cb43804610)
2026-12-03 09:16:09 -08:00
Anees Iqbal 3fd3114085 ✅ Test the failure posts' stand-in-or-wait as one call
Both of the host's failure posts (the ring's, for a message the decoder did
not carry out, and the lane's, for a command buffer walked in its turn) made
a stand-in where they may, and otherwise waited on the CPU for the video work
the walk handed off, each in an inline form of its own that no test reached.
They now call GraphicsDecoder::stand_in_or_wait, which a test drives on the
fake platform: a failure stood in for waits for nothing on the CPU, one with
nothing handed off goes on at once, and one not stood in waits until the
session's event reaches the handed-off value.

The order at the lane is unchanged: the stand-in, else the CPU wait, then the
turn's wait, under the same turn and reset-gate guard. A reset that comes
during the CPU wait waits up to HAND_OFF_WAIT (15 s), inside
RESET_SETTLE_BOUND (30 s): a comment at the wait says so, and a const assert
by HAND_OFF_WAIT keeps the two in that order. Nothing changes for the guest.

(cherry picked from commit b7b2b2f1c9e416bb9248097243fe9a842289325f)
2026-12-03 09:16:09 -08:00
Anees Iqbal d9986c3dcd ✅ Check that a faulted walk's signal is posted once
An audit read a walk that passes a mid shared-event signal and then faults
as keeping its Signals notification armed, so that EVENT_SIGNALLED could
reach the guest twice: once from the walk's notification, and once from
the stand-in. The Finisher's drop lets the faulted walk's sink go, so its
notification posts nothing. This test pins that: a walk that asked for a
notification as it passed a signal, then faulted, has its value posted
once, by the stand-in's completion, ahead of the buffer's failure. Nothing
changes for the guest.

(cherry picked from commit 6082cc9e710f32f2dc0bf5876e5ccf159ac36652)
2026-12-03 09:16:08 -08:00
Anees Iqbal 18a2d29cfc 🐛 Wait for a video op's handed-off work before a walk's failure
decode_op hands the picture to the session, which starts it at once, and
encode_op hands the frame; ops after that hand-off (the cache's note of the
decode, the wait's encode, any later op of the buffer) can still fault. A
faulted walk's buffer is never committed: its stand-in carried the guest's
event ops alone, not the session's wait, and where no stand-in was made the
failure was posted at once. So the guest was told of the failure while the
landing still wrote the output's pages, or an encode still read its source
in place, and a reset's settle waited for the stand-in, not the work.

decode_op and encode_op now note each hand-off (the session, its value, and
how many of the buffer's event ops came before it) on the message's state,
cleared at each message's begin. stand_in_for_failed waits for each value at
its place among the event ops it carries, a signal before it then posted as
its event reaches it. Where no stand-in is made, both callers wait on the CPU
for the values before posting the failure (wait_for_hand_offs), bounded by
DEVICE_WAIT and STALL_HOLD, 15 s, past which a stalled landing has ended the
process.

What the guest sees: a command buffer that faults after its decode or
encode was taken completes failed only once the hardware's work on its
surfaces ends, instead of at once.

(cherry picked from commit 8bcf5132400d8833b850b0c5275eba0df4a358bc)
2026-12-03 09:16:08 -08:00
Anees Iqbal c92ae9cdaa ⬆️ Build on metal2vulkan development b531238180
Pin U, from dfbc157464 (T): 56 commits, no merges: c6a7995260 and its
bless commit, which touches only the translator's tables.

What changes for the guest:
- A kernel's [[stage_in]] attribute read through an indexed step
  (MTLStepFunctionThreadPositionInGridXIndexed or ...YIndexed) at a step
  rate past 1 is now fetched: element origin + index[min(position / rate,
  size - 1)], as an M3 Max reads it (metal2vulkan's stage-in-region-clamps,
  rows at rates 2 and 3). Before, the compute pipeline state was nil with
  an NSError (rt's Gap::StageIn, IndexedStepRate).
- A texture of the private usage bit BlockWritesOnly (0x10000) takes a
  kernel's write as one of ShaderWrite does, and takes an index: the
  guest's where it places one, else one of the platform's own. Before, a
  texture of the bit alone had no index (resourceIndex and gpuResourceID
  0), and a write through it was refused at the dispatch
  (TextureUsageAtSlot).
- A thread-local global of the thread address space compiles, each
  thread's own from its initializer; before, rt refused the module
  (ModuleRecord code 7).
- A device-coherent texture's reads and writes (MSL 3.2
  memory_coherence_device) compile, coherent at device scope; before,
  UnknownIntrinsic. A coherent access beside a storage image compiles too;
  before, NotImplemented Lowering(MemoryModel).
- A kernel's or vertex function's calculate_clamped_lod through a runtime
  sampler compiles under the identity domains, reading the sampler word's
  minimum level; before, refused.
- A padded form's (R10Unorm_X6, RG10Unorm_X12, their _sRGB twins) linear
  mip filter blends two levels, and a bfloat form's reads the nearest
  level. The device makes no texture of these formats, so no guest
  reaches it.

What changes on our side:
- reaches() counts BlockWritesOnly with ShaderRead and ShaderWrite, as rt's
  reached does, so new_texture asks rt for an index for a texture of the
  bit alone; without it, rt refuses the make (Refusal::TextureIndex).
  shaders_reach_read_write_unknown_and_colour_target_usage and
  textures_and_their_indices_on_vulkan hold it.
- rt's StageInKind::IndexedStepRate and the translator's
  Feature::KernelStageIn are gone. The diagnostics' StageIn-IndexedStepRate
  gap cannot occur and goes with its docs and the ledger's line.
  a_kernel_s_stage_in_is_fetched_by_the_stage_in_region_on_vulkan fetches
  an indexed step at rate 3 (the recording's row xi_rate3_o2_r4_g12) in
  place of expecting the refusal; refusals_count_by_kind counts the two
  forms left.
- The counts line folds rt's six restoring-make metrics as
  rt-restoring-makes, rt-restoring-make-drain-ns, rt-restoring-make-wait-ns,
  rt-restoring-make-wait-submissions, rt-restoring-makes-shared and
  rt-restoring-make-shared-wait-ns, after the Shared coherence codes.
  over_copies_fold_into_the_counts_by_their_rise holds them.

(cherry picked from commit 391961f3365b8366a9673b444b67cd7d13f5e6af)
2026-12-03 09:00:09 -08:00
Anees Iqbal bb8738f7eb 🐛 Hold a stalled landing's failure until its write is done
The x86 device's own video sessions had the same gap. VA-API's zero-copy
processing into an output's pages (VaPicture::land) and NVDEC's copies
into its registered pages (write_in_place) sent a stall past DEVICE_WAIT
straight up, its work kept on Lingering; only the landings in device
caches held for it. The landing loop then cleared the planes and signalled
the session's event, so the guest's decode command buffer completed,
failed, about 5 s into the stall while the write could still land, after
a reset too.

The landing loop takes a KeptMark before each landing, and a landing that
failed with work kept since it (hold_stalled_landing) is counted
(video-landing-stall-held), logged once a boot, and held on
hold_while_kept up to STALL_HOLD before the clear and the signal; past it
the process dies. A landing that failed in device caches held there
already, so nothing is held twice. TEARDOWN_WAIT goes from 10 s to 15 s,
DEVICE_WAIT and STALL_HOLD, so a session's end waits a held landing out
instead of logging that its last picture did not land and detaching.

What the guest sees: a stalled picture's failure reaches its command
buffer up to 10 s later than the 5 s it took, once nothing of the host's
writes the output; a device that never finishes ends the process at 15 s.
A test pins that a reset's release of waits sets no session's event, so
the reset's settle waits for the decode's command buffer, and so for the
landing.

(cherry picked from commit 36ee87e5fc967b6edede54174db124be3d31c4b9)
2026-12-03 08:41:40 -08:00
Anees Iqbal 005049a93b 🐛 Hold a stalled VT decode's answer until its write is done
In an arm64 guest's paravirtual VideoToolbox decode, NVDEC's DMA and
VA-API's zero-copy processing write the lent surface's guest pages
themselves. Their waits end at DEVICE_WAIT (5 s); past it the decode
failed as a malfunction while the work stayed on Lingering, still able to
write the pages. The session then sent the error, Dfub and the surface's
rels at once, so the guest could reuse a surface the host was still
writing, and a reset's wait for the session's message in hand could end
with the write pending, to land after the reset returned.

VtDecoder::land takes a KeptMark before the arm's decode and passes the
answer through answered_once_written: a failure with work kept since the
mark is counted (vt-decode-stall-held), logged once a boot, and held until
Lingering lets the work go, up to STALL_HOLD (10 s); past it the process
dies, as the device caches' landings do (Landing::failed_in_caches).
hold_while_kept, kept_since and STALL_HOLD now build on every host, since
arm64 guests run on Windows hosts under TCG; VtBackend takes the
platform's clock.

What the guest sees: a stalled decode's error, and the rels of its
surface, come up to 10 s later instead of at once, only once nothing of
the host's can write the surface; a device that never finishes ends the
process 15 s into the stall, inside the reset's 30 s bound.

(cherry picked from commit 0b81777dfbc101c80f53f7da5cf8cb514df2eb58)
2026-12-03 08:41:40 -08:00
Anees Iqbal 4bb5db49fc 🐛 Keep one buffer out of use at most, ending the route at a second
S5-1 (06cdbdc075, b13fe6059b, 9a849a50a7) kept out of use the buffer of each
GPU pass or copy that failed once committed: the 4:4:4 gatherer's arguments, the
NVIDIA arm's and the XYUV route's 4:4:4 scratches, and a host video session's
staging buffer. Those lists had no bound: each failed pass parked a frame-sized
buffer for the life of the decoder or session, and the next picture made a new
one, so a GPU that keeps failing grew host memory without limit. They parked
too where the wait returned and the command buffer ended in an error, when the
GPU is done with the buffer.

The four places now share one rule (video_host::OutOfUse):
- A buffer is kept out of use only where the wait itself failed (on the rt
  platform, a lost device). A pass or copy whose wait returned and which ended
  in an error fails its picture or frame as before, and its buffer is used
  again. The XYUV route's scratch after a driver's write that failed is kept
  only where the write stalled (VaError::Stalled, as work_ended reads it); a
  write that failed otherwise has stopped.
- One buffer is kept at most. At a second failed wait the route ends, as the
  XYUV route's Gathered::Ended ends it at a refused scratch: the second buffer
  stays where the route holds it, used no more, so a failing GPU holds two
  buffers, not one a picture.
- Gatherer::gather answers Ungathered::Failed (its wait returned, the pass
  ended in an error), Running (its wait failed, its arguments kept) and Ended
  (a second: the gatherer submits nothing more).
The NVIDIA arm's route takes an ended state like the XYUV route's, kept while
the decoder lives. Its scratch refusal ends it the same way, where it dropped
the route before, and with it buffers the GPU may still read. The VideoToolbox
arm (videotoolbox.rs) keeps nothing out of use and is unchanged.

What changes for the guest: nothing on a live device. After a second failed
wait (on the rt platform, a lost device), a VideoToolbox decoder on the NVIDIA
arm or the XYUV route takes its later 4:4:4 pictures the CPU's way, as where
the device refused its scratch: lands_4_4_4_by_gpu answers false and the
surfaces come with no buffer over them. Before, each went to the GPU through a
new scratch. A host video session stops staging: each later picture that
stages a plane for a device cache fails to land at once, handed failed as it
was at its copy's failed wait before, and each later encode frame staged out of
a device cache fails, with no new staging buffer.

What changes for the host: each ending is counted, its first logged at warn
under its kind: video-staging-ended, video-nvdec-gathers-ended and
video-xyuv-gathers-ended (docs/conventions.md), each a failure path.

Tests (S5-1's tests of unbounded parking change here):
- gather: a_pass_whose_wait_fails_keeps_its_arguments_out_of_use (now
  Running), a_second_pass_whose_wait_fails_ends_the_gatherer,
  a_pass_that_ends_in_an_error_takes_its_arguments_again;
- video_host: a_route_keeps_one_buffer_out_of_use_and_ends_at_a_second,
  a_second_copy_into_caches_whose_wait_fails_ends_the_staging,
  a_copy_into_caches_that_ends_in_an_error_stages_in_its_buffer_again,
  a_session_whose_staging_ended_fails_each_later_staged_picture;
- xyuv: a_second_scratch_out_of_use_ends_the_route on the stand-in device;
  and, ignored (a VA-API GPU that writes XYUV),
  a_picture_whose_wait_fails_fails_and_a_second_ends_the_route (was
  a_picture_whose_pass_fails_once_submitted_fails_and_its_scratch_goes) and
  a_picture_whose_pass_ends_in_an_error_fails_and_its_scratch_is_taken_again;
- nvidia, ignored (an NVIDIA GPU):
  a_4_4_4_picture_whose_wait_fails_fails_and_a_second_ends_the_gpu_s_writes
  (was a_4_4_4_picture_whose_pass_fails_once_submitted_fails_and_its_scratch_
  goes) and
  a_4_4_4_picture_whose_pass_ends_in_an_error_fails_and_its_scratch_is_taken_
  again.
The GPU tests fail an ended pass through the gatherer's new test hook,
Gatherer::fail_next_pass; the stand-in tests through graphics::tests's
completing, which completes committed buffers with an error.

(cherry picked from commit 7a6409f1ac11af0758d08821dba3a629fe672fc5)
2026-12-03 08:31:44 -08:00
Anees Iqbal 55b69b5d73 📝 Put the fragments test's doc back over its own test [ci skip]
S9's reset test went in between the doc of
a_tile_in_fragments_lands_in_the_surface_its_first_fragment_lends and the
test itself, so the reset test carried both docs and the fragments test none.
The fragments doc goes back over its test, and the reset test's doc gets its
closing full stop.

(cherry picked from commit 8b662a2de44c7bed84f38c987d0a282cd0349636)
2026-12-03 08:22:59 -08:00
Anees Iqbal c6b6990a14 ✅ Check that a reset waits out the encode in hand
S9 made a device reset end every paravirtual VideoToolbox session and wait
for each session's message in hand. Its test drove a decoder session only, so
nothing held the encoder session's side of it: that a closed session carries
out no queued efrm, and that the reset's wait does not end while an encode
may still read the guest's surface.

The new test holds an efrm's encode at a gate, queues a second efrm behind
it, and ends the sessions. The wait does not end while the encode is held,
and ends once it returns. Only the first frame was read, the second never,
however long after. The encoder is dropped, nothing reaches the guest from
the ended session, and an efrm for its UUID is answered as one with no
session, its lend given back.

GuestEncoder::encode now says what the arms already do and what the wait
relies on: it returns only once its reads of the source are done, the
device GPU's among them. The NVENC and VA-API arms wait for their GPU copies
of the lent surface before they return, and a future arm is held to the same.

(cherry picked from commit c79bcccdcc8f15d0859c33bf0452b50d0a9f1ec0)
2026-12-03 08:22:59 -08:00
Anees Iqbal 5eb5c0292c ✅ Pin only RGB10A8_2P_XR10's heap pass-through
metal2vulkan-runtime keeps the sRGB twin (551) a typed refusal, so the device
answers its heap size REFUSED and the guest's bound takes it, as for any shape
the platform refuses. The test no longer has the fake make it in a heap: that
read as a pass the Vulkan platform never gives.

(cherry picked from commit 4547963d26eaa84afa179e0e0b1a24f51166083e)
2026-12-03 08:04:15 -08:00
Anees Iqbal 9158a11963 ✅ Check that XR10 heap textures reach the platform
An arm64 guest under an Apple GPU's rules sizes and places textures of the
two-plane XR10 formats (RGB10A8_2P_XR10, 550, and its sRGB twin) in heaps. On
the Vulkan platform both calls wait only for metal2vulkan-runtime's texture of
the format, which it refuses today: the device answers the size query REFUSED
and the bundle answers its own bound. The test pins that the decoder adds no
refusal of its own, so once the runtime sizes and makes the format, the guest
gets its sizes and its heap textures with no change here.

(cherry picked from commit 1df792cf258e1ab9b4fe20d8806238d3c8301a17)
2026-12-03 08:04:15 -08:00
Anees Iqbal d92883f92a 🐛 Give back the lends of a VT_MESSAGE the device cannot read
The device answers a VT_MESSAGE it cannot read with VT_STATUS MALFORMED, and
the host never sees it. The guest's kext counts that message as posted, so
it holds each lend the message named until a rels names it, and none ever
came. Each such message kept its lends, out of the kext's 64, until the kext
stopped.

Where the message's RgfxVtMessage struct reads, the device now sends a rels
for the nonzero lends it names, among its first surface_count, before the
VT_STATUS. A guest that did not take VT_MESSAGES gets nothing, as before.

What the guest sees: a rels naming the lends of an unreadable message,
ahead of its MALFORMED answer, so the kext gets those lends back.
2026-12-03 07:59:11 -08:00
Anees Iqbal 3d4169adbb 🐛 End the VT sessions at a reset before it returns
A device reset left every paravirtual VideoToolbox session running. The
reset contract (reims-vgpu-graphics device.rs) says device_reset drops what
the host keeps for the guest's processes, and that the settle returns only
once nothing begun before the reset can write the guest's memory. Neither
held for these sessions. The guest's kext lets go of every lend at its stop,
but a session open at a panic or a hard reset kept its thread, its hardware
decoder, its kept views and its lent surfaces. A decode in flight at the
reset could still write a picture into the lent surface's pages after the
reset returned, and the rebooted guest may already be using those pages.

Both device_reset and the settle now end every session, as -all does
(paravirt::Host::end_sessions). A closed session sends nothing more, and its
requests end at once. Its thread carries out no message past the one in
hand and gives back what each message lent. The settle waits, within the
reset's 30 s bound on the platform's clock, for each closed session's thread
to end, so the reset returns only once no session can write. A session still
holding a message past the bound ends the process, as GPU work past the
bound does: a write a hardware decoder or GPU copy has begun cannot be taken
back.

What the guest sees: nothing of the boot before writes its memory after the
reset returns, and a message for an old session's UUID is answered as one
with no session.
2026-12-03 07:59:11 -08:00
Xiaochi You 9324949b55 Merge pull request #9 from yxc0915/steelbrain/backport-hidpi-cursor
🐛 Backport HiDPI cursor crossing on x86 macOS
2026-12-03 23:48:54 +08:00
YXC0915 48dd6d2fad 🐛 Backport HiDPI cursor crossing on x86 macOS
Backport porcelainhorse's 4c6acb5e from steelbrain/reims-vgpu#180.

Rebuild both guest prebuilt sets with Xcode 27.2 from the maintenance tree to preserve its bundled guest changes.
2026-12-03 23:47:57 +08:00
Anees Iqbal e604a71d8b 🆕 Count a VT lend the host drops with no rels
vt-lends less vt-lends-given-back is not a leak count on its own. A walk
ends with QMP quit while the guest runs, and the device's release there can
end the open sessions before the exit counts line is written. Their rels
then go on an ended link, which sends nothing, and a reset closes every
older link the same way. So lends that were in flight at the quit or the
reset show in that difference without any leak, and the line cannot say
which.

A leak is a lent surface the host drops without letting go of it. The S8-1
reply in the race was one: no rels names it, and the kext holds the lend
until it stops. The host now notes each surface as it lets go of it, in
LentSurface::letting_go, before the rels is sent, whether or not it is sent.
A GuestSurface dropped without that note counts vt-lends-dropped-held, and
the first one is logged. The count is exact on any counts line, whatever
sessions are open. vt_message now checks its message's runs before it makes
its surfaces, so a refused message drops none unnoted. Nothing changes for
the guest.
2026-12-03 07:39:19 -08:00
Anees Iqbal 9ea707bc68 🆕 Count the VT lends the host holds and gives back
The guest's kext holds at most 64 lends of IOSurfaces at once for its
VideoToolbox messages, and once they are all taken, it answers every further
message kVTParameterErr without posting it. A lend the host never gives back
keeps its slot taken until the kext stops, so a leak slowly turns the guest's
hardware video off. Nothing on the host showed how many lends it held.

The host now counts each lend a VT_MESSAGE gives it as vt-lends, the most
it held at once as vt-lends-live-most, and each lend a rels it sent gave
back as vt-lends-given-back. This covers the rels a refused message sends
too. vt-lends less vt-lends-given-back is what the host holds, plus any
rels that went on a link a reset or the device's end had closed. Nothing
changes for the guest.
2026-12-03 07:39:19 -08:00
Anees Iqbal 04aef9e84e 🆕 Count deferrals refused for runs that are not whole pages
A deferred IOSurface block whose SURFACE_PAGES carries runs that are not
whole guest pages summing to its surface's bytes, or that carry no page, is
answered INVALID_ARGUMENT with nothing made. Until now that refusal showed
only as a warning, logged once per boot and then folded into the repeated
lines, so a walk could not say how often a surface was refused this way, or
how big those surfaces were.

The host now counts each such refusal as surface-carry-refused, and the
surface's bytes as surface-carry-refused-bytes, on the degradation counts
line. Nothing changes for the guest: the answer is the same refusal as
before. A deferral refused for its flags is not counted under these codes.
2026-12-03 07:39:19 -08:00
Anees Iqbal 95dd1e1058 🐛 Hold a fragmented tile's surface until its last fragment
A tile (dtil) whose sample is past the guest's message buffer comes in
fragments, and the surface it lends may come with an earlier one. The
session let go of each fragment's surfaces as soon as it had kept its bytes,
so the tile's last fragment came with no surface: the tile was emitted with
kVTParameterErr and landed nothing, and its region of the image was left as
the guest's buffer held it.

Now the surfaces a tile's fragments lend are kept with the fragments, and
are the tile's at its last fragment, the earlier ones first; they go back
after the tile's reply, or with the fragments where those are dropped, and at
the session's end. What the guest sees: the tile lands in the surface its
first fragment lent, is emitted noErr, and the surface's rels comes after the
reply, as an unfragmented tile's does.

The test sends a tile in two fragments, its surface with the first, and
checks that nothing comes back until the last, then the tile's emission,
reply and rels.
2026-12-03 07:39:19 -08:00
Anees Iqbal c22a641b8b 🐛 Give back a held frame's surface when its number comes again
An encoder session keeps each frame, with the surface the guest lent for it,
until it is both encoded and emitted, by the guest's frame number. A second
efrm of a number still kept took the first's place, and the first frame's
surface was dropped with no rels: the guest's kext kept that lend for the
rest of the boot, out of its 64.

Now the frame that takes a kept frame's place lets the kept one's surface go.
What the guest sees: a rels for the first frame's surface as the second efrm
is taken, before its reply; the second frame goes on as any frame does.

The test holds frame 0, sends frame 0 again, and checks the first surface's
rels, then the second's at the invalidate.
2026-12-03 07:39:19 -08:00
Anees Iqbal 9dbce89570 🐛 Name a buffer lent past its Dbuf's wait unused
A decoder session asks the guest for each frame's output buffer (Dbuf) and
waits 1.1 s for it. Where the reply came later, the frame had already failed
with no buffer, and the late reply's surface was let go of, but the buffer
the guest registered for it was never emitted nor named unused (Dfub). The
guest's VideoToolbox kept that buffer out of its pool until the session
ended: one buffer of the stream's size for each late reply.

Now a host request may leave what its reply gets past the wait, the reply
handed over as the wait ends among them, for its session's last 64 requests
that stopped waiting. A Dbuf leaves a Dfub of the buffer its late reply
lends. What the guest sees: the frame still fails as before, then a Dfub
names the late buffer, so VideoToolbox has it back, and its surface goes back
with a rels.

The decoder test answers a Dbuf past its wait and checks the Dfub then the
rels; a session test checks that a reply handed over as the wait ends gets
what its request left, before its rels.
2026-12-03 07:39:19 -08:00
Anees Iqbal a5f49442d4 🐛 Give back what a reply lent as its request's wait ends
A host request that waits for the guest's reply (a decoder's Dbuf, whose
reply lends the frame's surface) gave up at its deadline and then stopped
waiting. A reply that came in between found its request still listed, was
handed to the wait that had just ended, and was dropped with it: the
surfaces it lent never got their rels. The guest's kext holds each lend
until the host's rels, at most 64 at once for the whole service, so each such
reply kept one for the rest of the boot, and once 64 were kept the kext
refused every lend and every hardware decode and encode of the guest failed.

Now a request that finds its reply handed over as it stops waiting takes it
back from the ended wait and lets go of what it lent, as it does for a reply
that comes later. What the guest sees: the request still fails as timed out,
and the surface goes back with one rels.

A test hook between the deadline and the end of the wait delivers the reply
there; the test checks the one rels, and a second test the later reply's.
2026-12-03 07:39:19 -08:00
charlysound 00607de750 🎨 Preserve upstream view-storage accounting with native mesh
Merge master 4312d830 after its runtime pin propagation. Keep the fully verified ef6a42c8 producer while preserving the new ViewStorage cause, kind-only classification and diagnostic counters. Re-run the bridge gates on this combined source; the runtime producer is unchanged.
2026-12-03 16:33:37 +01:00
Anees Iqbal 9a849a50a7 🐛 Keep a staging buffer whose cache copy failed out of use
A host video session stages a picture's planes, or an encode's source, in one
staging buffer and copies them into or out of the output's device caches on the
GPU. A copy that failed once committed failed its picture or frame, but the
buffer stayed the session's, so the next picture or frame staged its bytes in
it. Where the copy's wait failed (on the rt platform, a lost device), the GPU
may run the copy still, reading the buffer into the old output's caches or
writing it out of them, while the CPU writes or reads the next one's bytes
there.

Stage now keeps a staging buffer whose copy failed once committed out of use
while the session lives, and the next copy stages in a new one.

What the guest sees: nothing on a live device, where the wait returns once the
copy is done. After a lost device, a later picture or frame no longer shares a
buffer with a copy that may still run.

Test: a_copy_into_caches_whose_wait_fails_keeps_its_staging_buffer_out_of_use,
on the stand-in device with a scripted failed wait.
2026-12-03 07:28:47 -08:00
Anees Iqbal b13fe6059b 🐛 Fail a VT picture whose GPU copy failed once committed
The Mac host's VideoToolbox arm copies each picture into the guest's surface on
the GPU, and fell back to the CPU's copy on any failure of that copy, a failed
wait or an errored command buffer among them. Where the wait failed (on the rt
platform, a lost device), the GPU may run the copy still, so the CPU's copy and
the late GPU copy could both write the guest's surface.

gpu_copy now answers Uncopied::Declined before anything is committed, which the
CPU's copy follows as before, and Uncopied::Failed once committed, which fails
the picture as a malfunction.

What the guest sees: nothing on a live device, where the wait returns once the
copy is done. After a lost device, the picture's decode answers
kVTVideoDecoderMalfunctionErr, where a CPU copy raced the GPU's before.

Test: a_picture_whose_copy_fails_once_committed_fails_with_no_copy_of_the_cpus
(ignored: VideoToolbox's decoder and a stream), on the stand-in device with a
scripted failed wait.
2026-12-03 07:28:47 -08:00
Anees Iqbal 06cdbdc075 🐛 Fail a 4:4:4 picture whose GPU pass failed once submitted
A VideoToolbox decoder's 4:4:4 picture lands in the guest's surface through the
videoGather444 pass, on the NVIDIA arm and on the VA-API arm's XYUV route. The
gatherer answered a pass that failed once submitted as it answered a refusal
before anything was submitted. The caller then copied the picture into the
surface by the CPU, and the next picture's pass rewrote the same arguments
buffer and read the same scratch. Where the pass's wait failed (on the rt
platform, a lost device), the GPU may run the pass still: the CPU's copy and the
late pass could both write the surface, and a later picture's bytes could reach
it.

Gatherer::gather now answers Ungathered::Declined before anything is submitted,
and Ungathered::Failed after. A failed pass fails the picture as a malfunction,
with no copy of the CPU's. The gatherer keeps its arguments out of use, and the
decoder its scratch, while it lives, as gpu_copy and the VA-API fill keep
theirs; the next picture makes new ones.

What the guest sees: nothing on a live device, where the wait returns once the
pass is done. After a lost device, the picture's decode answers
kVTVideoDecoderMalfunctionErr, where a CPU copy raced the pass before.

Tests: a_pass_whose_wait_fails_keeps_its_arguments_out_of_use, on the stand-in
device with a scripted failed wait; and, ignored, for the NVIDIA arm
a_4_4_4_picture_whose_pass_fails_once_submitted_fails_and_its_scratch_goes and
for the XYUV route a_picture_whose_pass_fails_once_submitted_fails_and_its_
scratch_goes, through the gatherer's test hook, which fails a wait once its
pass is done.
2026-12-03 07:28:47 -08:00
Anees Iqbal 2c6ed20a20 🐛 Open a paravirt decoder again after a refused reopen
A sample whose format description carries another configuration record
reopens the session's decoder. Where the backend refused that open, the
frame's Demt carried the refusal and the decoder was gone, and the session
answered every later dfrm with 311 (no decoder) until the guest invalidated
it, samples that carried a description included. A sample carrying the
session's own first record did not even try: it compared equal to the
configuration the refused open left behind.

Now the next sample that carries a description tries the open again, the
session's first record included. Where it opens, the guest gets the
buffer attributes (Dpba) and the frame decodes and lands. A sample with no
description still answers 311 until one opens.

The fake backend refuses a given number of opens, and a test pins the
sequence: a refused reopen, 311 for a sample with no description, then the
first record reopens and lands with its parameter sets.
2026-12-03 07:28:47 -08:00
Anees Iqbal d1e705473a 🐛 Answer dcan no where a reopen would refuse the description
A paravirtual decoder session answers dcan (CanAcceptFormatDescription) before
the guest sends a sample of another format description, which then reopens the
decoder. dcan checked the codec, the size, that the record reads and its NAL
unit length, but not what open() refuses besides: a stream whose pictures the
host decodes none of (the codec's refusal or the arm's declines, undecoded())
and a record with no format to land in. So dcan could answer yes to a
description the reopen then refused, leaving the session with no decoder.

dcan now answers through the same refusals open() makes, so it says no exactly
where a reopen would refuse.

What the guest sees: after a mid-stream switch, at the same codec and size, to
a profile, chroma format or depth the arm does not decode, dcan answers no and
the guest's VideoToolbox makes a new session for the stream, as
VTDecompressionSessionCanAcceptFormatDescription documents. Before, every later
frame of the session failed with 311 (no decoder).

Test: can_accept_answers_whether_the_decoder_goes_on now also holds a no for an
H.264 High 4:4:4 stream at 10 bits, which the host decodes none of.
2026-12-03 07:28:47 -08:00
charlysound e602ea71f9 🎨 Merge upstream runtime-pin update without losing mesh
Resolve the upstream 14c37cc dependency update in favour of the verified ef6a42c8 producer. Preserve the restoring-make documentation with its ancestor reference. Relative to 87a45542 the only tree change is that documentation; product code and dependency bytes are identical, so existing final-pin and mesh execution evidence applies.
2026-12-03 16:28:27 +01:00
charlysound 87a455427d ⬆️ Pin the completely verified native mesh runtime
Pin all translator, runtime and devtools dependencies and Cargo.lock to public ef6a42c895681abf6f4a2f4a6f06da8f1194e421. Its only source difference from the qualified 14536cada is the complete golden table regenerated with genuine Apple tools. Preserve the precision-count regression and current-master fixes.
2026-12-03 16:24:59 +01:00
Anees Iqbal fca18a89bb 🐎 Keep the last sizes' VA-API processing contexts
A guest's previews make one short video session after another, each with
buffers of its own, and each size's video-processing context went with its
last import. So every session's first run was a new context's first run in
the driver, a few milliseconds on radeonsi. Measured before, on the Radeon
780M (Mesa 26.2.6, m3-max-83333): a 400x258 HEVC thumbnail's frame took 5.54
to 6.83 ms from its take to its signal across 12 sessions of one size, its
run's vaEndPicture 4.83 to 6.14 ms of that.

The imports' table now keeps the contexts of the 4 sizes imported last
(KEPT_CONTEXTS) past their last import, at most 4 at once beside those live
imports hold, and holds no surface: a context is made on none. A size
imported again moves to the back; a size imported past the 4 pushes out the
one imported longest ago, destroyed once no import holds it; the rest go with
the table, which the VA-API arm holds, so at the arm's teardown. No time
bounds it: the decoder cache's idle epoch is Windows' alone, where no dma-buf
is lent and so no import or processing context is made. A unit test fills
the table past its cap, and the 780M's hardware test pushes a kept context
out with 4 other sizes.

What 4 kept contexts, each run once, freed as they went, by the driver's
fdinfo for the process: nothing on the Radeon 780M (radeonsi, m3-max-83634),
and 7,244 KiB of drm-total-system0, 28 KiB of it resident, on the Iris Xe
(i915, intel-media-driver 26.3.5, m3-max-83635), about 1.8 MiB a context.

Measured after, the same thumbnail on the same 780M, in one job alternating
A (this change) and B (the tree without it), each arm a boot of 6 sessions 4
s apart and 6 back to back (m3-max-83795): with it, every session but a
boot's first took 1.11 to 1.97 ms from its take to its signal (median 1.55
ms, 22 sessions), against 5.29 to 6.83 ms without it (median 6.12 ms); a
boot's first session of the size, on a new context, took 5.8 to 6.8 ms in
both. The guest's warm qlmanage thumbnail took 0.072 to 0.081 s with it and
0.075 to 0.090 s without.
2026-12-03 07:23:27 -08:00
Anees Iqbal f29d3abfc5 📝 Say that the host does not bound a lock's hold wait [ci skip]
With the kext's 1 s bound gone, a lock waits as long as the host's span
lasts, and nothing on the host bounds that span: read from the runtime's
code, a make whose batch holds an upload into memory another API shares
waits for guest GPU work submitted with it. design.md now says the wait is
not bounded by the host, and gives the 57.9 ms span as what one walk on an
Iris Xe showed, not as a limit.
2026-12-03 07:22:33 -08:00
Anees Iqbal 1f21a92e10 📝 Give the hold's longest measured span alone [ci skip]
The span the docs gave came from one arm of the walk, with a reason for it
the walk did not establish. The longest span the walk measured on the Iris
Xe is 57.9 ms, its cause not yet split: design.md and HOLD_BEGIN_BOUND's
comment now give that alone, and design.md no longer says what the make
waits on.
2026-12-03 07:19:10 -08:00
Anees Iqbal f9cc3d5f91 📝 Give the hold's span on an Iris Xe as it stands [ci skip]
design.md's hold section held a placeholder for the longest span a lock
waits on the hold. A guest's walk on a Linux host's Iris Xe, with the
runtime's restoring make no longer sharing its batch with the guest's command
buffers, measured 57.3 ms at the longest and 62.2 ms over its 8 spans, no
begin's wait given up and nothing declined no-lock-hold.

HOLD_BEGIN_BOUND's comment now says what holds: how the runtime's restoring
make waits, and the span the walk measured against the bound, with no runtime
commit, date or job in it.
2026-12-03 07:19:10 -08:00
Anees Iqbal 12b3367b2e ✅ Check that a stale install's pair takes no hold
A host and a kext set from either side of the hold word's move meet where a
user updates one and not the other. Each such pair must come out as before
the hold existed: no hold taken and no create answered, on both sides, never
one half alone (a host answering creates the kext does not wait for, or a
kext waiting on a word the host never raises or lowers).

The host's an_older_kext_on_this_host_takes_no_hold_and_gets_no_answered_create
starts the device with a driver that takes bit 1 of what is offered, as such
a kext does, and with one that writes bit 1 outright: the driver reads back
no bit, the host takes no hold, and no create over pages is answered. The
answered-creates test shares its helper, which now also checks the host's
hold flag. The kext's surface_hold_test checks the other pair: on a host
that offers bit 1, the kext writes nothing, reads back no hold, says no
answered creates in its word and admits no answered Submit, and a read-back
of bit 1 would turn neither on.

Tests only: nothing the guest or the host sees changes, and the kext sets
are unchanged, as the kext's tests are none of their sources.
2026-12-03 07:19:10 -08:00
Anees Iqbal c917902e93 📝 Link the hold word's place to Caches::note_hold_word [ci skip]
InPlace::hold_at's doc linked SurfaceCaches::note_hold_word, which does not
exist: the method is Caches'. rustdoc -D warnings refused the link on every
target. The comment only; nothing else changes.
2026-12-03 07:11:01 -08:00
Anees Iqbal 8cff64e8f9 🐛 Wait out the host's hold span with no bound of its own
A read-write CPU lock waited 1 s at most on a raised hold word, then went
on with the word still raised. The bound was there because any process
holding the surface could store RAISED in the block's header and keep it up.
Now only the kext and the host write the word, so nothing but the host's
span keeps it raised, and a lock that goes on inside the span loses its
writes to the span's copy back.

A lock now waits as long as the host's span lasts. The wait still ends once
the word is lowered, the device stops or resets, or the thread is aborted.
kPastBound, the bounded wait, its count and the kext's log line for a lock
past the bound are gone, so a walk's count of such locks reads 0 from now.
What the guest sees: no lock goes on with the word raised.

Both kext sets, guest/prebuilt and guest/prebuilt-arm64e, are built again
from this tree.
2026-12-03 07:11:01 -08:00
Anees Iqbal 2e1b9c570f 🔒 Keep the surface hold word where no process maps it
The hold word lay at byte 8 of a cached block's header, which every process
holding the surface maps writable: any holder could store RAISED there and
hold the other holders' read-write CPU locks of the surface. The word now
lies in the block's own part, which no process maps. Each block laid out in
place keeps a 4 KiB hold page past the span its holders map and before its
runs, and the word is the page's first u32, at region offset runs_offset -
RGFX_SURFACE_HOLD_ROOM, where the host finds it from SURFACE_PAGES. The kext
maps the page with the header and stores 0 there as it caches the block, so
only the kext and the host write the word.

The hold moves to FEATURES_EXT bit 2 (feature bit 66). Bit 1, the hold in
the header, is retired: no host offers it, a write of it takes nothing, and
it is never reused. A mixed pair therefore takes no hold. A guest with an
older kext on this host, or this kext on an older host, gets no image made
in place over a cached surface's pages (declined no-lock-hold) and no
answered creates of textures over pages buffers. Mixed pairs come only from
a stale install, since reims-ctl carries the kext sets with the host.

The host refuses a word that would lie in the block's first 4 KiB, where the
header is: such a block has no hold word, is counted (rt-shape-hold-no-word)
and its makes that copy are declined no-lock-hold. Our kexts lay out none.
The host lowers the word on every exit of a make whose span it opened: rt's
after, or the fence's own drop where the make fails or unwinds past it. As
before, a lock's wait also ends where the device stops or resets, or the
thread is aborted; rgfxHoldSleep now carries those ends, and the native test
holds them. The kext logs the live in-place blocks and what their hold pages
take of the region, and the host logs its holds with the no-word count, so
one boot per guest reads both.

What the guest sees: each in-place block takes 4 KiB more of the region on
x86-64, and 0 or 16 KiB on arm64, where blocks are whole 16 KiB pages; no
process can hold another's locks through the word. The option ROM's record
takes the wire header's new hash; the ROM's bytes are unchanged. Both kext
sets are built again with the next commit.
2026-12-03 07:11:01 -08:00
charlysound bfea808f23 🎨 Merge latest video fixes and refresh native mesh producer
Preserve current master 3a4adacb video changes and pin the translator, runtime, devtools and lockfile to public 14536cada, merged with master pin T. Retain the verified mesh precision-note regression. Combined validation follows without changing the installed VM.
2026-12-03 16:03:39 +01:00
charlysound e42fb09ccc ⬆️ Pin the completely verified native mesh runtime
Pin all translator, runtime and devtools dependencies and Cargo.lock to public 7e6efdaffad502a72f5b684a79438a6db0f1a81d. Its only source difference from the qualified 2c297ad7b is the complete golden table regenerated with genuine Apple tools. Preserve the precision-count regression and current-master fixes.
2026-12-03 15:58:52 +01:00
Anees Iqbal 4312d83052 ⬆️ Build on metal2vulkan development dfbc157464
Pin T, from 14c37cc76d (S): 31 commits, no merges.

What changes for the guest:
- A fragment shader that copies texture handles as integers and merges
  them at a join now compiles as the handle of the branch taken. A handle
  phi of a constant with one candidate of its class compiles too. Before,
  rt refused both (Lowering(Access) HandleUse, ConstantOperand); a 3D-model
  preview's lit pipeline met the first at each boot.
- A texture over a buffer that is written through a view of another
  format, where the device makes that linear image only plain, is now a
  counted copy (rt's OverCause::ViewStorage) instead of the extended
  image in place. The guest reads and writes the same texels.
- A select of a typed 64-bit atomic's slot on the address form compiles;
  before, rt answered an internal error (ZeroAddress).
- rt's mode-2 texture-buffer word writes round half and RG11B10 to
  nearest even. The device answers no to mode 2, so no guest reaches it.

What changes on our side, for the new cause:
- The counts line folds rt's view-storage copies as
  rt-over-copies-view-storage and rt-over-copy-bytes-view-storage. The
  trace's rtcounts carries the pair after image-memory's.
- A shape's in-place refusal and download name it view-storage. Like
  linear-features, it comes from the descriptor and the kind of memory
  alone, so it is kept per descriptor and kind.
- The 10 s summary lists its bytes as "view storage".
- over_copies_fold_into_the_counts_by_their_rise holds the new pair.

HOLD_BEGIN_BOUND's doc says the restoring make's wait holds "from
14c37cc76d on", which T leaves as it was.
2026-12-03 06:57:39 -08:00
charlysound 553c764713 🐛 Record native mesh pipeline precision notes at creation
Apply upstream precision reporting to the mesh descriptor path too. The CPU pixel regression compares the counted rise with the state’s own nonempty notes, so missing or doubled reporting fails. It fails before the fix with no counts instead of colour-conversion and interpolation notes, then both CPU mesh cases pass with the fix.
2026-12-03 15:42:28 +01:00
charlysound 27e3174e26 🎨 Merge current master and refresh native mesh dependency
Preserve upstream shared-surface hold fixes and precision reporting alongside the native mesh bridge. Pin all three translator/runtime/devtools consumers and Cargo.lock to public runtime 2c297ad7b, merged with current master. Validation follows on this identified source without installing it into the VM.
2026-12-03 15:30:21 +01:00
Anees Iqbal fdc1ecbbb5 ⬆️ Build on metal2vulkan development 14c37cc76d
metal2vulkan's development moves from 0959445d39 to 14c37cc76d, 34 commits
(SEMANTICS_VERSION 2342, RUNTIME_VERSION 2559, ARTIFACT_FORMAT_VERSION 606).
The runtime's restoring make waits for its restore's batch, not for the
command buffers of a group that goes in the same batch. The translator
declares a texture buffer's storage slot without a format under the identity
domains, and holds a texture buffer made to be read and written as words
where its format's own view reads none without a format; runs fragment
storage writes under texture write rounding mode 2; blends an extended-range
3D texture's two levels for a linear mip filter; records NativeHalfConversion
for half arithmetic on the 16-bit instructions; reads an A8Unorm colour held
in red through its view's alpha; and binds a slot's element of its set-1
array as its own pixel under the identity domains. The rest are validation
tooling, the conformance ledger, docs and the blessed golden and
compile-census tables.

What the guest sees change: a kernel or fragment function that reads and
writes a texture buffer through access::read_write, of a format whose view
the device reads only with a format (BGRA8Unorm, B5G6R5Unorm, BGR5A1Unorm,
BGR10A2Unorm, RG11B10Float, RGB10A2Unorm, RGB10A2Uint on ANV), runs where rt
refused it (Gap::StorageElement); an extended-range 3D texture's linear mip
filter runs where it was refused; a begin of the surface hold that waits for
a restoring make waits for the restore's batch alone. Kernels are translated
again on first use. Our device still answers no to texture write rounding
modes 1 and 2, so no guest pipeline asks for mode 2.

The hold's begin bound's doc says what the runtime's restoring make waits
for at this pin.
2026-12-03 06:16:44 -08:00
Anees Iqbal 3a4adacb52 ✅ Check that CoreMedia takes an HEVC prefix SEI
A paravirtual HEVC session hands the arm every array of the guest's hvcC
record, prefix SEI units among them where a file carries them, and the Mac
host's VideoToolbox arm passes them all to
CMVideoFormatDescriptionCreateFromHEVCParameterSets. Whether CoreMedia takes
an SEI there was not checked: a refusal would fail such a file's session at
its make.

The test makes the format description of the probe's VPS, SPS and PPS of a
64x64 Main stream, alone and with a prefix SEI of one user_data_unregistered
message, and a VideoToolbox session of the latter, and holds that each is
made.
2026-12-03 06:16:31 -08:00
Anees Iqbal e1f579aa27 🆕 Count the VT arm's IOSurface imports, made and reused
The Mac host's VideoToolbox arm keeps the imports of the last eight
IOSurfaces its pictures landed in (IMPORTS_KEPT), on the word that
VideoToolbox's pool lends a few surfaces again and again. Where the decoder's
outputs serve as its references too, a stream could cycle through more than
eight, and every picture would then import its surface again, a cost nothing
counted.

Each import a picture's GPU copy asks for is now counted, as made
(video-vt-surface-imports-made) or kept from an earlier picture
(video-vt-surface-imports-reused), on the counts line, so the next Mac-host
video run shows whether eight hold the pool's surfaces. The lookup moves into
Imports::kept_or_made.

Tests: an_import_is_kept_by_its_surface_and_counted_as_made_or_reused, and
the Mac-host stream test now prints the two counts and checks that an import
was asked for each GPU copy.
2026-12-03 06:16:31 -08:00
Anees Iqbal f64f14020a 🐛 Answer a VT decode's status to the guest as the host's VT gave it
The Mac host's VideoToolbox arm mapped every VideoToolbox status through one
table written for a session's make, where -12906, -12910 and -12911 are a
stream VideoToolbox will not make, and so Unsupported. It used the same table
for a picture's decode, where the guest's VideoToolbox then answered
kVTVideoDecoderUnsupportedDataFormatErr (-12910) for a decode the host's
answered kVTVideoDecoderMalfunctionErr (-12911).

A session's make keeps that table (make_error). A decode (decode_error) now
answers as the host's VideoToolbox did: -12909 bad data, -12910 a format it
does not take, and -12911, with every other status, a malfunction.

What the guest sees: a picture whose decode the host's VideoToolbox fails with
-12911 now fails with -12911 in the guest too, where it failed with -12910;
the same for -12906, which no decode is known to answer. A status outside
those three still reaches the guest as -12911, as the arm's error carries
three kinds.

Test: a_make_and_a_decode_take_videotoolboxs_statuses_each_its_own_way.
2026-12-03 06:16:31 -08:00
Anees Iqbal 2a2437e222 🐛 Give a frame's parameter sets to the next where its decode fails
A paravirtual decoder session hands the configuration's parameter sets to
the arm once, at its first decode, and dropped them where that decode failed:
the next frames came with none. On a Mac host the VideoToolbox arm makes its
session from them at the first decode, so a make that failed there, or a
first sample with no data, left every later frame of the configuration
failing with kVTVideoDecoderBadDataErr ("no parameter sets yet") until the
stream's format description changed. Tiles already got the sets back
(d3372a8d1d). Frames now do too, until one decodes, and the arm's next
decode makes its session.

The arm also kept the sets only inside its session, and took them out with
it at a change of surface, so a make that failed there lost them the same
way. It now keeps the guest's last sets apart from its session.

What the guest sees: after a first frame that failed to decode, the next
frames of the configuration decode where the host can make the session,
instead of each failing until the format changes. The NVIDIA and VA-API arms
read the sets as a sample, and get identical ones again only while no frame
of the configuration has decoded.

Tests: a_frame_that_does_not_decode_gives_its_parameter_sets_to_the_next, on
a fake arm whose first decode fails, and, ignored for a Mac host,
a_session_not_made_is_made_at_the_next_picture_from_the_kept_sets, whose make
at a change of surface a test hook (fail_makes) fails.
2026-12-03 06:16:31 -08:00
Anees Iqbal 3bb3ff94e7 🐛 Wait for a frame's issued runs before declining it to the CPU
GuestImport::run returned at once where a strip's run failed to issue
(Buffer::with_value or render_picture) after the runs into the strips above
it had gone to the driver. write_planes then declined the frame, and the arm
copied it into the guest's buffer by the CPU while those runs could still be
writing the same pages. The module doc's rule, that a frame is never declined
with a run of its in flight, did not hold on that path. Nor did it where a
wait answered an error other than a stall: run returned before the later
strips' runs were waited for.

Now a failed issue still waits for the runs issued before it, until the
frame's deadline. Done, the issue's error is the answer and the frame is
declined as before; past the deadline, the frame stalls as any late run's
does, and its import is kept. A wait's other error is the answer once every
issued run is waited for. The guest's buffer ends with the same bytes either
way, as both writers copy the same picture; the CPU's copy no longer races a
run into it.

A strip's issue moves into GuestImport::issue, which a test hook refuses at
the nth issue. The new test, ignored for a VA-API host, refuses strip 1's run
of a 4K frame imported in two strips, and checks that strip 0's run is waited
for, and done, before the decline.
2026-12-03 06:16:31 -08:00
Anees Iqbal 40c2b1abeb 🐛 Hold a VA-API encode's rate control to its profile's own config
The VA-API arm's encode entry lists a rate control where any of the codec's
configs lists it, and check() held an encode's settings to that list. Each
profile's encoder is made on its own config, which the VA crate's encoder holds
a stream to as it is made: settings of a profile whose config lacks the rate
control asked passed the op's check, and the make on the encode thread refused
them, so every frame of the session came back RGFX_VIDEO_ENCODE_FAILED.

check() now also holds the settings to their profile's own config
(profile_takes_rate), as the make does: the op is refused as it is checked, as
VideoToolbox refuses a property its encoder does not take as it is set. A rate
held to a hard limit is taken by a config that codes at a constant QP, whose QP
the VA crate's own rate control picks, as the make takes it. The caps answers
are unchanged.

The test a_rate_control_is_held_to_its_profiles_own_config holds a driver whose
H.264 High config lists CQP, CBR and VBR and whose Main lists CQP alone.
2026-12-03 06:16:31 -08:00
Anees Iqbal c9716e60f9 🐛 Upload an NVENC frame whose GPU copy the platform refuses
What the guest observes changes. Where the platform refused a command of the
NVENC fill's copy of a frame into NVENC's input (on the rt platform,
metal2vulkan-runtime's refusal, which records nothing), the frame failed: its
result read RGFX_VIDEO_ENCODE_FAILED. Now the frame is uploaded by the CPU from
the source's host bytes, as a frame whose copy the fill declines is, and is
encoded: its result reads RGFX_VIDEO_ENCODE_OK with its access unit, as the
VA-API arm's frame does, whose fill declines such a refusal to the upload.

265f8bc27f made the refusal fail the frame so that NVENC is never handed an
input nobody wrote; that still holds, since nothing of the refused copy is
submitted or handed to NVENC, and the upload writes NVENC's own input buffer.
A plane in a device cache is staged by the session's own GPU copy first, which
fails the frame where the platform refuses it too. The session's first refusal
is still said at WARN, now that the frame is uploaded, and its end line counts
the frames uploaded this way; the session's next frames are copied as before.

The test a_frame_whose_copy_the_platform_refuses_is_uploaded_on_rt (ignored: an
NVIDIA GPU on rt) refuses the first frame's copy in the platform's stead
(Filler::refuse_copies, a test field) and holds every frame OK, the refused one
uploaded and the rest copied by the GPU. copy_frame's own test, which holds the
refused copy unsubmitted, now says the frame is uploaded.
2026-12-03 06:16:31 -08:00
Anees Iqbal ccf3e286e4 🐛 Make an encoder that was not made again at the next frame
An encode session's settings come with its first encode, and again only when
they change. Both arms make the encoder for new settings on the encode thread,
dropping the old one first; where the make failed, the backend kept no encoder
and its old settings, and each later frame, which carried none, failed "an
encode with no settings" until the guest changed its settings, which it has no
reason to do. A refusal that passes, NVENC's sessions taken by other encodes on
the host among them, failed the session for good, while the guest had been told
at the op that the settings were taken.

Each arm's State now keeps settings whose encoder was not made (unmade), and a
frame that carries none makes it again, until one is made: the refusal fails
the frames up to its end alone, and the first frame of the new encoder is its
keyframe with its parameter sets, as any new encoder's.

The tests an_encoder_not_made_is_made_again_at_the_next_frame (ignored: an
NVIDIA GPU, and a VA-API GPU) fail the first make before it reaches the
hardware (State::fail_makes, a test field), and hold the next frame encoded as
a keyframe and the one after it encoded.
2026-12-03 06:16:31 -08:00
Anees Iqbal 627a502773 🐎 Refuse a frame NVENC cannot code in place before its copy
An x86 guest's NVENC session with the GPU fill copied a frame asked in place
of the last one into NVENC's input, and then handed it to
encode_device_in_place, which refuses a frame that cannot be coded in place at
all: none to replace, another frame_index than the last, or an IDR picture in
place of one that is not. Fills::encode_filled took that refusal as NVENC's
read of the GPU's copy failing: it turned the fill off for the session, and
the frame went to the CPU's upload, which refused it again, as the refusal
had dropped the last frame. The frame failed either way, but every later
frame of the session was uploaded by the CPU, and the log blamed the copy.

The NVIDIA crate now gives the in-place check its own call,
NvencEncoder::check_in_place, which refuses as encode_in_place does, and
NvencFrame::encode_into makes it after the settings and before any copy: a
frame refused in place fails before it is copied, and the session's frames go
on reaching NVENC by the GPU's copy. The guest's results are unchanged: the
refused frame fails as before, and the frames after it are coded the same.

The test a_frame_refused_in_place_leaves_the_gpu_fill_on_rt (ignored: an
NVIDIA GPU on rt) refuses a frame in place between filled frames and holds the
filler on with every other frame written by the GPU.
2026-12-03 06:16:31 -08:00
Anees Iqbal 554a5b1a7d 🐛 Count a landing failure the guest was never told of
A picture that does not land after its command buffer completed at its
decode (the VA-API arm's video processing into caches, and on Windows its
draw) fails the session's next decode in its stead. Where it was the
session's last decode, a one-picture session's among them, the failure was
carried into nothing: the guest, told that the picture landed, was never
told otherwise, while the warn line said the next decode fails and
CARRIED_CODE counted it as carried.

CARRIED_CODE now counts a failure as the next decode takes it, and the
session's end counts and logs one no decode took, video-landing-failure-
untold, so a report shows that the guest got a picture that did not land.
The guest-visible answers are unchanged: with no command buffer left there
is nothing to fail. The fake-platform test lands a failure after the
completion at a session's last decode and ends the session.
2026-12-03 06:16:31 -08:00
Anees Iqbal ea93190daa 📝 Say that a cache copy with no blit encoder fails its picture [ci skip]
The host video module's docs said a copy into an output's device caches that
the platform makes no blit encoder for is skipped, the picture landing with
the caches as they were and not counted as a failure. The code fails such a
landing and counts it as unmade (Stage::copy_with_caches, whose own docs say
so, and the test a_copy_into_caches_the_platform_makes_no_blit_encoder_for_
fails_the_landing): the skip was taken out after the docs were written. The
module docs now say what the code does.
2026-12-03 06:16:31 -08:00
charlysound ee32e02bc3 Record the verified merge against current master
Keep the exact tested source tree from 8db19df39 and both published parent histories. Master is the first parent so the PR merge base can be refreshed without rebasing or force pushing.
2026-12-03 15:16:07 +01:00
Anees Iqbal 0fc8734741 🐛 Bound a CPU lock's wait on a raised hold word at 1 s in all
A read-write CPU lock of a cached surface waits while the block's hold word
is raised, 1 ms a sleep, ending only once the word is lowered, the thread is
aborted or the device stops. The word lies in the block's header, which each
process holding the surface maps writable: a process that stored RAISED there
held every other holder's read-write locks of the surface, WindowServer's
among them, for as long as it kept the word up. A Mac's locks wait for no
other process.

A lock now waits 1 s in all at most, then goes on with the word raised,
logging the boot's first such lock and counting each. Guests' walks measured
host spans of up to 63.9 ms on an Iris Xe (m3-max-83207) and 33.0 ms on a
UHD 630 (m3-max-83316), while the make shares its batch with the guest's
command buffers: the bound is about 15 times that. What the guest sees: a
lock on a word held up past 1 s goes on; a real span over 1 s, possible only
while rt shares its batch with a guest command buffer of over 1 s, could lose
that lock's write. The native test holds the bound and a span inside it.
Both kext sets are built again.
2026-12-03 06:05:46 -08:00
Anees Iqbal 3009883f65 🐛 Post an answered texture create as an ask its close waits for
The kext admits kRgfxSubmitAnswered for a texture over a pages buffer and
waits for its COMPLETE with no deadline. The host answers such a create only
while the buffer it names is the context's (answers_create). A Submit read
the context open under the list lock and posted after, and releaseContext,
which waits for the context's asks but not for Submits, could post the
context's CONTEXT_CLOSE in between. The create then reached the host after
the close, found no buffer, and was never answered: the creating thread
waited until its process ended.

An answered Submit is now an ask (rgfxSubmitOpen): begun only while the
context is open and its close has not begun, and ended once its wait ended,
so the close waits for its answer and its create goes before the
CONTEXT_CLOSE. The host answers it while the context is open, so the wait
ends. Other Submits read the context as before. The native test stages a
close arriving while an answered Submit sits between its read and its post.
What the guest sees: no answered create hangs at a close. Both kext sets are
built again.
2026-12-03 06:05:46 -08:00
Anees Iqbal 7adbf0d834 🐛 Build the register barrier for the CPU the code runs on
`make -C guest test` stopped building on an x86-64 Mac at 2dfdbe1df5: the
native tests of the arm64e kext's values (arm64_region_test and its peers,
built with RGFX_GUEST_ARM64=1) include RgfxRegionMapping.hpp, whose register
write barrier issued `__builtin_arm_dmb` wherever RGFX_GUEST_ARM64 was set,
and an x86-64 host's compiler has no DMB (measured: m3-max-83470 on the
2019 MacBook Pro). The barrier now takes the CPU's own test, __aarch64__, as
the register accesses beside it do: the arm64e kext, built for arm64, keeps
its DMB, and the x86-64 kext and the native tests take none. Neither kext's
binary changes; both sets are recorded again for the source.
2026-12-03 06:05:46 -08:00
charlysound 8db19df396 Pin mesh bridge and lockfile to verified runtime snapshots
Use the public 9dd319e8f runtime in all three dependencies, including devtools. Its library sources match the tested ae1ea9f19; later commits refresh generated validation data and two device-gated test arrays. The final pinned Vulkan crate compiles on Linux. The preceding full xtask check passed all lints, Windows clippy, headers, prebuilts and doctests, with 3295 of 3298 tests passing: the same three private-CPU-ICD failures recorded before mesh.
2026-12-03 14:04:40 +01:00
Anees Iqbal 9497aa621d 🐎 Take a kept NVDEC decoder for a smaller 4:2:0 picture size
A kept NVDEC decoder now serves a new decoder of its codec, chroma format
and bit depth whose size is no larger on either side, with surfaces
enough, for 4:2:0 at 8 and 10 bits; other formats take a kept decoder of
their own size alone, as before (docs/video/bugs.md, D32). One of the
asked size is taken first, then the smallest larger one, so a larger one
stays for a larger stream. A taken decoder is reconfigured to the asked
size before its first decode where it was last set to another, and its
pictures decode into its larger surfaces at that size. Where that
reconfiguration fails, the kept decoder is destroyed and one is made.

What changes for the guest: a first video session of a new, smaller size,
after a larger session of its codec, format and depth whose decoder has
surfaces enough, no longer pays cuvidCreateDecoder, 43.3 ms of a 400x258
HEVC session's first decode call on an RTX 3090 (m3-max-83275). A kept
1920x1088 decoder taken for 400x264, its reconfiguration included, took
0.08-0.09 ms, against 18-25 ms for one made in the same process
(m3-max-83382). The pictures are the same: the hardware tests decode
H.264, HEVC Main and Main 10 streams of NVENC's, VP9 profile 0 and 2 and
the size-changing VP9 stream, and AV1 Main streams on a kept larger
decoder, each against its own MD5s (m3-max-83425). Left at the larger size
and reconfigured only to map, a 400x258 H.264 stream read back other
pictures (m3-max-83368), hence the reconfiguration at the take.

It does not reach the x86-64 macOS 26.7.2 guest's Quick Look thumbnail of
that 400x258 movie: its first session asks for 8 surfaces, and the one
larger decoder of its format kept by then, the wallpaper's 1024x1024 HEVC
at 8 bits, has 5 (m3-max-83451).
2026-12-03 04:56:42 -08:00
charlysound 380c6f487c Merge current master and align the native mesh bridge
Retain upstream indexed patch support and typed errors while wiring object and mesh commands to the finalized runtime API. Pin both runtime crates and test tooling to the same public fork commit. The merged workspace compiles with all targets; the sole stale import found by the initial check is removed.
2026-12-03 13:38:58 +01:00
Anees Iqbal 64fa79edf5 🐛 Never destroy the bundle's statics as its process exits
A static or global object with a destructor is destroyed as the process exits,
while the app's other threads may still run the bundle's code: a command
buffer's completion, a decode, a log line. A thread that then took one of the
bundle's static locks would end the process with "mutex lock failed: Invalid
argument" as the app quit, so a guest app could abort at quit, with a crash
report. No run has shown it. A review after the shell_tests race found 42 such
objects in guest/bundle/src: locks, a condition variable, sets, strings, class
tables, a shared pointer, and the video driver's session and driver lists. None
has a destructor whose work the exit needs (a flush, a file's close).

Each is now never destroyed (static T &x = *new T(), as RgfxLibraryStream's
lock already was). A guest sees nothing new while it runs; at its exit the
bundle frees none of them, and a thread still in the bundle finds them whole.
tests/bundle_exit_check.sh, first in the bundle's make test, fails where the
bundle imports ___cxa_atexit, which the compiler calls to register a destructor
at exit, and names the objects that do: on the tree before this commit it fails
for x86_64 and arm64, naming 30 objects. The bundle is the guest's only
user-space code; the kexts do not exit. Both guest kext sets are rebuilt
(RgfxGate carries the bundle), and docs/lessons.md has the trap.
2026-12-03 04:15:27 -08:00
Anees Iqbal 019b98b4c0 ✅ Keep the protocol tests' queue fixtures past the test
A test's command queue can outlive the test: the block that runs a command
buffer's record on the queue's completion queue holds the queue until it
returns, and the test's wait wakes inside the record. The test can then return
and free its stack serializer, rings and region, and the queue's end, on the
completion queue's thread, posts its barrier fences' destroys through the freed
serializer. shell_tests aborted with "mutex lock failed: Invalid argument"
once in 30 runs on the M3 Max beside a CPU load, right after
test_commit_behind_an_untaken_write_fails.

protocol_tests' QueueFixture and its four tests that build their fixtures by
hand now never free what a queue borrows, as queue_tests' and shell_tests'
fixtures already did and as the guest's device never frees its serializer. The
bundle's code is unchanged: a guest's queues borrow the device's serializer,
which lives as long as the process. The trap goes in docs/lessons.md.
2026-12-03 04:15:27 -08:00
Anees Iqbal ea22709fc1 ✅ Leave a newer release's base members unchecked on an older Mac
With macOS 27's members added on the 2019 MacBook's 26.7.1, the register check
still failed 11 times (m3-max-83151): members of MTLDeviceSPI that 27's Metal
carries and the register lists 'base', answered by the device's IOGPU base on
27, which 26's base does not carry, so no class answered them there.

A member RELEASES adds for releases all newer than the Mac's is now not checked
against the Mac's base when the register lists it 'base': that base, of an
older release, cannot carry it. The run prints how many it left unchecked. On a
Mac of the release that carries the member (the M3, macOS 27) the check is as
before, and a class of ours answering such a member still fails. Nothing the
guest sees changes.
2026-12-03 04:15:26 -08:00
Anees Iqbal 376421b624 ✅ Let the protocol register stand on a Mac of macOS 26
The register of the bundle's protocol members is made on macOS 27, and its
check failed 35 times on the 2019 MacBook's macOS 26.7.1 (m3-max-82661 on
development, m3-max-82842 on placefix): 21 register lines name members only
macOS 27's Metal carries, which no class of ours has on 26, and 14
releases lines name members 26 carries and 27 lacks, which the check told to
drop because that Mac's protocol has them.

protocol_members_releases.txt now lists the members of our classes' protocols
that macOS 27.0.1's Metal carries and 26.7.1's lacks, under 27.0.1 (protocol
dumps on the M3 and the 2019 MacBook, m3-max-83120 and m3-max-83119), so on a
Mac of 26 the check adds them to our classes as it adds an older release's.
A releases line whose member the Mac's protocol has now fails only where the
Mac runs none of the line's releases (by major version): on a Mac of a release
the line names, the member is walked already. Nothing the guest sees changes.
2026-12-03 04:15:26 -08:00
Anees Iqbal a26d61a3bd 🆕 Count rt's precision notes at each make, the first logged
metal2vulkan-runtime records where what it makes can answer otherwise than
Metal on the host's GPU, its precision notes, fixed at the make and never
decided at a draw, and pin R gives each a stable degrade code. Nothing here
read them, so a boot's log said nothing of them.

The rt platform now reads them right after each make that succeeds: compute
and render pipeline states, sampler and depth-stencil states, textures (views
among them) and a render encoder's pass. Each note is counted under rt's own
code, metal2vulkan-degrade-<note>, kept as rt names it so the counts line
matches rt's catalogue, and the process's first of each code writes one line
on stderr. The process holds one rt device, so that is once per device.

What the host's log shows: for each code, once,

  reims-vgpu: <call>: metal2vulkan-runtime made it with a precision note
  (<code>): its answers there can differ from Metal's on this device; the
  first of its kind, each make that carries it counted

and, on the degradation counts line, each code with how many makes carried
it. Nothing is read or counted at a draw, a dispatch or a blit, rt's notes of
commands are not counted, and there is no setting. The tests show one first
line per code, counts that run, and draws and dispatches under noted states
counting nothing.
2026-12-03 03:52:44 -08:00
Anees Iqbal cafeccd534 ✅ Clear the view settings for each test that reads them
Two settings of the process decide how views of guest pages reach a device:
IMPORTS_NEED_FILES, set at rt's first refusal of a view's one dma-buf, and
SEVERAL_DMA_BUFS_REFUSED, set where the device binds no several dma-bufs. Each
is set once and for good. nextest runs each test in a process of its own, where
both start clear, but in one process the tests before a test leave them set.

Run in one process (rt_platform::buffer's 35 tests, --test-threads 1, on the
Iris, potluck job m3-max-82981), views_past_one_dma_buf_are_mapped_from_files_
where_none_several_bind_on_vulkan failed at its check that no view is mapped
from its files: views_after_one_refused_through_dma_bufs_... and imports_whose_
dma_buf_and_pointer_rt_refuses_count_so_on_vulkan, run before it, had set
IMPORTS_NEED_FILES. Alone it passed (m3-max-82988). Other tests that branch on
the settings (views_of_two_runs_on_vulkan, views_past_one_dma_buf_on_vulkan,
views_whose_dma_buf_went_nowhere_count_why_on_vulkan, and os::linux's vm and
device_lend tests) passed there, on what the tests before them left set.

A test that reads or sets the settings now holds os::FreshImports first: both
cleared, as a process starts them, set back as they were when it ends, one such
test at a time across the process's threads. No code outside the tests changes.
2026-12-03 03:52:43 -08:00
Anees Iqbal d79900d2ba 🐛 Correctness fix: a staged copy lands nothing over a shape in place
A shape in place over a surface's pages is an image over the pages themselves:
a write through it lands in the pages, and so do the copies into it (rule 1's,
a texture over the buffer's). A staged copy into the pages (a download's, a
release's, a synchronize's) moves its bytes in two steps: the GPU copies the
cache into staging pieces, and the host's CPU copies the pieces into the pages
once that command buffer completes. Nothing orders a write through an image in
place behind the CPU's step: a later command buffer waits for the copy's GPU
step alone (OutCopy::wait, but for a copy that circulates its pieces), and a
synchronize's own buffer runs its later work before its completion. Where the
CPU's step covered a shape in place, it landed the bytes as of the copy over
that later write, which the pages then lost.

That happened wherever the copy's record held the shape's rows:
- a synchronize of a texture whose shape lies in place (its write is written
  back into the buffer, and the copy out lands it);
- a dirty shape in place (written while the buffer held bytes the pages lack);
- another shape's write that rule 1 copied into the shape in place.

The CPU's step now passes by the rows of every shape in place that owes no fill
from the buffer (SurfaceCache::past_in_place): the pages hold those bytes
already. A shape in place that owes a fill (a video write, a write unseen) still
takes the copy's bytes there, as before. For the guest: on a host whose copies
are staged (rt), a write through a texture in place over a surface, after a
download, a release or a synchronize of it, stays in the surface as a Mac keeps
it. The module doc's sentence that such a shape is never dirty is corrected.

Found by reading (audit, in-place reads R2, read from code; no run shows it).
The test synchronizes a texture whose shape lies in place after the blit that
wrote it and finds no piece's bytes landed in the pages.
2026-12-03 03:52:43 -08:00
Anees Iqbal 2bd446bc0e 🐛 Correctness fix: refuse an in-place image over a copied import
An IOSurface shape's image in place over its pages lies in the cache's import
of them, and where rt takes neither the pages' pointer nor a dma-buf of them,
that import is a copy of the pages, a Shared block of rt's own, which a command
buffer syncs with the pages only through the objects it uses that name the
copy from their make. The image for views made over it named no copy, nor did
its views or the views a move in place retargets onto it, so the command
buffers that used them synced nothing: the GPU read the copy as it was made,
missing the guest CPU's later writes, and its writes through the views never
reached the guest's pages, which the caches take for the image's own bytes and
never download (read from code; no boot log since 11-25 shows a merging copy
beside shapes in place, the M3 boots' 6 copied imports being read-only and
unchanging pages).

The make now refuses as "copied" where the buffer lies in a copy, before rt is
asked, so the shape takes an image of its own with the caches' fills and
downloads, as for any refusal. For the guest: on a host where the import of a
surface's pages falls back to a copy, textures over the surface read the CPU's
writes and their GPU writes reach the CPU. Found by reading (audit, in-place
reads R1); the test makes the image over a merging copy, its pointer refused,
and finds it refused.
2026-12-03 03:52:43 -08:00
Anees Iqbal a47b82357d ⬆️ Build on metal2vulkan development 0959445d39
metal2vulkan's development moves from aed8b7eba3 to 0959445d39, 8 commits
(SEMANTICS_VERSION 2334, RUNTIME_VERSION 2557). The translator decorates a
Converted half rounding's conversion pair NoContraction, as it did the
Controlled one, so the pair is not fused into one operation; and
PrecisionNote::code states each precision note's stable degrade code. The
rest are tests, docs (a state's precision notes are recorded at its
creation) and the blessed golden and compile-census tables.

What the guest sees change: a shader whose half rounding takes the Converted
form rounds each value as the conversion pair says, where a contracted pair
could round differently. Kernels are translated again on first use. Nothing
here reads PrecisionNote::code yet.
2026-12-03 03:52:43 -08:00
Anees Iqbal 3a535a9e1b 📝 Give the walk's span at the hold's begin bound [ci skip]
HOLD_BEGIN_BOUND's comment called 100 ms far past a make's span, from
metal2vulkan-runtime's seam tests (3.5 ms for a 1080p BGRA8 image alone). A
guest's walk on the Iris Xe (m3-max-83207) measured spans up to 63.9 ms: the
runtime's restoring make shares its batch and signal with the command buffers
going out in its submission, and waits for them too. The comment now gives the
walk's figure and that cause, and says when a wait outlives a span. No wait gave
up in the walk. Comment only.
2026-12-03 03:52:39 -08:00
Anees Iqbal 9e64d13753 🐛 Record the hold word's wire header in the ROM's record
The surface hold added the hold word to reims_graphics_wire.h, one of the
files the option ROM is built from, so the ROM's record still named the
header's old sha256 and `make -C firmware prebuilt-check` failed. `make -C
firmware prebuilt` on a Mac built the ROM again from the new header: its
bytes are unchanged (ebf34561...), and only the header's line in
ReimsGraphics.toml moves. The guest's firmware sees nothing new.
2026-12-03 03:47:57 -08:00
charlysound 787a3f744f Forward the focusing click when input capture is disabled 2026-12-03 12:29:11 +01:00
charlysound 99d612e8a3 Preserve the visible HEVC window when hardware replaces sequence headers 2026-12-03 12:25:32 +01:00
charlysound b6b884caf6 Bridge native mesh pipelines and draws through the qualified Vulkan runtime 2026-12-03 12:24:46 +01:00
Anees Iqbal 33562258cf 🎨 Count a make's span apart from the hold fence's own time
The hold's span was counted from the raise of the hold word to the point where
the fence's second call held the caches' lock, so a wait for that lock showed
as the platform's time. The span now ends as the fence's second call starts,
and the fence's own time in its two calls, its waits for the caches' lock
among it, is counted apart (rt-shape-hold-fence-ns and -most). A long span on
a walk then shows whether its time is the platform's save, move and
write-back or the fence's. Nothing the guest observes changes.
2026-12-03 03:06:48 -08:00
Anees Iqbal 3fca95c66b ✅ Pin the answered creates' pairing of bundle and host
The bundle posts a texture over a buffer to wait for the device's answer where
the buffer is the one its BUFFER_OVER_PAGES made (rgfxOverPagesItself), and
the kext waits for that answer with no deadline. The host answers a texture
over a buffer a BUFFER_OVER_PAGES made, its refusal of one among them. Were
the two rules ever to differ, the creating thread would wait for good.

The host's test checks an answer for the buffer over pages and for its
refusal, and none for a Managed buffer over it, a buffer in a heap over pages
or one over the region. The bundle's no-copy test checks rgfxOverPagesItself
for each buffer it makes over pages or falls back from. Each names the other.
2026-12-03 03:06:48 -08:00
Anees Iqbal 44e7185449 🐛 Carry a waiting lock's generation to its surface's new block
A read-write CPU lock that waits on its cached block's raised hold word finds
the block's entry again after each sleep. Where the surface's block had gone
and another had been cached meanwhile, the lock went on to wait on the new
block's word, but its CPU generation had gone into the old block's header
alone: a make in place over the new block read an unmoved generation at its
fence, and the new block's cache was never refilled with the lock's writes.
The lock now moves its generation in the new block's header, as a lock taken
there would, and fences before it reads that block's word (rgfxHoldWordNow).
A block that went holds no hold: the host answers a block's release only once
a make's span over its pages has ended, and the kext lets the block's header
go with the block, so the lock does not read it again.

The kext also reads whether it took SURFACE_HOLD once, at the first context's
open, as it reads the device's other features, rather than reading
DRIVER_FEATURES_EXT on every read-write lock of a cached surface: an exit to
the host in a VM, under the locks' state lock.

Both kext sets are rebuilt on the Mac (job m3-max-83108), for this branch's
guest changes, the placed update's and P4's. The kext's native tests pass
there, surface_hold_test's block change red without the generation's move, as
do rgfxgate's tests and the bundle's arm64 checks.
2026-12-03 03:06:34 -08:00
Anees Iqbal 029fbe1ed7 🐛 Place the bundle only on a volume that takes writes
The placement writes below the VFS, which skips its read-only check, and it
wrote into /System/Library/Caches without making that check itself, where the
BaseSystem's install makes it for /Library. Every release we keep firmlinks that
path to the Data volume, so no boot has reached a read-only place, but where the
path resolved to the sealed system volume the kext would write into it.

rgfx_place.h's steps now ask the file system whether the volume a path resolves
to takes writes (KernelPlace::writable: vfs_isrdonly of the path's mount, or of
its nearest existing ancestor's): placing on a read-only volume writes nothing
there and leaves the tree at /Library/GPUBundles, and a placed tree on one does
not move back, so the install stages nothing and the placement stays as it was.
place_test covers both over a directory whose volume answers read-only while
its writes still succeed, as the kext's do. For the guest: nothing changes on
the releases we keep; the check adds one lookup per pass.
2026-12-03 02:57:54 -08:00
Anees Iqbal 59cb1b53ff 🐛 Answer a release or re-naming of pages after a make's span
A make in place copies a cached surface's pages out and back around its image's
first layout move. A BLOCK_RELEASE of the block, or a SURFACE_PAGES that names
the block's pages again, did not wait for that span: either one's answer lets
the guest take the pages back, and the make's copy back could then write the
bytes it saved over what the guest wrote there next.

Both now wait for the span before they are answered, as a begin that uses the
block does, at most the same bound, and count as the begin's waits do. The
tests take a release and a naming of the pages inside a make's span on a thread
of their own and find each answered only after it.
2026-12-03 02:57:49 -08:00
Anees Iqbal 7a78303477 🐛 Wait out a make's span after a fill's last let-go of the lock
A begin's first fills and a present's fill read a surface's pages, and wait
for a make in place over them to end its span first, so they never read the
bytes the platform leaves undefined between its copy out and its copy back.
They waited before making the pieces their copies lack, which lets go of the
caches' lock, so a make could start its span in that gap and the fill read the
pages inside it: the cache took undefined bytes, which the guest then saw in
the surface.

The wait now runs after the last let-go before the fill, with the lock held
from there to the fill; a present's fill checks again whether it still needs
the fill after the wait. A read-only CPU lock still waits for nothing, as
known-issues.md says.

No test makes this red. The fake platform never reaches the gap in
reserve_unlocked, where the caches' lock is let go while a fill's piece is
made, so no make in place starts its span there. Three tries at a red test
passed without the fix (m3-max-83071, m3-max-83078, m3-max-83084), so the fix
is shown by reading alone.
2026-12-03 02:57:49 -08:00
Anees Iqbal 40dc87b946 🐛 Refuse a make in place over pages that lack the cache's write
A command buffer that writes a surface's device cache can end between the
host's decision to make a texture in place over the surface's pages and the
make's fence. The cache then holds a write the pages lack, and nothing kept a
download of the surface out of the make's span: the download copied the write
into the pages, and the make's copy of the bytes back undid it, while the host
held the pages as having it. The guest's lock then read the old bytes.

The fence now refuses the make as busy wherever the decision's own "behind"
rule holds at the fence: the shape takes the host's own image, and a later
begin moves it in place once the pages hold the write. A block free of that
holds no write the pages lack, so a download inside the span copies nothing.

The test runs the write's begin on a sibling decoder between the decision and
the fence, and a download inside the span, and reads the write in the pages.
2026-12-03 02:57:49 -08:00
Anees Iqbal 94ec584792 📝 Note how a fake's own copy of guest memory hides a race [ci skip]
The first red test of a CPU write lost inside a make in place passed before any
fix (job m3-max-82675): the fake platform's import of the pages was a buffer of
its own, so the make's save and write-back never reached the pages the guest's
lock wrote. docs/lessons.md now says how to spot the next such test.
2026-12-03 02:57:49 -08:00
Anees Iqbal 1ab5ed8893 🐛 Wait out a make's copy of a surface's pages in the kext and bundle
The kext takes the device's SURFACE_HOLD (DRIVER_FEATURES_EXT) where the host
offers it, and stores 0 into a cached block's hold word as it caches the block.
A read-write lock, after storing the surface's new CPU generation and a full
fence, waits while the word is raised: it sets WAITED and sleeps at most 1 ms
at a time, woken by the device's vector as the host lowers the word
(SURFACE_HOLD_LOWERED). So a locked write never lands inside the host's copy
of the pages out and back, and the host's make never misses the lock.

Where it took the hold, the kext says so in its word (bit 22,
AnsweredCreates) and admits a Submit flagged kRgfxSubmitAnswered for a texture
over a buffer. The bundle posts each texture it makes over a Shared buffer
over a process's own pages that way, and the create returns once the host
answered, so the thread's writes after it follow the host's span.

Both sets are rebuilt once, in a later commit of this branch, with the kext's
other changes. The kext's native tests, rgfxgate's and the bundle's arm64
checks passed on this change (job m3-max-82922).
2026-12-03 02:57:49 -08:00
Anees Iqbal 0b44900694 🐛 Keep guest writes out of a make's copy of a surface's pages
On a host whose GPU shares the CPU's memory, rt makes a texture in place over
a cached surface's pages by copying the bytes under it out and back around the
image's first layout move. A guest write to those bytes inside that span was
lost (the two tests of the commit before), where a Mac keeps it. The make now
runs rt's RestoreFence around the span, which keeps its writers out:

- The guest's read-write locks. A new device feature, FEATURES_EXT bit 1
  (SURFACE_HOLD), is taken in a new register, DRIVER_FEATURES_EXT (0x05c).
  Where the driver took it, the host raises a hold word in the cached block's
  header (offset 8) before the copy out, rereads the surface's CPU generation
  after a full fence, and refuses the make as "unsettled" where a lock moved
  it. A lock that finds the word raised sets WAITED and waits. The host lowers
  the word once the bytes are back and, where a lock waited, posts
  SURFACE_HOLD_LOWERED (0x413), whose vector wakes it.
- The device's own writers. The make is refused as "busy" where a command
  buffer that uses the cache is begun and not ended, or a copy into its pages
  or a fill from them is in flight. Otherwise the block is marked made, and a
  begin that uses it waits for the span's end, at most 100 ms.
- The thread that made a texture over a buffer of its own pages. Where the
  driver took the hold, the host answers each TEXTURE_FROM_BUFFER and
  LINEAR_TEXTURE_FROM_BUFFER over a BUFFER_OVER_PAGES buffer with a COMPLETE
  once carried out, so the thread's writes after its create follow the span.
  This is a device-wide rule (A), not a per-block flag (A'): on Linux, whether
  a block's make restores (its import by address, not as dma-bufs) depends on
  the views' folds at their budget and on rt's refusals, which come after the
  pages are answered, so no answer can carry it exactly. The rule only waits
  more, and its waits are counted (rt-pages-texture-creates-answered, -ns).

A driver that does not take the hold, as the kexts before this change, gets no
make that would copy the bytes out and back: it is declined as no-lock-hold,
and the shape takes the platform's own image. That is decided up front where
every import of pages lies in host memory (a Mac, Windows), and per block on
Linux once a make over the block's import ran the fence.

What the hold does not cover: a guest thread writing those bytes with no lock,
or another device's DMA, inside the span; and a read under a read-only lock
then may see other bytes. docs/known-issues.md says so, with the hosts.

The two red tests pass. New tests cover a lock ahead of the hold, a command
buffer and a copy in flight, a begin inside the span, the device's register
and event, and the answered creates. Each writer kind's tests fail with its
check switched off (job m3-max-82923).
2026-12-03 02:57:38 -08:00
Anees Iqbal 88dfdd7fb4 ✅ Show a locked write lost inside a make in place
A guest that makes a texture over a surface, then locks the surface, writes
it and unlocks it, may do so while the host still makes the texture's shape
in place over the pages: TEXTURE_FROM_IOSURFACE is not answered, so the
guest's call returns once it is posted. rt's make over host memory on a
device of one memory copies the bytes under the image out and back around
the image's first layout move, and a host write between the two copies is
lost (metal2vulkan-runtime's Buffer::new_texture docs). The guest's lock
asks the host nothing where its GPU wrote nothing of the surface since the
pages last took the cache, so nothing orders it after the make. The same
holds for a shape moved in place at a command buffer's begin. Metal touches
no byte of a surface at a texture's make, so the write must be kept.

Two tests park a fake make, which copies the bytes out and back as rt does,
inside that window and take the guest's lock there as the kext takes it
(the CPU generation moved in the block's header, the bytes written): one at
the shape's make, one at its move. Both fail today, the guest's write
replaced by the bytes the make saved (potluck job m3-max-82680); the fix
follows once its shape is ruled.
2026-12-03 02:57:38 -08:00
Anees Iqbal e447795571 🐛 Correctness fix: a copy out leaves shapes in place owing no fill
A copy out of a surface's cache through its buffer, the download a guest's
lock asks for where the cache cannot download straight, writes the buffer into
the pages, so the shapes lying in place over them hold every byte the buffer
holds. It left those shapes owing the fill from the buffer that a write
through another shape of their plane had marked, so the next use of the
surface copied the buffer over the pages again. Those are the pages' own
bytes unless the guest's CPU wrote them since: a command buffer committed
before the guest's lock, whose begin the host met after the CPU's write, put
the buffer's older bytes back over that write (read from code, not measured),
where on Metal a command buffer that only reads a surface writes none of it.

A whole copy out now marks the cache's shapes in place as holding the pages,
as a fill from the pages does. For the guest: a CPU write to a surface after a
read-back of the GPU's writes is kept, and the next use copies nothing into
the pages. A straight download, where the cache can take one, leaves the
buffer lacking the pages, so the next use took them into the buffer first;
it now copies nothing into the pages either. Found by reading (audit Z4); the
fake platform's test copies the cache out through the buffer (straight
downloads off) after a write through the plane's storage shape, and finds the
next use making no fill onto the image in place.
2026-12-03 02:33:18 -08:00
Anees Iqbal 81278e3954 🐛 Correctness fix: a move in place holds its shape's identity
A begin moves a shape in place over its surface's pages: it makes the image
with the caches' lock let go of, then re-checks that the cache still holds the
shape by its identity, the address of its tag. The move held no reference to
the tag, so where the shape went meanwhile and a new shape of the same key was
made, the new one could take the freed address. The re-check then took the
new shape for the one it moved: the views of the old shape's image moved onto
the image in place and the new shape was folded into it, while the new
shape's own textures kept viewing its own image, so their writes missed the
pages and the surface's later textures, and their reads missed the pages'
bytes.

The move now holds the shape's tag while the image is made (ShapeHold), so no
shape made meanwhile takes its identity, and the re-check also asks that the
shape found still has the image the move began from, compared by object id.
For the guest: a texture made over a surface while a begin moved another of
its shapes in place reads and writes the same texels as the surface's other
textures. Found by reading (audit Z2); the fake platform's test gives the
shape another image under the same identity while the image in place is made,
as a shape made at a reused address would stand, and finds the move raced.
2026-12-03 02:33:18 -08:00
Anees Iqbal 798dd912b7 🐛 Correctness fix: drop a make in place over pages named again
A shape's image in place over a surface's pages is made with the caches' lock
let go of, and kept once the lock is taken again where the block's cache holds
no shape of its key yet. The kext names a block again over other pages with a
SURFACE_PAGES, which may come on another thread than the texture's make: the
block then holds a new cache, and the re-check, by block and key alone, found
it holding no such shape and gave the new cache the shape and the import of
the old pages. The new surface's texture read and wrote the old surface's
pages, guest RAM no longer the new surface's, and the new cache kept that
import for its later shapes in place.

The re-check now also asks that the cache be named by the pages the image was
made over (its Unmade, held while the image is made); where the block holds a
cache named since, the image and its import are let go of, and the texture is
made unshaped, as where the block lost its cache meanwhile. For the guest: a
texture of a surface whose block was named again while the texture was made
reads and writes that surface's pages, not the ones before. Found by reading
(audit Z3); the fake platform's test names the block again over other pages
from inside the make and finds no shape and no image in place kept.
2026-12-03 02:33:18 -08:00
Anees Iqbal 3ab03545a0 🐛 Correctness fix: a widened shape keeps the fill it owes
A shape in place over a surface's pages owes a fill from the cache's buffer
once a write through another shape of its plane reaches the buffer, which then
holds bytes the pages lack. A texture made over such a shape with a usage its
image in place lacks moves it onto an image of the platform's own (a widen),
and the widen copied the image in place into the new image and promoted it as
copied, which cleared the fill the shape owed: the new image held the pages'
older bytes, and the shape's textures read texels without that write until
another write covered them, with nothing refused or counted.

A widen of a shape owing a fill now takes no copy of its image in place and
leaves the new image owing the fill, which the shape's next use makes from the
buffer. For the guest: after a write through one texture of a surface's plane,
a texture of another shape of that plane, in place and then widened by a
texture of a new usage, reads the write. Shapes lie in place on hosts of one
memory (the M3, Iris). Found by reading (audit Z1); the fake platform's test
writes through the plane's storage shape, widens its in-place shape, and finds
the next use filling the moved image from the buffer, with no copy of the
image in place.
2026-12-03 02:33:18 -08:00
Anees Iqbal 4f46e27e3b ✅ Name a slot as the kept AIR's kernel-input gap
the_air_kept_is_of_translations_and_unsupplied_draw_and_dispatch_inputs built
its kernel-input gap as KernelInputKind::PointerTranslation, the translator's
root table of addresses. metal2vulkan is deleting the translator's resident
form, after which rt makes no such gap, so the example would name a refusal no
run meets, and its variant could not go.

The test now builds KernelInputKind::Slot, an argument slot the compute encoder
does not bind, which rt produces at the pinned commit (f606e43b30,
crates/metal2vulkan-runtime/src/pipeline.rs:1925) and at pin Q's e79864f16f.
Its meaning holds: a kernel-input gap keeps its AIR, as every Gap::KernelInput
does in air_kept_of.
2026-12-03 02:33:17 -08:00
Anees Iqbal 0d42e4b589 🐛 Correctness fix: keep a video op begun before a write in place
A command buffer whose video ops name a cache's buffer readies it at its begin:
its memory made, and the pages taken where it lacks them. A write through a
shape in place over the pages, by a buffer of another queue that finishes after
that begin, marks the buffer as lacking the pages, and since the drop of a
command naming a made buffer that lacks them (2090684177), the video op met
after that finish was dropped and its command buffer failed with Metal's
internal error, where before it read the buffer as its begin left it.

The caches now keep, among a block's users, those whose video ops name its
buffer, readied at their begins; while one is begun and not finished, a
command naming the buffer reads it as that begin left it, as it reads one whose
shape not in place such a write reached, and is not dropped. That holds for a
command of another kind naming the buffer in that window too, which is no
longer dropped either; the bundle sends none, so no guest meets it. For the
guest: a video encode or decode begun before another queue's write in place
finishes completes, where its command buffer failed. Found by reading (audit
A2); the fake platform's test begins the video buffer, finishes the write, then
meets the op.
2026-12-03 02:33:17 -08:00
Anees Iqbal 50ea03ea09 🐛 Race a move in place met by a texture of a new usage
A move in place makes its image in place with the caches' lock let go of, of the
usages the textures over the shape declared, then checks again under the lock
that nothing changed before it makes each texture's view a view of the image.
The check compared the shape alone, so a texture made over it meanwhile that
declared a usage the image lacks (ShaderRead beside ShaderWrite, say) had its
view moved onto an image made without that usage: the guest's texture answered
the usage while the platform's image did not take it.

The check now also compares the shape's usages with those the image was made of:
a texture of a new usage races the move, counted as a raced move, and a later
begin moves the shape to an image of every usage asked. For the guest: such a
texture's usage is honoured after the move, where its view was of an image made
without it. Found by reading (audit A1); the fake platform's test makes the
texture during the image's make.
2026-12-03 02:33:17 -08:00
Anees Iqbal 0bcb30c6a5 📦 Rebuild both guest kext sets for the placed update's fix
RgfxGate's install now moves the placed tree back before it stages and places whichever tree is at the bundle's path afterwards, and its rename follows neither end; the sets carry dm's bundle from #53. Built on the M3 (m3-max-82860): guest/kext and guest/rgfxgate tests (place_test among them), the bundle's arm64 checks, both sets and prebuilt-check.
2026-12-03 02:32:00 -08:00
Anees Iqbal 30d1641878 📝 Record the placed update's trap in lessons.md [ci skip]
A step in front of an atomic replace removed the live tree the replace was to keep, and the rename's lookups followed a final link. Both were found in review; the lesson names place_test's red and green runs and how to spot the next one.
2026-12-03 02:32:00 -08:00
Anees Iqbal 95ca58c498 🐛 Correctness fix: keep a whole bundle through a placed update
A failed update on a placed system left no bundle at all. To write at the
bundle's path as before, the install removed the link and the placed tree,
the live bundle, before it staged; a stage or final rename that then failed
(a write error, a full Data volume) left nothing in /Library/GPUBundles or in
the placed directory, so that boot had no Metal device. Before placement the
swap always kept the old tree whole, as installBundle's comment promises.

The install now removes the link and moves the placed tree back to the
bundle's path, so the swap exchanges it whole and a failed install leaves it
there; the pass then places whichever tree is at the bundle's path, the new
one or the old. A link that cannot be removed, or a tree that cannot move
back (the link is made again), leaves the placement as it was and stages
nothing, and a link still at the bundle's path when the staged tree is to go
in stops the rename. A placement that finds no tree at the bundle's path
moves nothing, so a placed tree left by a pass that ended between the move
and the link stays for the next install to move back.

The rename looks both ends up without following a final link, as rename(2)
does: a followed link at the target handed VNOP_RENAME(X) the link's target,
a directory elsewhere, under the link's name and parent. The AppleGVA
preference's atomic write shares the rename.

The steps' order moves to rgfx_place.h, over the file system as a parameter,
and tests/place_test.cpp runs it over real directories with each step made to
fail in turn.
2026-12-03 02:32:00 -08:00
Anees Iqbal b786cede49 ⬆️ Build on metal2vulkan development aed8b7eba3
metal2vulkan's development moves from f606e43b30 to aed8b7eba3, 21 commits
(SEMANTICS_VERSION 2333, RUNTIME_VERSION 2557). Among them: a restoring make
(an in-place texture over an imported host-memory block on a unified device)
calls a caller's RestoreFence around its save, move and write-back, through
Buffer::new_texture_fenced and new_texture_in_place_fenced, and a fence that
refuses makes the make return RestoreFenceRefused with nothing saved or
written; an unknown runtime-library routine is refused as its family; a
commit looks up only the Managed buffers with a device copy its encoders
named; and a failed wake of the completion thread is owed to the next wake.
Kernels are translated again on first use. The last of the 21,
aed8b7eba3, changes only metal2vulkan's own test tables
(crates/metal2vulkan/tests/golden_hashes.tsv and the authored-compile
corpus table), which this build does not compile.

What the guest sees change: nothing in the device's answers; a kernel calling
an unknown runtime-library routine is refused under its family's name in the
host's log. The fenced makes are not called here yet: the unfenced
new_texture and new_texture_in_place are unchanged, and the next batch fences
the in-place makes of guest surfaces and buffers.
2026-12-03 01:42:50 -08:00
Anees Iqbal 26d367e16c 🐛 Correctness fix: retargeted views move on with their new image
A retarget made each view of an image a view of another, but left the views in
the first image's registry, so a later retarget of the second image moved none
of them. A shape of the surface caches moved in place (its views retargeted onto
the image over the pages) and then widened or promoted (that image retargeted
onto the platform's own) kept the textures made before the move on the image
over the pages: they read and wrote the pages while the cache and every later
texture used the new image, so two textures over one surface region showed
different pixels, with nothing refused or counted. Shapes move in place on hosts
of one memory (the M3, Iris); on the Iris the views read the image in place's
texels, not the last image's.

A retarget now moves the views into the other image's registry, with the images
they may name as the texture they view, so a retarget of that image moves them
on; a view made of the first image later is made of the last image its views
moved to and kept with those. A retarget onto an image whose views were moved,
or onto itself, is refused. The fake platform keeps the same chain: a view made
of a retargeted texture is a view of the texture its views moved to, and a
texture is retargeted once.

retarget_chain runs the same chain on both platforms, so the fake cannot pass
where the Vulkan platform fails: on the GPU, both views read the last image's
texels.
2026-12-03 01:42:42 -08:00
Anees Iqbal b9e3791c24 📦 Rebuild both guest kext sets for dd's bundle changes on placement
The bundle inside RgfxGate now answers three members of Metal's dynamic
library SPI (formattedDescription:, serializeToURL:options:error: and
shaderValidationEnabled) and logs the guest's asks of the 21 device queries
nothing has verified, on top of #52's RgfxGate that places the bundle under
/System. Both sets were built again on the M3 after dd's restack onto
a20576e1fd (m3-max-82713, `make -C guest prebuilt` and `prebuilt-arm64e`):
RgfxGate's binary changes in each, with its hash in set.toml and the changed
sources' hashes in sources.toml. prebuilt-check, the kext's and RgfxGate's
tests, and the bundle's arm64 checks pass in the same job.
2026-12-03 01:22:51 -08:00
Anees Iqbal 712cc49b36 ✅ Refuse copies rt refuses between aliases in the fake
At metal2vulkan bb09d7bb06 the Vulkan platform refuses a copy between a
texture placed in a heap and memory of the heap it shares: a region of another
texture over it, or of a texture in place over a buffer over it, and a buffer's
bytes over it either way, as Metal's validation stops them (AliasingCopy,
counted as rt-refused-metal); and a whole level into a whole level between two
placed textures, which rt orders no copy for (OverlappingCopy, rt-refused-gap).
The fake recorded them all, so a test could carry out a copy no host makes.

The fake now keeps where a placed texture lies in its heap, and where a
texture in place over a buffer lies (TextureLies), and refuses those copies
by rt's rule (texture_copy and buffer_copy): two textures, not one texture or
a texture and its view, whose memory meets where either is placed in a heap,
and a placed texture whose memory meets a copy's buffer bytes. Two textures in
place over one buffer, and memory apart or of another heap, still copy.
2026-12-03 01:22:51 -08:00
Anees Iqbal c3e5d33082 ✅ Refuse render passes rt refuses in the fake
The Vulkan platform makes no render encoder of a pass it refuses: Metal values
no enumeration has, an attachment of a texture that is no render target or of
the wrong aspect, a level, slice or plane past its texture, a resolve it cannot
do, attachments of different sample counts, and a pass with no attachment that
sets no render target width, height and default raster sample count. The fake
made an encoder of every pass, so 22 tests drew in passes with no attachment
and no size, and 18 display tests drew into a drawable that was no render
target: paths no host reaches.

The fake now answers nil for such a pass (impls::pass), its call still logged.
Tests that are not about the pass take a sized one (new_sized_pass, or the
wire's size and sample count). The display tests' drawable is a render target,
as a frame target is. The video clear tests make their passes as the surface
cache does, over the plane's image.
2026-12-03 01:22:51 -08:00
Anees Iqbal c7d23011b2 ✅ Refuse encoders and event ops rt refuses in the fake
The Vulkan platform makes no encoder of a command buffer, and records no
signal or wait of it, while one of its encoders is open or once the buffer is
committed (rt's EncoderOpen and Committed). The fake made and recorded them
all, so a test could hold two encoders of one command buffer at once, as
keyed_by_class_not_selector did.

The fake now keeps the encoder a command buffer made last, and whether it
ended (blit encoders now keep it too). Such a make answers nil and such a
signal signals nothing, each call still logged. An encoder dropped unended is
closed, as rt's ends at its drop. The faults test takes its compute encoder
from a command buffer of its own.
2026-12-03 01:22:51 -08:00
Anees Iqbal c4bc19dbe1 ✅ Answer the fake's CPU ICB encodes nil unless scripted
The Vulkan platform answers the CPU's indirectRenderCommandAtIndex: and
indirectComputeCommandAtIndex: nil, and its resetWithRange: resets nothing:
its buffers' records are Private, which no CPU encode reaches
(rt-unbuilt-icb). The fake answered a command and reset it, so 20 tests drove
CPU encodes no host carries out.

The fake now answers them as the platform does, each call still logged, unless
the script answers a value for it, as it answers copyIndirectCommandBuffer.
The decoder's record and slot tests, the rings' test and model_setters script
values, so the decoder's handling of the records stays covered; the slot test
that scripts a take's death clears its script and orders it.
2026-12-03 01:22:51 -08:00
Anees Iqbal 8e4a85c162 ✅ Refuse ICBs rt refuses in the fake, unless scripted
The fake made every indirect command buffer it was asked for. The Vulkan
platform makes one only of one draw kind alone (plain, indexed, patch or indexed
patch draws, the patch kinds where the device runs the tessellation stages),
whose commands inherit their pipeline state and bind their own buffers, of at
most 31 vertex and 31 fragment buffers, of at least one command and of no
resource index (rt_platform/icb.rs). So 45 tests and the fuzz harness made
buffers a guest never gets, and covered paths no host reaches.

The fake now answers nil for those makes, its call still logged, unless the
script answers a value for it (Fk::make_unless_refused); it answers as a device
that runs the tessellation stages. Tests that are not about the descriptor take
the platform's form (impls::icb::made_desc). The descriptor tests and the
compute buffers, which the platform refuses outright, script the make instead,
so the decoder's handling of them stays covered.
2026-12-03 01:22:51 -08:00
Anees Iqbal 0a7c92abfd 📝 Say what the device answers of samplers, tiles, dylibs [ci skip]
The oracle doc's Q9 "ours" column and Q30, and the register's %spi-no-dylibs
reason, still told what the device answered before the runtime became its
platform. Each now says what the code answers, citing it:

- maxArgumentBufferSamplerCount is 3999, the runtime's sampler indices, not 0;
- the sparse tile sizes are 0x0x0, the AMD's: the runtime has no sparse
  textures, and the device info carries no tile;
- supportsFunctionPointers is the runtime's YES, and supportsDynamicLibraries
  its NO, beside the lane's NO for supportsRaytracing;
- Q30: the device makes no dynamic library: both dylib queries answer NO, and
  a make that reaches the host answers its refusal, where the old paragraph
  said every answer was the AMD's;
- %spi-no-dylibs: the base's NO is the lane's answer, as no dynamic library
  is made, where it said the lane made a compute pipeline's.
2026-12-03 01:22:50 -08:00
Anees Iqbal dfbf17ca6e 🆕 Note the guest's asks of the 21 unverified device queries
The register lists 21 MTLDeviceSPI feature queries %spi-unverified: the M3
Max, the AMD 5300M and the Intel UHD 630 all answer YES, the device's IOGPU
base answers NO, and what each gates is not established. No walk says which
of the guest's processes ask them, so nothing ranks which to settle first.

The device now answers each as its base does and notes the ask, as the
protection-option asks are noted: the first ask of each query in a process is
logged with the process's name and the answer, and every ask is counted
(src/RgfxUnverifiedQueries.h). The queries join the device's class at the
bundle's load, each only where the base answers it with no argument and a
BOOL, with the base's type encoding, so what the device responds to and
answers is unchanged on every release. The table holds exactly the
register's 21 names; the register's lines move from base to gap, since the
device's class now answers them, and a name outside the 21 joins nothing.

Source only: both guest sets are rebuilt from this with the next set
rebuild, and make -C guest prebuilt-check fails until then.
2026-12-03 01:22:50 -08:00
Anees Iqbal 7360196a8f 🐛 Pair feature set 10002 with the read-write tier on x86
What changes for the guest: an x86-64 guest's device now answers
supportsFeatureSet: of macOS_ReadWriteTextureTier2 (10002) yes where its
readWriteTextureSupport answers tier 2, and no where it answers tier 1 or
nothing. Before, it answered the platform's no beside tier 2, the Apple M3
Max's pair, which no x86 Mac answers: the AMD Radeon Pro 5300M answers yes
with tier 2 and the Intel UHD 630 no with tier 1 (macOS 26.7.1,
oracle_caps; docs/graphics-kext/dgpu-oracle.md, Q9). An arm64 guest keeps
the M3 Max's no with tier 2.

The pair is decided where the blob is made, after the lane's tier, so the
two answers cannot drift apart. The new test pins the oracle row; the
feature-set and framebuffer-read tests change with it, since 10002 is now
the one feature set an x86-64 guest's blob answers otherwise than an arm64
guest's.
2026-12-03 01:22:50 -08:00
Anees Iqbal 863998c003 ✅ Answer the fake's tile size 0 and predication ends NO
The fake's render encoder answered a tile size of 32 and its compute
encoder's encodeEndIf, encodeEndWhile and encodeEndDoWhile answered YES, where
the Vulkan platform answers 0, as its pass has no tiles, and NO, as it builds
no command predication and so none is open (rt_platform/render.rs and
compute.rs). The fake now answers as rt does.

Nothing in the decoder reads either answer (the guest's bundle answers its own
encodeEnd* NO), so nothing changes for the guest or the host.
2026-12-03 01:22:50 -08:00
Anees Iqbal 02ab6f1e2d ✅ Refuse commands off their buffers or pass in the fake
The Vulkan platform refuses a render or compute command off the buffers it
names or off its pass, where the fake recorded it: indirect arguments at an
offset not a multiple of 4 or without their 12, 16 or 20 bytes after it;
indices off their size or past their buffer; a patch index buffer offset not a
multiple of 4; tessellation factors at an odd address; an execution past its
indirect command buffer's commands, or a range buffer offset off 4 bytes or
without 8 after it; a Boolean or Counting visibility result mode in a pass with
no visibility result buffer, off 8 bytes, past the buffer or at an offset taken
before; and a store action the pass's rendering could not have begun with
(metal2vulkan-runtime 208360ab6d, encoder.rs:1065, render_encoder.rs:1825,
:2571, :2719, :2834, :3392, :3439, :4301, :4584 and pass.rs:1232-1272).

A render encoder now keeps its pass's visibility result buffer's length, the
offsets its modes took and its attachments, and the fake refuses each,
recording nothing (impls/encoders.rs). The census found no decoder test that
relied on the old answers, and the decoder goes on past a guest's refused
command, so nothing changes for the guest or the host.
2026-12-03 01:22:50 -08:00
Anees Iqbal e96210d088 ✅ Refuse arguments rt refuses in the fake's encoders
The Vulkan platform refuses a render or compute command by its arguments
alone, where the fake recorded it: a count, an index, a base or a size past
rt's 32 bits; a value no Metal enumeration has, or a usage past sample; a list
of another length than its range, or past the runtime's 31 buffer, 128 texture
or 16 sampler slots, whose entries before them bind; what rt has not built or
keeps none of away from Metal's default; none or more than 16 viewports or
scissor rectangles and a viewport field that is not finite; an imageblock off
its rule; a compute encoder's execution of an indirect command buffer, which
holds draws alone on rt; a nil indirect buffer, or a nil resource in a
concurrent encoder's useResources:. A compute pass of a dispatch type no
MTLDispatchType is makes no encoder (rt_platform/compute.rs, render.rs and
command.rs:1690; metal2vulkan-runtime 208360ab6d, encoder.rs:38-42, :1699 and
render_encoder.rs:1592, :1955, :1975).

The fake now refuses each, recording nothing (impls/encoders.rs). The census
found no decoder test that relied on the old answers; every decoder caller of
a guest's command goes on whatever the answer, so nothing changes for the
guest or the host.
2026-12-03 01:22:50 -08:00
Anees Iqbal e336f36cee ✅ Keep encoder state in the fake and refuse as rt does
The fake's render and compute encoders recorded every command their script
did not answer nil, where the Vulkan platform refuses a command after
endEncoding, a dispatch, a draw or an execution with no pipeline state set
(or nil set since), and a buffer offset set at a slot no buffer is bound at
(rt_platform/compute.rs and render.rs; metal2vulkan-runtime 208360ab6d,
encoder.rs:768 and render_encoder.rs:1335). A test of a caller that reads the
answer could pass on the fake and fail on rt.

Each encoder now keeps an EncoderModel (impls/encoders.rs): whether it ended,
whether a pipeline state is set, and the buffer slots bound, a visible
function table's among them. A command rt refuses is answered refused,
recording nothing, and changes nothing the encoder keeps; a refused dispatch
waits for no stage fill, as rt's.

The census of the decoder's tests found two that relied on the old answer, the
fake's own: a_compute_command_the_script_answers_nil_is_refused and
a_render_command_the_script_answers_nil_is_refused dispatched and drew with no
pipeline state set. They now set one first. Every decoder caller of a guest's
render or compute command goes on whatever the answer, so nothing changes for
the guest or the host.
2026-12-03 01:22:50 -08:00
Anees Iqbal cca4d4b7e5 📝 List the 3D model previews that quit on Apple silicon guests [ci skip]
On an arm64 guest on macOS 27, Preview and Quick Look quit when they show
a 3D model: macOS draws part of the model's lighting into a texture format
that Metal lets programs write only on a GPU that reports an Apple family,
and our device reports none until it can do everything a family promises
(docs/graphics-kext/design.md, item 10). Intel Mac guests show the models.
2026-12-03 01:22:50 -08:00
Anees Iqbal 55bed1857c 📝 Say rt refuses memoryless textures, in the oracle's Q5 [ci skip]
Q5 said our stack makes memoryless textures. At pin 208360ab6d
metal2vulkan's runtime refuses one at its create (Gap::MemorylessTexture),
and the platform answers the guest nil, counted under rt-refused-gap
(rt_refused_texture_create), so the note says that.
2026-12-03 01:22:50 -08:00
Anees Iqbal 3902b5dbe1 📝 Say the lane carries Apple1's to Apple3's pieces [ci skip]
design.md item 10 still said Apple3 waited on indirect command buffers. The
lane has carried them, with a compute one's memory barriers and binary
archives, since they joined WIRED in device_info.rs, which already says it
carries Apple1's to Apple3's pieces and holds every Apple family at none
until each piece up to Apple7's is carried. The item now says the same, and
names the first pieces it lacks, Apple4's tile pipelines and imageblocks.
2026-12-03 01:22:50 -08:00
Anees Iqbal 7950466a36 ✅ Name the dynamic library descriptions before checking them
The new SPI test passed a message expression with commas to CHECK, which the
preprocessor split into several arguments, so shell_tests did not build
(m3-max-81871). The descriptions the test wants are now named first, written
out as the x86 Macs' measured text.
2026-12-03 01:22:50 -08:00
Anees Iqbal 09cc4cb1e8 🆕 Answer three dynamic library SPI members as the x86 Macs do
Both x86 Macs' dynamic libraries answer formattedDescription:,
serializeToURL:options:error: and shaderValidationEnabled, from Metal's own
_MTLDynamicLibrary, and the bundle's raised an unrecognized selector for each.
What the guest sees now, as measured on macOS 26.7.1 with the AMD 5300M and the
Intel 630 (m3-max-81849, m3-max-81863):
- formattedDescription: is the object's description, then its label, install
  name and the path of the file it was read from on lines of their own,
  indented by the indent plus 4, "<none>" for a label or path it has none of;
- serializeToURL:options:error: writes what serializeToURL:error: writes, and
  fails into a directory that is not there with the same "Invalid URL";
- shaderValidationEnabled is NO.
The register lists the three as implemented, implemented and metal; the other
12 pending members stay pending.
2026-12-03 01:22:50 -08:00
Anees Iqbal fe7cc09ff3 📝 Name what relays a gap now, not answer::relay_gap [ci skip]
Two doc comments named reims_vgpu_vulkan::answer::relay_gap as what relays a
creator's refusal, a function that no longer exists. The relay is now
note_relayed_gap's callers in rt_platform: unbuilt's refuse_create,
rt_refused_create and refused_error_as, and rt_refused_error for a pipeline's
NSError, the path a fetch pipeline's format gap takes. Neither name was an
intra-doc link, so no rustdoc check could have caught it.
2026-12-03 01:22:50 -08:00
Anees Iqbal ab29f50df8 📝 Say an arm64 guest's device answers fewer sample counts [ci skip]
The doc of sample_positions_taken said the bundle's device answers the host's
sample counts. Since lane_sample_counts, an arm64 guest's device answers the
host's counts without those an Apple silicon Mac makes no texture of (8), so
the doc says so. The bundle still sends no positions at a count the host does
not make, as the arm64 answers are a subset of the host's.
2026-12-03 01:22:50 -08:00
Anees Iqbal 174f2a4d4e 🐛 Count the placed bundle's mappings in check-boot's amfi-map
On a full system RgfxGate now places the Metal bundle's tree under
/System/Library/Caches/ai.aneesiqbal.reims-graphics and links
/Library/GPUBundles/reims-graphics.bundle to it, and Metal maps the
executable by the placed path. amfi-map counted WindowServer's mappings of
GPUBundles/reims-graphics.bundle alone, so every arm64 boot with the
placement read "maps the bundle 0 times" and failed, while
windowserver-metal and metal-app passed on the device (arm64 26.6.2 under
TCG on the 780M). It now counts mappings by either path.

The placement was checked by walks that ran no check-boot; docs/lessons.md
gains the trap, and docs/qemu.md says which paths the check reads.
2026-12-03 01:22:18 -08:00
Anees Iqbal a20576e1fd 📦 Rebuild both guest kext sets for the bundle's placement
Both sets carry the RgfxGate that places the Metal bundle under /System,
linked from /Library/GPUBundles. Built and checked on the M3 (m3-max-82673:
the kext's and RgfxGate's tests, the bundle's arm64 checks, prebuilt-check).
2026-12-03 00:55:26 -08:00
Anees Iqbal 8c6386f0b9 🐛 Place the Metal bundle under /System, linked from GPUBundles
A sandbox profile built on the system's base profile lets its process read
under /System, and /Library/GPUBundles only where it also takes the system's
graphics rules. Sandboxed processes without them were refused our bundle's
files and found no Metal device on our GPU, where on a real Mac they have
one: on arm64 the 3D-preview service, on x86 and arm64 the attributed-string
agent, and other agents.

On a full system RgfxGate now moves the installed tree to
/System/Library/Caches/ai.aneesiqbal.reims-graphics, a Data-volume directory
whose path is under /System, tags it like the bundle, and makes
/Library/GPUBundles/reims-graphics.bundle a tagged symbolic link to it, below
the MAC layer like the install's other writes. The signature pin and the
install writes take the placed directory too. An install or update removes
the link and the placed tree, writes the whole tree at the link's path as
before, and places it again; a pass that finds the link only tags it again.
Base systems keep the tree in /Library/GPUBundles.

For the guest: Metal follows the link and maps the executable by the placed
path, IOGPU trusts it there, and no process is refused a read of either path.
Walks with the placement (m3-max-82522, -82508, -82615), each on its first
boot and, on x86, again after the guest's own restart: arm64 27.0.1; x86
11.7.11, 12.7.6, 13.7.8 and 26.7.2. Every release we keep reads /System in its
base sandbox profile (read from the guests' files: arm64 13.6 to 27.0.1, x86
11.7.11 to 26.7.3). On arm64 the 3D-preview service then reaches the open of
our user client, which its profile still refuses.
2026-12-03 00:55:26 -08:00
Anees Iqbal 90214271ed 🐛 Answer an arm64 guest no for 8 samples, as Apple silicon does
An arm64 guest's supportsTextureSampleCount: answers were the host's. From pin
P the Vulkan platform can answer yes for 8 samples, so an arm64 guest would
read yes where no Apple silicon Mac does: measured on an M3 Max, macOS 27.0.1,
Metal answers yes for 1, 2 and 4 and no for 3, 5, 8, 16 and 32, and an arm64
guest's frameworks are that Mac's.

The device info now answers an arm64 guest the host's counts without those the
M3 lacks (lane_sample_counts, beside the other per-architecture answers). An
x86-64 guest still reads the host's, as the x86 Macs' AMD and Intel GPUs
answer yes for 8. The test sets the platform's answers to yes for all four
counts: x86-64 reads [1, 1, 1, 1], arm64 [1, 1, 1, 0].
2026-12-03 00:07:10 -08:00
Anees Iqbal eadc8b4a0d ⬆️ Build on metal2vulkan development f606e43b30
metal2vulkan's development moves from bb09d7bb06 to f606e43b30, 72 commits
(SEMANTICS_VERSION 2332, RUNTIME_VERSION 2557, artifact format 604). Among them:
mul24 and mad24 at 32-bit lanes are the product of their operands' low 24 bits,
so a kernel that calls them is translated where it was refused as an unknown
intrinsic; supportsTextureSampleCount: answers 8 where the device renders 8
samples into a colour, a depth and a stencil attachment; a draw that writes an
8-bit sRGB texture runs the render state's sRGB variant; a half simdgroup or
quad sum or product is Metal's tree of rounded half operations; and a texture
buffer is read through a sampler by its words where the device holds its format
as words. Kernels are translated again on first use.

What the guest sees change: supportsTextureSampleCount: answers YES for 8
where the host's device renders 8 samples into colour, depth and stencil
attachments, where it answered NO; kernels that call mul24 or mad24 are made
where the make answered nil. At this commit both guest arches pass the host's
sample counts (device_info.rs sets them for every arch), so an arm64 guest on
such a card also reads YES for 8, which an Apple silicon Mac does not answer
(measured on an M3 Max on macOS 27.0.1: YES for 1, 2 and 4, NO for 8 and 16);
the next commit restores the arm64 guest's answer to the Mac's.
2026-12-02 23:59:17 -08:00
Anees Iqbal 348bd8a2db 📝 Describe what the nonce update's match finds, in words [ci skip]
The owner chose this form for the boot policy kext's patch: its bytes stay in
firmware/ambrosia/kvm.plist, and policy_nonce.rs's module doc no longer lists
the instructions of the update's beginning. It now says in plain words what
the two state checks do, what the patch turns into a nop, and what
begins_update matches: six instructions, two byte loads, two compares and two
branches, the first branch landing eight instructions on at the proposed
nonce. Comment only; nothing the restore does changes.
2026-12-02 22:56:21 -08:00
Anees Iqbal 9147f51449 🐛 Decline a move in place whose image Metal views as no texture's
A move in place makes each guest texture over a shape a view of an image in
place over the pages, of the textures' usages together. A storage shape's own
image is made with the Unknown usage, which Metal views in any colour format
of its texel's size, so a BGRA8Unorm texture over an R32Uint storage shape is
a view of it. The image in place takes only the asked usages: without
PixelFormatView, Metal views it in its own format and its sRGB sibling alone.
The move asked rt to retarget the BGRA8Unorm view anyway, and rt refused it as
Metal does (rt-refused-metal, Iris boots 82198 and 82159, and the UHD 630's
82219), which declined the move.

The shapes now keep their textures' formats with their usages, and a move
checks each against Metal's view rules (the sRGB sibling, or any colour
format of the texel's size where the image's usage is Unknown or holds
PixelFormatView) before it asks the platform for the image, and again under
the lock before the retarget. A texture the image would not take declines the
move as retarget, counted as before, with nothing asked of rt. The guest sees
no change: the shape keeps its own image either way.
2026-12-02 22:53:50 -08:00
Anees Iqbal 7719ce6610 🐎 Import no pages for a shape whose kind of memory rt refuses
A shape's make in place on a device of one memory maps and imports the
surface's pages before rt refuses the texture over them. Where rt refuses
for a cause that comes from the descriptor and the kind of memory alone
(host-memory, dma-buf, dma-bufs, dedicated, surface, linear,
linear-features: rt's Buffer::texture_copy_cause doc, metal2vulkan
b7e1e435e3), every later make or move of that descriptor over that kind is
refused the same way, so the map and import are wasted work.

The caches now keep such a refusal by pixel format, usage, width, height
and kind of memory, at most 64, the oldest going first, where the kind is
the one every import of the pages lies in: off Linux, the pages' pointer
(host-memory). On Linux each import's way is chosen at it, so nothing is
kept there; a refusal over a copy of rt's own (own) is not kept either. A
make or move of a kept descriptor is refused before any import, counted
under its why and under rt-shape-in-place-known-refusals. Place-dependent
causes (spilled, pitch, alignment, render-reach, image-memory) are asked
every time.

Guest-visible results are unchanged: the shape takes the same path a
refusal gave it before.
2026-12-02 22:53:50 -08:00
Anees Iqbal 2090684177 🐛 Drop a command naming a made cache buffer that lacks its pages
A straight download copies a cache's dirty shapes into the pages alone and
marks the buffer as lacking them, whether its memory is made or not.
Caches::memory_of looked for a lacking buffer only where its memory was not
made, so a command that named a made one read the buffer's older bytes, not
the pages: the state every straight download now leaves.

A command that names a cache's buffer that lacks the pages, its memory made
or not, is now dropped as the unmade case was: its command buffer fails with
Metal's internal error, counted as rt-shape-lacking-named. A fill asked and
not made (a texture over the buffer, a video begin) keeps a made buffer, as
the command's buffer waits for it on the GPU.

For the guest: a command buffer naming such a buffer fails with
MTLCommandBufferErrorInternal where it read stale bytes before. The bundle
names no cache's buffer in a command, so no guest reaches it today.
2026-12-02 22:53:50 -08:00
Anees Iqbal b177728ad1 ⬆️ Build on metal2vulkan development bb09d7bb06
metal2vulkan's development moves from a6f34a7fbe to bb09d7bb06, 54 commits.
First, a fix for a crash guests met on discrete cards: a Managed buffer's
range is now taken at the first commit that names the buffer, and its first
bytes go at the next commit whatever it names (RUNTIME_VERSION 2554). Beside it:
draws and both patch kinds that a kernel encodes into an indirect command
buffer are executed (SEMANTICS_VERSION 2328); a copy between two buffers whose
bytes meet leaves memmove's bytes, and copies between a heap texture and memory
it aliases are refused as Metal refuses them, a whole level between two heap
textures excepted; a release counts as waiting until it is done; and the
texture_copy_cause doc states which causes hold for every buffer of a kind of
memory. Kernels are translated again on first use.

What the guest sees change: an indirect command buffer of plain draws alone,
of patch draws alone or of indexed patch draws alone is now made where the
make answered nil (the patch kinds where the host's executions run the
tessellation stages); a buffer of two draw kinds together still answers nil.
indirect_command_buffers_on_vulkan now makes a buffer of plain draws and takes
plain and indexed draws together as the kind rt refuses, and the icb module's
doc names the kinds made and the TessellationStages refusal.
2026-12-02 22:30:57 -08:00
Anees Iqbal ba7dcae503 🐎 Read an encode's frame from its video cache's plane images
A recording's colour conversion writes its NV12 straight into the video
cache's plane images (D31's Unix half), so at each encode the cache's buffer
lacked those writes. The encode's begin wrote both planes back into the
buffer for the encode to read: about two write-backs a recorded frame, and an
encode op that waited on the CPU for that fill on nearly every frame (1,670
of 1,678 on a 3090).

An encode whose luma and chroma textures show the planes whole now reads the
plane images where the cache answers them (Caches::encode_planes): the
surface is made, neither plane shape owes or waits for a fill, and no guest
texture over the buffer lives. Rule 1 keeps the planes current with every
shape of theirs at each encoder's end, so they hold the frame. The encode's
command buffer, of video alone, then writes nothing back first where every
write the buffer lacks is a plane's and its ops read the block by encodes
alone (Reach::named's encode flag, and a use that writes nothing). A write of
another shape is still written back first, and a deferred fill leaves the
op waiting for it and reading the buffer, as before. The buffer keeps
lacking the planes' writes until a later copy out writes them back.

The arms read the images, each frame so counted as
video-encode-fills-from-plane:
- VA-API: videoEncodeFillTexture and videoEncodeFillTextureY210 write the
  input's words as videoEncodeFill and videoEncodeFillY210 do, from R8Uint,
  RG8Uint, R16Uint or RG16Uint views of the images; the metallibs are
  rebuilt on the Mac. An rt test holds them byte for byte to the buffer
  kernels over the same rows (NV12, P010 and a Y210 repack; linear and
  Y-tiled inputs; images as wide as the frame and wider).
- NVIDIA: one copyFromTexture of each image's rows into NVENC's input at
  its pitch. NVENC's input takes no margin and no tiling: it is linear at
  the pitch, registered as NV_ENC_BUFFER_FORMAT_NV12 or YUV420_10BIT by
  NvencEncoder::encode_device, so the image's rows are all it takes.
- An upload stages each plane out of its image (Stage::copy_with_caches).

The red test now takes its encode after the buffer took the pages, as each
frame after a recording's first does: the first video op over a buffer
that lacks the pages still has it take them. Windows' encodes read the
buffer as before.
2026-12-02 22:03:36 -08:00
Anees Iqbal 01c307a678 ✅ Test that an encode over written planes writes nothing back
A recording's colour conversion writes NV12 into a video cache's plane images
through UINT views, and the encode that follows reads the cache's buffer: its
command buffer, of video alone, writes the dirty plane shapes back into the
buffer first, and the encode op waits on the CPU for that write-back (1,670 such
waits on an RTX 3090 recording boot, the video planes line). Row 5's second half
makes the encode read the plane images instead.

The test holds the begin's half: a command buffer of encodes alone over a cache
whose writes the buffer lacks are its planes' alone writes nothing back and
fills nothing, and a written storage shape beside a plane is still written back
first. It fails now on the first: the planes are written back.
2026-12-02 22:03:36 -08:00
Anees Iqbal 94b2d2c4c2 ✅ Test that rows at their pitch download as one span
A staged straight download's CPU leg moves the dirty shapes' rows from the
staging piece into the pages, and merges the rows that touch: a shape whose rows
lie at its pitch with no byte between them is one span, a single copy into the
pages, as a copy out of the buffer moves its written span. Nothing held that
merge, and a per-row copy would move the same bytes in as many calls as the
shape has rows.

The test reads the spans a straight download would move now, through a test's
accessor of the caches, Caches::straight_spans: 8 rows of 128 bytes at a pitch
of 128 are one span, and 8 rows of 128 bytes at a pitch of 256 are one span a
row, the 128 bytes between them left as the pages held them once the download
lands.

What changes for the guest: nothing; the test holds what it gets now.
2026-12-02 22:03:36 -08:00
Anees Iqbal 1f526f2506 📦 Rebuild both guest kext sets for the reworded comments
The comments of 46 set sources changed wording (the kext, bundle and
rgfxgate commits before this one), so both sets' records were stale.
make -C guest prebuilt and prebuilt-arm64e rebuilt them on the M3
(Xcode 27.2), in potluck job m3-max-82037 with the guest's arm64 pass:
every kext, bundle and Graft binary came out byte for byte as before,
and only each set's sources.toml changes, with the sources' new hashes.
prebuilt-check passes, as do the kext's and rgfxgate's tests and the
bundle's at ARCH=arm64, the members test among them (1845 members, 0
failures).
2026-12-02 21:58:12 -08:00
Anees Iqbal b41db039df 📝 Say what two more kext comments rely on [ci skip]
Two comments of the arm64 framebuffer's colour paths still named where a
layout and a call's thread were seen, a wording the first pass's sweep
missed. Each now states the behaviour with the releases it holds on, and
keeps the measurement it cited. Comments only.
2026-12-02 21:58:12 -08:00
Anees Iqbal 571adfbe61 📝 Drop the source the kvm patch's comment named [ci skip]
The comment over Ambrosia's kvm patch named where the instruction after
the patched stores was seen, which this public repository does not cite.
It now states what that instruction does, and keeps the measured count of
the patched instructions in each release. A comment of the plist only:
its Find and Replace are unchanged.
2026-12-02 21:58:12 -08:00
Anees Iqbal ac3d0a2804 📝 Say what the docs' Apple claims rest on, not how learned [ci skip]
The docs named sources for Apple's behaviour that this public repository
does not cite. A claim here cites a public header or SDK, or a probe, walk
or test of ours, or states the behaviour plainly.

Each such clause in design.md, dgpu-oracle.md, lessons.md, qemu.md and the
video docs now states the behaviour, with the release it holds on, and
keeps every measurement and boot of ours it cited; dgpu-oracle.md's one
row of that kind is marked unmeasured. testing.md's "read" tag now names
only our code, an open-source driver's, and what a public header or SDK
states.
2026-12-02 21:58:12 -08:00
Anees Iqbal 9284ef4653 📝 Say what the host crates rely on, not how it was learned [ci skip]
Four comments in the host crates and one line of reims-restore's design
named sources for Apple's behaviour that this public repository does not
cite. A comment here cites a public header, or a probe, walk or test of
ours, or states the behaviour plainly. Each now states the behaviour, with
the release it holds on, and keeps the measurements it cited. Comments and
docs only: no code changes.
2026-12-02 21:58:12 -08:00
Anees Iqbal c2ee81b6ca 📝 Say what the bundle relies on, and mark Metal's unmeasured [ci skip]
The bundle's comments and its members register named sources for Apple's
behaviour that this public repository does not cite. A comment here cites
a public header, or a probe, walk or test of ours, or states the behaviour
plainly.

Each such clause in guest/bundle's sources, tests and tools now states the
behaviour the code relies on, keeping every measurement and probe of ours
it cited. In tests/protocol_members.txt the 137 tags of that kind become
"unmeasured", which its header defines: what an entry says Metal's own
classes answer is owed to an oracle run on the 2019 or the M3, not passed
off as measured. Every kind and %name stays, and the test reads only
those. Comments and the register's text only: no code changes.
2026-12-02 21:58:12 -08:00
Anees Iqbal ffda092a7d 📝 Say what the kext relies on, not how it was learned [ci skip]
The kext's comments named sources for Apple's behaviour that this public
repository does not cite. A comment here cites a public header, or a
probe, walk or test of ours, or states the behaviour plainly.

Each such clause now states the behaviour the code relies on, with the
release it holds on where that matters, and keeps every citation of our
own tests and measurements. Comments only, in guest/kext and
guest/rgfxgate: no code changes, and no comment changes its line count.
2026-12-02 21:58:12 -08:00
Anees Iqbal bbffc2d731 📦 Rebuild both guest sets and the ROM's record for shared textures
The kext's shared texture names and the bundle's shared textures change what
both guest sets are built from, and the wire header the option ROM's record
hashes. make -C guest prebuilt and prebuilt-arm64e rebuilt both sets on the M3
(Xcode 27.2) at this tree, on top of the protection-ask diagnostic's sets, and
make -C firmware prebuilt wrote the ROM's record: the ROM's bytes are
unchanged, as the ROM reads none of what the header gained.
2026-12-02 21:51:00 -08:00
Anees Iqbal 7bfa5fb999 ✅ Point the refusal list's shared texture rows at their commit
The four rows named the bundle's shared texture commit by a hash that a
rebase replaced. They name it by its hash on this branch, 905dff6204.
2026-12-02 21:51:00 -08:00
Anees Iqbal 06f2401912 🐛 Key the shared texture tokens' device caches by an object
The export made the token's device cache with the address of a byte of the
kext's as its accelerator. IOSurfaceDeviceCache::init casts the accelerator
it is given to IORegistryEntry, a call of a virtual of it, so the cast read
a vtable from that byte and the guest's kernel panicked at the first export
of every boot: on macOS 26.7.2 (x86-64) a page fault in
OSMetaClassBase::safeMetaCast under deviceCacheForAccelerator and
exportSharedTexture, in HydraRenderingService as the image viewer opened a
3D model and in shtex_probe; on macOS 27.0.1 (arm64) the guest rebooted at
the probe's first export.

The table's caches are now known by an object of the kext's own, made with
the table and held for the kernel's life, still apart from the accelerator
the caches of CPU locks are known by. It is no registry entry, so its caches
carry no registry ID. The KPI declaration takes the accelerator as an
OSObject, so a pointer that is none no longer compiles.
2026-12-02 21:51:00 -08:00
Anees Iqbal 645c079ed4 ✅ Keep the shared texture twin open on the refusal gate's list
The planner keeps newSharedTextureWithHandle:withResourceIndex: open on
the list: it stays unsupported, as the device picks every resource id
itself, but it is not counted as settled.
2026-12-02 21:51:00 -08:00
Anees Iqbal a71f342834 🎨 Read the shared texture test's texels as clippy asks
clippy's chunks_exact_to_as_chunks refused the two-process test's
chunks_exact(4) under -D warnings; as_chunks::<4> reads the same texels.
2026-12-02 21:51:00 -08:00
Anees Iqbal 1c730298e7 🎨 Print shtex_probe's lines as each process writes them 2026-12-02 21:51:00 -08:00
Anees Iqbal 0f8426f411 ✅ Count shared textures as made in the guest's refusal gate
The bundle now makes shared textures, their handles and the textures
opened from them, so a run that logs any of the three as unsupported
again is red. The withResourceIndex: twin stays unsupported on purpose:
the device picks every resource id itself.
2026-12-02 21:51:00 -08:00
Anees Iqbal 0b19de3e09 📝 Say which device a shared texture's token names [ci skip] 2026-12-02 21:51:00 -08:00
Anees Iqbal 9825136288 🆕 Add shtex_probe: a texture drawn in one process, read in another
The guest's check of shared textures across processes: the first process
clears a shared texture and hands its handle to a second, which opens it,
checks its shape, label and texels, and clears it again for the first to
read back; a third, given only the surface's ID, opens nothing, and on the
guest's device the kext refuses its open by that ID; and a handle that
outlives its texture still opens it. It runs on the guest's device and on a
Mac's own, built by make shtex-probe.
2026-12-02 21:51:00 -08:00
Anees Iqbal 9eeb6961c6 🐛 Name the device on shared textures' tokens, under a lock of their own
Metal's handle made over a surface answers the device the surface's
creation properties name under kMetalRegistryID, and ends the process for
a surface that names none (oracle_shtex made, the 5300M); on the M3 it
answered nil, so the shell test saw no handle. Each token now names its
texture's device. The token's first ask took the texture's runtime lock,
which an app may hold (bundle_sync_check.sh): it takes a mutex of the
texture's own instead.
2026-12-02 21:51:00 -08:00
Anees Iqbal 9cc8aae874 🆕 Ask the oracle which surfaces Metal's texture handle is made over
oracle_shtex's made case makes MTLSharedTextureHandle over IOSurfaces of
our own with initWithIOSurface🏷️, each in a process of its own, and
prints what the handle answers and what NSXPC hands back of it, and the
values Metal's own handle's surface carries. The bundle's tokens follow
its answer: a surface whose creation properties name the device's
registryID under kMetalRegistryID gives a handle of that device; one that
names none, or another device's, ends the process.
2026-12-02 21:51:00 -08:00
Anees Iqbal 4614fc15d4 📝 Describe textures shared across processes and FEATURES_EXT [ci skip]
design.md says how a shared texture crosses processes: the token IOSurface
as the capability, the kext's two calls and their names, one host storage
with a view per holder, what holds the name and the storage, the bound on
names, the feature that negotiates it, and the residuals. The register
table gains FEATURES_EXT at 0x058, a guest-visible read, the selector map
gains 23 and 24, and the kext's word gains SharedTextures.
2026-12-02 21:51:00 -08:00
Anees Iqbal f200ad0eb6 🐛 Build the bundle's shared textures under clang's rules
The share link and its constant lay inside RgfxTexture's @interface, where
Objective-C++ takes no variable, and the opened texture's token was cast
from CFRetain's const answer. Both now build for x86-64, arm64 and arm64e.
2026-12-02 21:51:00 -08:00
Anees Iqbal c0a9aa89d3 🆕 Share textures across processes in the guest's Metal bundle
What changes for the guest: where the device offers shared texture names
(FEATURES_EXT) and the kext offers its calls, newSharedTextureWithDescriptor:
makes a Private texture by SHARED_TEXTURE_CREATE, newSharedTextureHandle
answers Metal's own handle over the texture's token IOSurface, which the
kext names at the first handle, and newSharedTextureWithHandle: opens the
texture the token names through the kext, with its descriptor and the
handle's label. supportsSharedTextureHandles answers YES there, as Metal's
devices do, where the IOGPU base answered NO, and a shared or opened texture
is shareable. Each was nil before, so the image viewer's 3D window stayed
white: HydraRenderingService draws into a shared texture and hands it over.

A host or kext without them, or any storage but Private, still gives nil
and posts none of the four messages; the creators take the plain create's
nil rules, as Metal's devices answer both alike (oracle_shtex). The
withResourceIndex: twin stays unsupported: the device picks every resource
id itself. The ledger row now says the platform's own shared textures stay
unbuilt and the guest's do not take them.
2026-12-02 21:51:00 -08:00
Anees Iqbal ab4fa65b2a 🐛 Answer nil for an RGBA16Float_XR texture, as the 5300M and M3 do
What changes for the guest: the device's newTextureWithDescriptor: of the
raw format 556 (RGBA16Float_XR) now answers nil and sends nothing, where it
made a texture before. The AMD 5300M answers nil for it at 1, 4 and 8
samples and the M3 Max at 1 and 4 (oracle_shtex formats); only the Intel
630 makes it. The x86 guest answers as the 5300M, its model, and the arm64
guest as the M3. Shared textures take the same rule, as Metal's devices
answer both creators alike.
2026-12-02 21:50:59 -08:00
Anees Iqbal 5ebf697dac 🆕 Add the oracle probe of textures shared across processes
oracle_shtex asks a Mac's Metal what its shared textures answer: which
descriptors newSharedTextureWithDescriptor: refuses, what a handle and the
texture opened from it answer in this process and through NSXPC, how long
the opened texture lasts after its creator goes, what views answer, and
each format's plain create against its shared one. The bundle's shared
textures cite its measurements on the M3 Max and the oracle's AMD 5300M and
Intel 630.
2026-12-02 21:50:59 -08:00
Anees Iqbal aa68ca708e ✅ Reserve the shared texture test's resource ids on rt
The rt platform grants a guest's resource ids to its runtime only where the
device reserved them, as the host reserves the guest's whole pool as its
device's first call. The two-process test now reserves the two ids its
processes place their textures at, so the views over the storage are made
there.
2026-12-02 21:50:59 -08:00
Anees Iqbal 229877c883 🆕 Name and open shared textures by a token IOSurface in the kext
A process hands its shared texture to another by Metal's handle, which
carries an IOSurface over XPC. The bundle makes that IOSurface a token of
the texture, and the kext takes the token as the capability: Export (23)
names the caller's texture device-wide by its token, once per token, and
Import (24) opens the name in the caller's context. Each looks the token
up in the caller's task first, so only a task that holds it names or
opens anything, and each posts through the caller's own client of the
context it names. SHARED_TEXTURE_NAME, IMPORT and UNNAME stay the kext's:
Submit refuses them, and admits the process's SHARED_TEXTURE_CREATE.

The name holds the host's texture while any task holds the token. The
kext watches each token through a device cache of its own accelerator
ID, apart from the caches of CPU locks: at a client's going it looks, on
a thread call and out of IOSurface's call, whether anything but the kext
still holds the token, and posts the unname once nothing does. A token
whose clients went while a port carried it is looked at again at each
later export. The table holds at most 1024 names; an export past that is
refused (kIOReturnNoResources), counted and logged.

The kext offers the two calls (kRgfxKextFeatureSharedTextures) only where
the device offers the names in FEATURES_EXT, so a host that reads 0 there
gives the bundle neither.
2026-12-02 21:50:59 -08:00
Anees Iqbal 87b1ff51e2 ✅ Hold that a guest before shared textures meets the host as before
A guest set built before FEATURES_EXT never reads it and never sends the
four shared texture messages. On a host that offers them, it reads the
same registers and takes the same features as on a host that offers
nothing there, before its start, after it and after a reset; and its
Private textures are each the one texture its create makes, with no view
or storage of the host's, and nothing held once it destroys them and
closes.
2026-12-02 21:50:59 -08:00
Anees Iqbal 3dd2306c57 ✅ Pin the shared texture records and FEATURES_EXT in the size table
The size table pins every record of the wire header and every register of
BAR 0 at the version they land in, and its tests fail on a record or a
register without a row. The five shared texture records and FEATURES_EXT,
at 0x058, where no register of an earlier version sat, land at version 3,
which they leave where it is: older guests never send the messages, and
read nothing at 0x058.
2026-12-02 21:50:59 -08:00
Anees Iqbal 50b5c58f7d 🆕 Carry out shared textures' create, name, import and unname
A process's shared texture is a view over a storage the host makes at
its own address and index, at the resource index the process picked;
another process that opens it by its name gets a view of its own over
the same storage, at its own index. Each holder's GPU work then reads
and writes the one texture with no copy, and each index stays its own
context's. Each view holds the storage until its destroy or its
context's close, and each name until the kext's unname, so a handle
another process holds opens the texture after its creator is gone.

A create of any storage mode but Private is refused, as Metal answers
nil for one. The name and import come from ring 0 on the sender's
lane, behind what its context posted before, as shared events' do; the
import is answered with the texture's descriptor. The host offers them
in FEATURES_EXT.
2026-12-02 21:50:59 -08:00
Anees Iqbal 3734e41fb9 🆕 Add the wire for textures shared across processes
A texture made shareable in one guest process is opened in another by a
device-wide name the kext mints: SHARED_TEXTURE_CREATE makes it (Private
storage only), and the kext-only NAME, IMPORT and UNNAME give a name to
it, open it in another process at that process's own object id and
resource index, and take the name back. The IMPORT's answer,
RGFX_EVT_SHARED_TEXTURE, carries the texture's descriptor, so the opener
learns what it opened.

All 64 FEATURES_LO/HI bits are spent, so a new read-only register,
FEATURES_EXT at 0x058, carries further offers. It takes nothing: the
guest reads it and uses an offer the host makes, with no write to
answer. Its first bit, RGFX_FEATURE_EXT_SHARED_TEXTURE_NAMES, offers the
four messages. A host that does not override features_ext reads 0, so a
guest finds no offer and makes no shared texture, as before.
2026-12-02 21:50:59 -08:00
Anees Iqbal d0bd099a10 🎨 Format the movable shapes' test as rustfmt does 2026-12-02 21:47:26 -08:00
Anees Iqbal 6ae98ac228 📝 Name in D30 the shape kind rt refuses in place on the M3 [ci skip]
The census's kind lines named the one kind of shape whose move in place rt
refused on the M3, as host-memory: RGBA8Unorm, 18 by 18, of usage 0x7 in all
its textures. D30 names it, so it is not found again.
2026-12-02 21:47:26 -08:00
Anees Iqbal bfdcac08eb 🐛 Bound a move in place's tries where its cache changes meanwhile
A move in place makes its image with the caches' lock let go of. Where the
cache changed meanwhile (another queue's begin made it busy, a write marked
it behind), the image was let go of and the shape stayed movable, so a
surface that two queues keep busy could make an image at each begin, about
one a frame, each with rt's restore pair; and a retarget the platform
refused was asked again the same way.

A raced move is now counted (rt-shape-moved-in-place-raced) and tried again
at a later begin at most MOVE_TRIES (3) times, then refused for good as
raced; a refused retarget is refused for good at once, counted by its why.
So a shape's image in place is made once at its make, or at its move's few
tries, never once a frame.
2026-12-02 21:47:26 -08:00
Anees Iqbal 8ad2f6c454 📝 Say in D30 where shapes lie in place and where O still copies [ci skip]
With the shapes' images in place over their pages on a device of one memory,
and a deferred surface's shapes moved there once its pages hold them, D30's
straight download is left on discrete and virtual GPUs, where rt makes no
image in place over host memory, and for the shapes rt refuses in place. The
entry now says so, with the M3 census: 3,729 straight downloads without the
images in place against 24 with them, and the restore copies each make costs.
2026-12-02 21:47:26 -08:00
Anees Iqbal a9a79b163a 🆕 Lay a surface's shapes in place over its pages on rt
rt's in-place-only make (Buffer::new_texture_in_place with no index, reached
through its views alone) is what the caches' seam asks for, so on rt a
surface's shape now lies in place over its pages wherever rt takes it there.
On a device of one memory, a shader's write through such a shape is in the
pages: a screen recorder's planes need no download or write-back.

- RtPlatform answers shapes_in_place from rt's has_unified_memory, as rt
  makes an image in place over host memory's import on such a device alone.
  On a discrete or virtual device no shape imports its pages only to be
  refused: every shape keeps the platform's own image and O's straight
  download, as before.
- shape_image_in_place calls RtObj<RtBuffer>::new_texture_in_place_for_views,
  an image for views whose guest textures are views at the guest's own
  indices, so no index the guest sees is ours. It is never bound to a slot
  itself.
- A refusal names rt's OverCause under rt's own counts' name
  (rt-shape-in-place-refused-host-memory, -pitch, -render-reach, ...), with
  no texture made and no copy counted, and the shape keeps the platform's
  own image. While the process records its calls none is asked, as the
  recording's stream holds no such make.
- rt runs the restore pair in a submission of its own inside the make and
  returns after it completes. Bytes the guest's CPU wrote before the make
  and after its return are kept; a write by another guest thread during the
  make is rt's known gap. The make never runs in a scheduled handler: only
  TEXTURE_FROM_IOSURFACE makes a shape, and a COMMAND_BUFFER's begin moves
  one, both on the decoder's thread.
- The counts line carries rt's restore copies and their bytes
  (rt-over-copies-host-memory-restore), one pair a make in place.
2026-12-02 21:47:26 -08:00
Anees Iqbal 4dd9d442e6 🎨 Name the refused moves' kind type as clippy asks
clippy -D warnings took the kinds' list type for very complex; it is a named
type now, and the kind's fields wrap as rustfmt wraps them.
2026-12-02 21:47:26 -08:00
Anees Iqbal 5e784ebca6 🆕 Log each kind of shape whose move in place the platform refuses
The M3's census counted 11 moves rt refused as host-memory, which on a device
of one memory means its external image query offers no linear image of the
shape's format and usage for host memory's handle, but the one line logged
named only the block. Each kind of refused move, its why and the image's pixel
format, size and usage, is now logged once, of the first 64 kinds, so the
census names the formats and usages rt does not lay in place.
2026-12-02 21:47:26 -08:00
Anees Iqbal 99a91104cd 📝 Link the move's retarget in its doc as the widen's doc does
rustdoc -D warnings refused the move's doc link to Texture::retarget_views,
which the module does not import by that name; it now carries the same link
definition the widen's doc carries.
2026-12-02 21:47:26 -08:00
Anees Iqbal e9db7ca883 🆕 Move a shape made before its pages in place once they hold it
The M3's census of Z showed the recorder's planes still downloaded every
frame: they are deferred surfaces, whose shapes are made at the GPU's first
write, before the CPU's first lock names their pages, so the make in place
was refused as no-pages (552 of 564 refusals), and their textures live on,
so no later make asked again.

- A deferred block named by its runs at its attach keeps them for its
  shapes' images in place, as a make by runs does.
- A shape refused in place at its make for a why of the caches' that may
  pass (layout, over-buffer, no-pages, unsettled, behind) keeps the why. At
  a command buffer's begin, beside the promotions, a cache that holds one
  moves it in place where the cache is idle, the generation settled and the
  cache holding nothing the pages lack: the image in place is made with the
  lock let go, of the usages of the textures made over the shape, its views
  are retargeted onto it with no copy, and its own image is held as a
  promoted plain image is. A guest write after the download holds the move
  until the REFILL use shows its unlock, whose fill takes the newer bytes
  first. A move the platform refuses is counted by its why and never asked
  again.
- Counted: rt-shape-moved-in-place and its bytes, move refusals by why, and
  straight downloads by the why their shape was refused in place.
- An in-place shape counts no bytes in its table, as the caches' budget
  held none for it: dropping one took bytes out of the caches' total that
  were never added.
2026-12-02 21:47:26 -08:00
Anees Iqbal ab281a7278 🐎 Ask for shapes in place only on a device that makes them
A new shape asked for an image in place wherever the platform built the
seam, so on a device that makes no image in place over the host's memory
(on rt a discrete or virtual GPU, which rt's in-place make refuses with the
host-memory cause) each new shape would map and import its surface's pages
only to be refused, and let the import go. The platform now answers per
device whether it makes such images (`ApiPlatform::shapes_in_place`), and
the device's decoder installs the seam only where it does, so a host on a
discrete GPU keeps the shapes' images as before with no import.
2026-12-02 21:47:26 -08:00
Anees Iqbal 64161c4ebd 🐛 Join the in-place shapes' log lines with line continuations
Three log lines of the in-place shapes (a shape not made in place, an
import of a block's pages refused or raised) carried a run of spaces in the
middle of their text where the literal was wrapped without a line
continuation. Each is now wrapped with a trailing backslash, as the file's
other log lines are, so the logged text reads as one sentence.
2026-12-02 21:47:26 -08:00
Anees Iqbal 64e5559a72 🎨 Format the in-place shapes as rustfmt does
rustfmt's layout of the in-place shapes' code, and the in-place make's
descriptor copied rather than cloned, as clippy's clone_on_copy asks: no change
in what the code does.
2026-12-02 21:47:26 -08:00
Anees Iqbal 0dd466890e 🆕 Make shapes' images in place over their pages behind a seam
The owner asked to remove the recorder's download copy. A surface's shape
copies its bytes between the pages and its image at the guest's events. This
change lets a shape's image lie in place over the pages instead, where the
platform makes one, so a write through it is already in the pages and no
download or write-back moves it.

- ApiPlatform::SHAPES_IN_PLACE and shape_image_in_place are the seam. It
  is one call with a typed refusal whose why the caches count
  (rt-shape-in-place-refused-<why>). By default the platform refuses as
  "unbuilt", and no platform turns it on in this commit, so nothing the
  guest or host observes changes yet. rt's make comes with metal2vulkan's
  in-place-only texture.
- A new shape asks first. Its image takes the usage the texture declares.
  The block's pages are mapped and imported at the first ask, and that
  import is let go of once no shape lies in place. The ask is skipped
  where the image would not hold all the cache holds: a dirty shape, bytes
  the buffer holds that the pages lack, video, a wide or repitched layout,
  or a texture over the buffer. It is also skipped where the surface's CPU
  generation is not settled, meaning neither 0 nor seen unlocked by a
  REFILL use (before_one records that). The make's time is counted.
- An in-place write at its command buffer's end leaves the buffer lacking
  the pages, as a straight download does. Where the buffer held bytes the
  pages lack, the shape is marked dirty instead. Fills from the pages pass
  in-place shapes by, and a recovery leaves them owing nothing.
- A texture whose usage or format the in-place image lacks moves the shape
  to an image of its kind's usage. It reuses the promotion's copy, retarget
  and ShapeTable::promote. Where the cache is in use, the texture lies over
  the buffer instead. Both cases are counted.
- O's straight download stays as the copy of the shapes not in place:
  discrete devices, and the shapes a device of one memory refuses.
2026-12-02 21:47:26 -08:00
Anees Iqbal 16530f8107 ⬆️ Build on metal2vulkan development a6f34a7fbe
metal2vulkan's development moves from 208360ab6d to a6f34a7fbe, 18 commits:
its conformance record mode reads the host's macOS release from the side, and
the runtime gains Buffer::new_texture_in_place, a texture over a buffer made in
place or answered with a typed refusal (TextureNotInPlace with its copy cause),
reached through its views alone when made without an index. A texture over host
memory's import now lies in place on an integrated or CPU device alone, with its
bytes saved and written back once inside its make, counted under a cause of its
own (Metrics::over_copies_host_memory_restore and its bytes), while
over_copies_host_memory counts the per-use copies elsewhere. The translator's
RUNTIME_VERSION is 2552, so kernels are translated again on first use.

Nothing in this tree calls the new make yet; the guest sees the same answers.
2026-12-02 21:46:33 -08:00
Anees Iqbal 543d03fa61 ✅ Classify the dynamic library's SPI by the x86 Macs' answers
The register held 19 members of MTLDynamicLibrary's SPI as pending, the x86
Macs' answer unmeasured. Measured now on macOS 26.7.1 (oracle_spi_members ask,
m3-max-81768): a dynamic library of the AMD 5300M and one of the Intel 630,
both of Metal's own _MTLDynamicLibrary, answer 15 of them from that base
class, and neither answers the 4 global constants members, though the SPI
protocol declares the two setters required. The 4 are now absent, as neither
x86 Mac's answers them; the 15 stay pending, and their reason now says what
both Macs answer and from which class. Nothing the bundle answers changes.
2026-12-02 20:46:15 -08:00
Anees Iqbal 14a22e140c ✅ Make a dynamic library in the SPI members oracle
The register lists 19 members of MTLDynamicLibrary's SPI as pending, because
oracle_spi_members made no dynamic library to ask, so what the x86 Macs' own
libraries answer was not measured. The oracle now makes one on each device that
makes dynamic libraries, from a library of one visible function with an install
name, as the guest's compute dynamic libraries are made, and walks it, or asks
it the members an ask list names, as every other kind. It says whether the
device makes dynamic libraries, and why a make failed.
2026-12-02 20:46:15 -08:00
Anees Iqbal a5918aaa43 ✅ List the dynamic library's two release-only SPI setters
macOS 26.7.1's MTLDynamicLibrarySPI carries setGlobalConstantsBase: and
setGlobalConstantsSize:, which macOS 27.0.1's lacks, so the members check on
the M3 never walked them, and on a 26.7.1 Mac it failed them as unclassified
(m3-max-81752). The releases list was dumped from the guests before a class of
ours adopted MTLDynamicLibrary, so none of that protocol's release-only members
were compared. The two are now releases lines, measured on 26.7.1 alone, as the
list's header says, and register lines of RgfxDynamicLibrary: pending, as its
getters of the same values are, since no class answers them and the x86 Macs'
answer is not measured.
2026-12-02 20:46:15 -08:00
Anees Iqbal 5acaee98ab ✅ Refuse off-grid textures over buffers in the fake
The Vulkan platform makes a texture over a buffer only 2D of one level,
sample and slice, of one colour texel a block, or a texture buffer, or
by its tiled form of more levels; with rows whole texels and at least a
row apart, from an offset of whole texels, every texel inside the buffer
(metal2vulkan-runtime texture.rs: check_over, over_texel, at pin
208360ab6d; rt_platform tiled::bad_layout). The fake made any. Its three
makes over a buffer now answer nil there, texels sized from
metal2vulkan's format tables, and still log the call.

A census of the fake's tests found three that relied on it.
creates_and_destroys_the_state_objects made a 1920x1200 texture over a
64 KiB buffer, now 64x32. a_linear_texture_is_made_by_the_platform_s_
linear_form made a linear 2D array, which rt answers nil, and is now 2D,
its routing and arguments as before. The managed 2D array test on
unified memory held a linear 2D array over its CPU copy; renamed to say
it is two copies where the platform makes no linear one, it holds rt's
answer: the linear make refused, the platform's Managed texture beside
its CPU copy, regions through replaceRegion: and a synchronize a copy.
Nothing changes for the guest: on rt the decoder already falls back so
(managed.rs). A guest told hasUnifiedMemory that reads such a texture's
GPU writes without a synchronize sees its CPU copy's old texels on rt;
that is ledgered apart.
2026-12-02 20:46:15 -08:00
Anees Iqbal 23da2c327a ✅ Refuse blits past what they name in the fake
The fake recorded every copy and fill, where the Vulkan platform's
runtime refuses one that reaches past what it names (metal2vulkan-runtime
blit.rs: buffer_to_buffer, fill_range, buffer_copy; texture.rs: place;
at pin 208360ab6d): a range past a buffer or meeting its own source, a
fill of no bytes or past its buffer, a level, slice or region outside a
texture or off its block grid, and a buffer layout whose rows, images or
bytes do not fit. The fake now refuses each, after logging the call and
answering its script, its texels sized from metal2vulkan's format tables
as rt_platform/blit.rs sizes them.

A census of the fake's tests found four tests whose blits it now refuses
(every_blit_command_drives_its_selector and three of surface_cache), each
of which reads only the call log and passes as before, and one fill of
the command-buffer fuzz. Nothing changes for the guest.
2026-12-02 20:46:15 -08:00
Anees Iqbal 40d9a7049f ✅ Refuse views past their texture's levels in the fake
The Vulkan platform's runtime refuses a texture view of an empty range of
levels or slices, or of one past the texture's (TextureViewRange,
metal2vulkan-runtime texture.rs, at pin 208360ab6d), and the fake made
any. Its four makes of a view of a range now answer nil there, a cube's
six faces each a slice and a 3D texture's one, and still log the call.

A census of the fake's tests found one such view:
a_view_is_made_by_the_selector_of_its_form made its swizzled view of
view 3, which has one slice, at slice 3, and now makes it at slice 0.
The message fuzz makes them too (7 by levels, 9 by slices) and passes
either way. Nothing changes for the guest.
2026-12-02 20:46:15 -08:00
Anees Iqbal 012a7770fb ✅ Refuse misplaced heap resources in the fake
The Vulkan platform places no resource in an automatic heap, none of a
storage or CPU cache mode other than its heap's, and no buffer off 256
bytes (rt_platform/heap.rs: misplaced, new_buffer_of_length), and the
fake placed them all. Its heap now keeps its type and a texture
descriptor whether its resource options were set, an unset one taking
the heap's as rt's does; each such make answers nil, its call still
logged.

A census of the fake's tests found no automatic heap on the guest's
path: the decoder makes a guest's Automatic heap a Placement one
(host_heap_type). The message fuzz makes 20 resources of another mode and
12 buffers off 256 bytes, and passes either way.
a_create_the_platform_refuses_makes_nothing placed a Shared texture in a
Private heap; heap_texture_create now gives it its heap's storage.
Nothing changes for the guest.
2026-12-02 20:46:15 -08:00
Anees Iqbal 65bf1b952a ✅ Refuse a heap texture off its place in the fake
The fake placed a texture in a heap at any offset, where the Vulkan
platform's runtime refuses one past the heap's end or off the alignment
its size-and-align query answers (metal2vulkan-runtime texture.rs, the
HeapTexturePlace check, at pin 208360ab6d). A fake test so saw a texture
the platform never makes. The fake now answers nil there, by its own size
and alignment (heapTextureSizeAndAlignWithDescriptor:, 16 KiB), and still
logs the call.

A census of the fake's tests found one placement off the alignment:
a_create_the_platform_refuses_makes_nothing placed its texture at 0x1000,
and now places it at 0x4000. Nothing changes for the guest: the decoder
does no arithmetic on the offset, and on rt the runtime already refused.
2026-12-02 20:46:15 -08:00
Anees Iqbal aa68fc6685 📝 Say that the guest's checks run for arm64 too on Apple silicon [ci skip]
make -C guest test now runs the bundle's checks a second time for arm64,
natively, in guest/bundle/build/arm64, on an Apple-silicon Mac, and its x86_64
checks run under Rosetta there and natively on an x86-64 Mac. The table of
checks says so in the guest row.
2026-12-02 20:31:40 -08:00
Anees Iqbal 7c3e156034 ✅ Record the two Makefiles the kext sets are built from
guest/Makefile and guest/bundle/Makefile are sources of both kext sets, and the
arm64 test pass changed them, so prebuilt-check failed. `make -C guest
prebuilt` and `make -C guest prebuilt-arm64e` built both sets again on the M3
(m3-max-81769): every kext's binary and Info.plist came out the same, and only
the two Makefiles' hashes in each record changed.
2026-12-02 20:31:40 -08:00
Anees Iqbal a0279bca64 ✅ Run the bundle's checks for arm64 too on Apple silicon
`make -C guest test` ran the bundle's checks for x86_64 alone, so an arm64
guest's bundle, with its 16 KiB pages and its own answers (residency sets, an
Apple GPU's command buffer SPI), was checked by no target, and four of its
checks had gone red unseen. On an Apple-silicon Mac the target now runs the
bundle's `make test` a second time with ARCH=arm64, natively, in a build of its
own, bundle/build/arm64, as the two arches' test binaries share their names in
build/. Other Macs run what they ran before.
2026-12-02 20:31:40 -08:00
Anees Iqbal 9c5ac74338 ✅ Size the HEVC encode test's buffer by the process's page
The HEVC encode test asked a bitstream buffer of 0x1000 bytes and wanted the
encode's capacity to be half of 0x1000, and an access unit of 0x1004 bytes to be
past the buffer. The driver rounds a pool's buffers up to the process's page
and maps each, so on arm64, whose processes have 16 KiB pages, the buffer is
0x4000 bytes and the capacity 0x2000 (m3-max-81657, `make test ARCH=arm64`):
the whole mapping is the driver's, and the access unit it publishes lies in it.
The test still asks 0x1000 bytes, and now wants half the page-rounded buffer
and takes the rounded size plus a start code as past it: 0x800 and 0x1004 on
x86_64, as before, and 0x2000 and 0x4004 on arm64.
2026-12-02 20:31:40 -08:00
Anees Iqbal 6c42e257fe ✅ Remap a page in, not 4 KiB in, in the pages join test
The pages join test mapped its memory entry again 0x1000 bytes in to show that
the same memory at another offset is not joined. On arm64, whose processes have
16 KiB pages, that map failed (m3-max-81657, `make test ARCH=arm64`), so the
test stopped before the bundle was asked anything. The map now goes a page of
the process in, vm_page_size: 0x1000 on x86_64, as before, and 0x4000 on arm64.
rgfxPagesIdentity reads each region's object, offset and length, whatever the
page size, so what the test checks of the bundle is the same on both.
2026-12-02 20:31:40 -08:00
Anees Iqbal 35181d6fcd ✅ Give the members register a line per arch where they differ
The protocol members' register listed encodeSignalEventScheduled:value: as
absent, the x86 bundle's answer, so `make test ARCH=arm64` failed on the arm64
bundle, whose command buffer answers it since de0ac7c079. A register line may
now start with "@arm64" or "@x86_64", and is then read only where the loaded
bundle (the test's own architecture) is of that architecture; an unknown
architecture or one with no member fails. The member has a line for each: absent
on x86_64, as before, and implemented on arm64, whose body the check reads as
any other. The residency reason no longer says the register's bundle is the x86
one.
2026-12-02 20:31:40 -08:00
Anees Iqbal 377d0255c4 ✅ Check the arm64 device's residency set in its base check
The base-class check held the x86 device's answer to
newResidencySetWithDescriptor:error: (nil, the error out set to nil) on every
bundle, so `make test ARCH=arm64` failed on the arm64 device, which makes a set
of its own since 864a468059. The check now wants, under the arm64 build, an
RgfxResidencySet with the error out set to nil, and under the x86_64 build nil
with the error out set to nil, as before. The member's +1 answer is taken as
retained, so the arm64 set is released.
2026-12-02 20:31:40 -08:00
Anees Iqbal 5cb4100135 🐛 Carry dropped ICB draws only through blits the platform records
A blit's copy of indirect commands moved their dropped draws (Dropped,
decode/icb.rs) onto the destination even where the platform refused the
copy, and a refused blit reset of a range still cleared its dropped
commands. The decoder now moves or clears them only where the encode
answers RECORDED. A CPU resetWithRange: is not gated: the platform's trait
gives no answer for it.

What the guest sees on the Vulkan platform is the same before and after.
rt builds no command the CPU encodes (rt-unbuilt-icb), so Dropped is never
marked there, and it refuses every copy between indirect command buffers,
so the destination keeps the commands it held. On a platform that builds
CPU encodes but refuses the copy, a destination command named by a refused
copy from a dropped one drew nothing before; it now draws what it holds.

The fake now refuses copyIndirectCommandBuffer: as rt does, recording it
only where the script answers a value, so a fake test sees rt's answer. A
census on 94e64a69c5 found three fake tests that copy an ICB, the two fuzz
targets and every_blit_command_drives_its_selector, none of which turns on
the copy's answer, and no test that scripts a blit reset nil. The fuzz
targets' counts are identical before and after.
2026-12-02 20:20:27 -08:00
Anees Iqbal b07e921a3a 📝 Name the plane lookup in the shapes doc without a link [ci skip]
ShapeTable::find_plane is built on Unix alone, so rustdoc for the Windows
target (batch cx's lint 2) found the module doc's intra-doc link to it
unresolved. The doc names it as code, saying it is Unix's.
2026-12-02 20:05:33 -08:00
Anees Iqbal 5c91a5b507 🆕 View a video plane from a texture that writes it
A recording's colour conversion writes its NV12 (or P010) through R8Uint and
RG8Uint (R16Uint and RG16Uint) textures declaring ShaderWrite. Each took the
storage shape of its plane's extent, an image of its own beside the plane, so
rule 1 copied every write into the plane (rt-shape-order-case,
rt-shape-order-copies). The red test lays its surface out as an RTX 3090
recording boot's (m3-max-81235).

On Unix hosts a video cache's surface's planes are now asked ShaderRead |
ShaderWrite | RenderTarget | PixelFormatView (0x17, was 0x15), and a texture
over a plane whole that takes storage while declaring ShaderWrite and no use
the plane's image lacks is a view of the plane (Caches::writable_plane): no
storage shape and no order copy. Such a writer asks the surface where it comes
first. ShaderAtomic and the Unknown usage keep the storage shape, and so does
every texture of an extent whose storage shape the cache holds. The platform
picks the surface's form for that usage: in place, or rt's copy form where the
device holds no linear image for it (NVIDIA's dma-buf route); the path takes
the images rt answers and assumes neither.

The Windows drawn planes keep 0x15 under their own constant, DRAWN_USAGE:
their Direct3D 11 textures are bound RENDER_TARGET | SHADER_RESOURCE, without
UNORDERED_ACCESS, and rt refuses ShaderWrite on such an import, so a texture
that writes one keeps the storage shape and its counted copies, now ledger
line D31 in docs/video/bugs.md.

What changes for the host: the planes' usage the device asks of the
platform's exported surfaces on Unix hosts. For the guest: the same pixels,
through one image where there were two.
2026-12-02 20:05:33 -08:00
Anees Iqbal 8f78333162 ✅ Count the video-plane write test's pages in u64
The red test's page count was an integer literal of no type, which div_ceil
cannot take; the rig's page is a u64.
2026-12-02 20:05:33 -08:00
Anees Iqbal 05d41f17e2 ✅ Test a write texture over a video plane as a view of the plane
A recording on an RTX 3090 (m3-max-81235) converts each frame into NV12
through ShaderWrite R8Uint and RG8Uint textures over the host's video
planes. Today each such texture takes a storage shape of its own beside the
plane, and rule 1 copies every write between the two (rt-shape-order-case,
-order-copies). This test holds the form the planes should take: asked
writable (ShaderRead | ShaderWrite | RenderTarget | PixelFormatView), a
writer over a plane whole a view of the plane's image, no image of the
decoder's own, no copy after a write, the plane dirty for the copies out; a
ShaderAtomic texture keeps the storage shape. It fails until the planes are
made so.
2026-12-02 20:05:33 -08:00
Anees Iqbal e21bfdcd05 ⬆️ Build on metal2vulkan development 208360ab6d
Pin M, twenty-five commits past pin K (dddd91b993), with no change to the
runtime's public API (tests/api_signatures.tsv is the same). For the guest:
a render pipeline takes the attachment feedback loop's colour flag at its
make only where one of its functions can read a texture (the pipeline's
flags change, no value does); a dma-buf plane's view list holds only the
formats its linear modifier samples; and a surface plane whose image in
place lacks a usage its texture asks takes the runtime's counted copy form
where the whole surface was refused before, which row 5's ShaderWrite
planes need on a device with no linear storage for their formats.
2026-12-02 20:04:18 -08:00
Anees Iqbal 9101df6ce2 📦 Rebuild both guest kext sets for the protection-ask diagnostic
The x86-64 and arm64e sets carry the Metal bundle that logs and counts the
makes asking for protection options, a diagnostic only: every make answers
as before. RgfxGate changes in both sets; ReimsGraphics and Graft are
byte-equal to the last sets'. Built by make -C guest prebuilt and
prebuilt-arm64e on the M3 at 2ac7cc3998 (m3-max-81074), where
make -C guest prebuilt-check passed.
2026-12-02 20:01:57 -08:00
Anees Iqbal ec89be620d ✅ Keep the protection-ask test's third heap to its end
test_protection_asks_are_noted_and_change_nothing let its third heap go as
soon as it was made, and a heap let go posts its release on the ring, so the
test's last check, that the ring is empty, failed on that release. The heap
is now held to the test's end, as the test's other heaps are.
2026-12-02 20:01:57 -08:00
Anees Iqbal d420d4c116 🆕 Log and count the makes that ask for protection options
A diagnostic only. A texture's or a heap's descriptor can carry protection
options, which the device does not build: a texture, a heap or a texture
over an IOSurface made with them answers exactly as one made without them,
before this change and after it. Nothing in a guest's log said which
process asks for them, at which make, or how often, so whether any of the
guest's frameworks relies on them could not be read from a boot.

Each such make now notes the ask (RgfxProtectionAsks): per process and per
kind of make, the first is logged with the options' value and the process's
name, every ask is counted, and the count is logged with the process's name
each time it reaches a power of two, so a process that asks every frame
logs a few lines, not one a frame. The command buffer's line for its own
options stays as it was. The shell test checks the counts by kind and that
a heap is made and created on the wire as one without the options.
2026-12-02 20:01:57 -08:00
Anees Iqbal ed68bb4ef7 📦 Rebuild both guest kext sets for the open encoders' ends
The x86-64 and arm64e sets carry the Metal bundle that ends the process where
Metal does with an encoder of a command buffer open (Q53: the event calls,
the commit, an encoder made with another open, an encoder let go without its
end), and the ReimsGraphics kext whose framebuffer and accelerator keep their
mappings of the device until they are freed. Built by make -C guest prebuilt
and prebuilt-arm64e on the M3 at c99522366a (m3-max-80837), where
make -C guest prebuilt-check passed.
2026-12-02 20:01:57 -08:00
Anees Iqbal 0ed439f58c 🐛 Keep the accelerator's region and registers until it is freed
A CPU lock of an IOSurface in any process (the surfaces' control function,
RgfxAcceleratorLocks.cpp) and the release worker reach the accelerator with
no client of their own, and write a block's runs through its region
(writeRuns), which can come after the accelerator's stop. The stop's
teardown released the region and the registers' mapping, so such a write
would reach a released mapping, a kernel panic.

No path in the lab was shown to run this stop while such a write is due:
kmutil refuses to unload the kext from the boot kernel collection, QEMU
refuses device_del, and a restart was not shown to reach stop(). The hole is
in the teardown the tree ships, so it is closed now rather than once a guest
meets it.

The region and the registers' mapping now go at free(), and a failed start
leaves them to it too. Nothing changes for a guest: boots, a restart and a
shutdown, on the fixes' own kext set (potluck job m3-max-80704), are
unchanged.
2026-12-02 20:01:57 -08:00
Anees Iqbal be40fe5013 🐛 Keep the framebuffer's device mappings until it is freed
The accelerator and its user clients are the framebuffer's siblings on the
PCI device, not its clients, so IOKit stops them in no set order. The
framebuffer's stop released its rings, control data, cursor slot, registers
and region while an accelerator client could still post: tryPost reads the
ready flag outside submitLock and the doorbell is rung outside it, so a post
that read it ready as the framebuffer stopped would write through a released
mapping, a kernel panic.

No path in the lab was shown to run this stop with clients alive: kmutil
refuses to unload the kext from the boot kernel collection, QEMU refuses
device_del, and a restart was not shown to reach stop(). The hole is in the
teardown the tree ships, so it is closed now rather than once a guest meets
it.

Teardown now resets the device and lets the work loop go, and the mappings
go at free() (releaseMappings), once nothing holds the framebuffer; a head's
region goes there too. Nothing changes for a guest: boots, a restart with
clients holding the device, and a shutdown, on the fixes' own kext set
(potluck job m3-max-80704), are unchanged.
2026-12-02 20:01:57 -08:00
Anees Iqbal fdd523cae2 ✅ End the tile-size test's sub-encoder before its pass
test_render_tile_size let its parallel pass's sub-encoder go without its end,
at the pass's end. Metal ends the process there (dgpu-oracle.md, Q53: the M3
at the pass's end, the x86 Macs at the sub-encoder's release), and so does the
bundle since the commit before this one, so the test ended shell_tests. The
test asks only the sub-encoder's tile size; it now ends the sub-encoder before
its pass, as a Metal app must.
2026-12-02 20:01:57 -08:00
Anees Iqbal 868ae658ba 🐛 End the process where an encoder goes without its end
Metal ends the process where a blit, compute or render encoder is let go
without its endEncoding, on the M3 Max, the AMD 5300M and the Intel 630, in
_MTLCommandEncoder's dealloc; a parallel render encoder's sub-encoder let go so
ends it at its release on the x86 Macs and at the parallel encoder's end on
the M3 (dgpu-oracle.md, Q53). The bundle's encoders let go silently, and the
buffer went to the host with the encoder open at its commit.

Each encoder now ends the process in its dealloc where its command buffer's
hold, which only its end lets go, is still there, with Metal's words, before
anything reaches the host. A sub-encoder is held by its parallel encoder to
that encoder's end, so one let go without its end ends the process there, as
on the M3. What changes for the guest: such a process ends as the encoder
goes, as on a Mac, where it used to go on until its commit.
2026-12-02 20:01:57 -08:00
Anees Iqbal 1c90b78fb3 🐛 End the process at an encoder made with another open
The M3 Max and the Intel 630 end the process where a command buffer makes an
encoder while one of its encoders is open, a blit in a blit and a compute in a
render encoder measured; the AMD 5300M makes it, and fails the buffer of a
compute encoder made in a render encoder (dgpu-oracle.md, Q53). The bundle
began the second encoder inside the first, so the buffer's stream went to the
host with nested encoders, which it faulted.

Every encoder maker now ends the process there, before the buffer's stream
reaches the host, in the M3's words on every guest: the M3 is the
latest-macOS target, and no guest is given the AMD's second encoder (the
planner's ruling, 12-02). What changes for the guest: such a process ends as
the encoder is made, as on the M3 and the Intel 630, where its buffer used to
reach the host and fault.
2026-12-02 20:01:57 -08:00
Anees Iqbal 47e5f26fb0 🐛 End the process at a commit with an encoder open
Metal ends the process at a commit made with an encoder of the buffer open,
on the M3 Max, the AMD 5300M and the Intel 630, for a blit, compute, render or
parallel render encoder, and at the commit after a parallel render encoder
let go without its end (dgpu-oracle.md, Q53). The bundle posted the buffer,
whose stream then ended with the encoder open, which the host faulted.

The commit now ends the process there with Metal's words, the M3's on a
device that answers as an Apple GPU and the x86 Macs' otherwise, before the
buffer is posted. What changes for the guest: such a process ends at the
commit, as on a Mac, where its buffer used to reach the host and fault.
2026-12-02 20:01:57 -08:00
Anees Iqbal 1008f10458 🐛 End the process at an event call with an encoder open
Metal ends the process at encodeSignalEvent:value: and encodeWaitForEvent:value:
called with an encoder of the buffer open, on the M3 Max, the AMD 5300M and the
Intel 630, for a blit, compute, render or parallel render encoder and a shared
or a plain event, and the M3 at encodeSignalEventScheduled:value: too
(dgpu-oracle.md, Q53). The bundle kept no record of an open encoder, so the
call wrote its event op inside the encoder and the buffer's stream went to the
host, which faulted it as malformed.

The encoder stream now records whether an encoder is open (a begin op to its
end), and the three calls end the process there with Metal's words, the M3's
on a device that answers as an Apple GPU and the x86 Macs' otherwise, before
anything reaches the host. What changes for the guest: such a process ends at
the call, as on a Mac, where its buffer used to reach the host and fault. The
test's death cases fail where the submission ring holds anything.
2026-12-02 20:01:57 -08:00
Anees Iqbal 9d7ee77db0 🆕 Add oracle_cmdbuf's open-encoder cases and Q53
Metal ends the process at some command-buffer calls made with an encoder of
the buffer open, while the bundle keeps no record of an open encoder and sends
the buffer's stream to the host, which faults it as malformed. The probe asks
each GPU what Metal does with an encoder open at the event calls (a shared
event and a plain one, with a blit, compute, render and parallel render
encoder), at encodeSignalEventScheduled:value:, at the commit, at a second
encoder made, at an encoder let go without its end (a parallel encoder's
sub-encoder among them), and at the calls that pass (enqueue, the handlers, a
debug group). Q53 records its answers on the AMD 5300M, the Intel 630 and the
M3 Max, which the four commits after this one follow.
2026-12-02 20:01:57 -08:00
Anees Iqbal 94e64a69c5 ✅ Script an answer behind an owed CB_SCHEDULED
The doorbell fuzz target failed where no buffer of its cases was answered
behind one of its queue that owed its CB_SCHEDULED. It answered about 3.4 such
buffers a run of its default 256 cases, so the guard rested on chance. Under
RGFX_FUZZ_SEED 1 to 300, 11 runs answered none (m3-max-81328).

Ahead of its drawn cases, the target now runs one scripted case, at any seed,
in both of its runs. Two buffers of queue 1 are each an empty blit pass. The
first asks for no CB_SUBMITTED, so its CB_SCHEDULED waits for the platform's
take, which the platform holds from its commit. The second asks, and is
offered to the answer while the first owes its record. The target fails
unless the second buffer is answered behind the owed record and the answer
offers no CB_SCHEDULED of its own. Both runs must give the platform the same
calls and the guest the same records. The case counts among the answers
behind an owed record, so that guard holds at any seed.

Tests (homelab-um870-1, fake platform; counts measured):
- m3-max-81535: cargo fmt and clippy (host and Windows) are clean. The 999
  tests of graphics::decode and graphics::tests pass, and so do the fuzz's six
  targets.
- The doorbell target's answers line is the parent's, with 3 answers behind
  an owed record in place of 2. The other targets' counts are the same.
- The scripted case alone passes under RGFX_FUZZ_SEED 0 to 20.
- Red: with the answer's owed check removed, the scripted case fails, its
  CB_SCHEDULED records out of order for the guest (37 before 36).
- Red: without the platform's hold, the scripted case fails, the line owing
  nothing at the second buffer's offer.
- m3-max-81543: under RGFX_FUZZ_SEED 1 to 300 the target passes at every
  seed, each with 1 or more answers behind an owed record. At each seed but
  72, its answers line is m3-max-81328's with one more such answer. Seed 72
  ended in a panic there, in a heap's buffer, which an earlier commit fixes.
2026-12-02 19:53:04 -08:00
Anees Iqbal 80169b88e7 🐛 Refuse a buffer past its heap in the fake; sum its offset checked
The fake platform's heap made a buffer at any offset, over no memory where it
did not fit. The Vulkan platform refuses a buffer whose offset and length
pass its heap's end (rt_platform/heap.rs, misplaced). The decoder's
BUFFER_AT_OFFSET then summed the guest's offset with where the heap's block
lies in the region (decode/mod.rs), which overflowed for an offset near
u64::MAX and ended a debug build's test. The message fuzz target ended this
way under 11 of RGFX_FUZZ_SEED 1 to 300, and the doorbell target under 1
(m3-max-81328). The default seed reaches none of them.

The fake heap now refuses such a buffer (nil), as the Vulkan platform does.
The decoder sums the offset checked and refuses the message where it
overflows: it takes the guest's number, and does not lean on the platform's
refusal coming first. On the Vulkan platform that refusal does come first, so
nothing changes for the guest.

Census (m3-max-81504, homelab-um870-1): with the old fake marked, the tests
of graphics::decode and graphics::tests (999) made a buffer past its heap
only in the message fuzz target, 7 times at its default seed. Those messages
are now refused, not carried out. Since the target mutates later messages
from those it carried out, its later inputs change from there: under
RGFX_FUZZ_SEED 1 to 300, the BUFFER_AT_OFFSETs carried out fell by 3,097
across the 278 seeds that had completed before, and the other types' counts
moved a little.

Tests (homelab-um870-1, fake platform; counts measured):
- m3-max-81535: the 999 tests of graphics::decode and graphics::tests pass.
- m3-max-81543: under RGFX_FUZZ_SEED 1 to 300 the message and doorbell targets
  pass at every seed, with no panic (seed 72 of the doorbell target among
  them).
2026-12-02 19:53:04 -08:00
Anees Iqbal f823ffbd53 ✅ Refuse a function range past its table in the fake
The fake platform's setFunctions:withRange: set the entries of a range that
ran past its table up to the table's end. Where the range started at
u64::MAX, it stepped its index past it, which ends a debug build's test with
an overflow. The trait's doc says such a range is the platform's refusal and
sets none of the entries, and the Vulkan platform refuses it
(rt_platform/function_table.rs). The message fuzz target ended this way under
11 of RGFX_FUZZ_SEED 1 to 300 (m3-max-81328), each a FUNCTION_TABLE_SET whose
first entry was u64::MAX. The default seed reaches none of them.

The fake now refuses, with checked arithmetic, a range past its table or of
another length than its list, as the Vulkan platform does, and sets none of
the entries.

Census (m3-max-81504, homelab-um870-1): with the old fake marked, the tests
of graphics::decode and graphics::tests (999) set no range past a table and
no list of another length, so none relied on the partial set.

Tests (homelab-um870-1, fake platform; counts measured):
- m3-max-81535: the 999 tests of graphics::decode and graphics::tests pass.
- m3-max-81543: under RGFX_FUZZ_SEED 1 to 300 the message target passes at
  every seed, with no panic. Under m3-max-81328, 22 of those seeds ended in
  one: 11 in a function table's range, and 11 in a heap's buffer, which the
  next commit fixes.
2026-12-02 19:53:04 -08:00
Anees Iqbal 41f14311fb ✅ Sweep each seeded op in the command buffer fuzz
The command buffer fuzz target failed where an op it seeds was never carried
out in a run of its default 768 cases. Each such op is carried out about 11
times a run, so the guard rested on chance. Under RGFX_FUZZ_SEED 1 to 1000, 2
runs found one at 0, seeds 734 and 956 (m3-max-81328). The default seed's
thinnest op stood at 2, so any change to the generator's draws could turn the
target red with no bug behind it.

Before its cases, the target now sends each op of a seeded group in a stream
of its own (seeded_stream_of): an encoder of its group that starts with an
UPLOADS_WRITTEN and holds the op alone past its pipeline's op. The buffer is
the one buffer of a setup of its own, its message as the guest sends it. The
target fails, naming the op, where one is not carried out and completed once.
That holds at any seed and any number of cases, so the chance guard goes. The
cases still print how many of each op were in buffers carried out.

seeded_stream draws its op, then builds the stream with seeded_stream_of.
command_buffer_on fuzzes its fields, then builds the message with
command_buffer_as. Both draw as before, so the other targets' inputs are the
same.

Tests (homelab-um870-1, fake platform; counts measured):
- m3-max-81496, m3-max-81535: cargo fmt and clippy (host and Windows) are
  clean, and the fuzz's six targets pass.
- Their counts (by tag, by type, and the answers line) are the same as on the
  parent's fuzz.rs. Only the process's degradation counts grew, from the
  sweep's setups.
- The command buffer target runs in 2.4 s, up from 2.0 s.
- Red: with SET_CULL_MODE's seeded body emptied, the target fails at
  RGFX_FUZZ_SEED=0 naming 0x101a RENDER_SET_CULL_MODE ("body too short").
- m3-max-81542: under RGFX_FUZZ_SEED 1 to 1000 the target passes at every
  seed, the sweep included. At each seed its cases' counts are those of
  m3-max-81328, which ran on the parent's fuzz.rs.
2026-12-02 19:53:04 -08:00
Anees Iqbal 465531ce05 🎨 Format the straight downloads' code as rustfmt does
Batch cw's lint leg found three files of row 4's straight downloads
(e7a1aba504 and its tests) that rustfmt formats differently: line breaks
only, no token changed.
2026-12-02 19:16:41 -08:00
Anees Iqbal 5338b7f585 🐎 Copy dirty shapes straight into the pages at a download
A download or a release of a per-shape cache wrote its dirty shapes into
the cache's buffer, then copied the buffer out: on the rt platform, whose
IOSurface blocks take no view, the GPU into Shared staging pieces and the
host's CPU into the pages. Census B on the M3 (m3-max-81170) counted 3,772
such write-backs, two a recorded frame, each 3.1 MB a 1080p picture, and
the downloads made 119 deferred buffers' memory for them.

Where the buffer holds nothing the pages lack beyond those shapes' writes
(its record of the host's copies is empty, no texture lies over it, its
pages are a view or copied, laid out as the pages), the shapes' rows now
go straight into the pages' view or a staging piece that holds their
extent, and the CPU moves the rows alone into the pages: one GPU copy
less a plane a read-back, and no memory made for the buffer. The pages
take the same bytes as before. The buffer then lacks the shapes' writes,
as after a straight fill, so a copy through it takes the pages first.
The shapes copied are counted as rt-shape-downloads and
rt-shape-download-bytes; docs/video/bugs.md D30 records the copies left.

This is not a keeper: the batch that lays a Mac's surfaces' shapes in
place over an import of their pages deletes it, unless another caller is
named then. Its entry is SurfaceCaches::write_back's, with its own counts
and a test knob, Caches::set_no_straight_downloads, which the twelve
tests of the copy through the buffer now set: the caches still make that
copy wherever a straight one does not go. The red tests take the counts,
and a third holds the copy through the buffer after a write over it and a
release that goes straight.
2026-12-02 19:16:41 -08:00
Anees Iqbal 36924edfa1 ✅ Test that a download copies dirty shapes straight out
A download of a cache whose buffer holds nothing its pages lack but its
dirty shapes' writes copies them into the buffer and the buffer into the
pages: two GPU copies of each byte, the second through staging pieces
where the pages are copied, and the buffer's memory made for it. These
tests hold the form that copies the shapes straight into the pages' view
or the staging piece instead, with no write-back and no copy out of the
buffer; they fail until it lands.
2026-12-02 19:16:41 -08:00
Anees Iqbal c310da59a8 ✅ Gate a run on the guest bundle's own unsupported answers
A nil the guest bundle answers itself never reaches the host's degradation
counts: the image viewer's 3D window stayed white while every host count read
clean, because the bundle answered newSharedTextureWithDescriptor: with nil.
scripts/internal/guest-unsupported.py reads a run's guest logs for the
bundle's "RGFX: unsupported:" lines and checks each selector against
guest-unsupported-expected.tsv, where each line is deliberate, open or fixed,
with the day it was last seen and the tree checked. An unlisted selector, or a
fixed one seen again, fails the run. Nothing changes for the guest or the host.
2026-12-02 18:48:23 -08:00
Anees Iqbal 33b4b800c9 🔧 End a stuck test on the NVIDIA legs before the job's limit
On an RTX 3090 seven GPU tests in flight stalled together after 2,033 had
passed, and the leg was killed at its 10-minute limit with six processes that
would not die (m3-max-80466, 12-02). The nvidia profile now ends a test that
runs past five minutes, so the leg names the stuck test instead of timing out
whole. Nothing changes for the guest or the host.
2026-12-02 18:47:53 -08:00
Anees Iqbal ad84030cd8 ✅ Seed framing ops in the doorbell fuzz
The doorbell fuzz target answered no buffer with a SURFACE_USE, a
SURFACE_ORDER or a COMMIT_ORDER (0 of each at 4,000 cases, m3-max-81015).
Those are the answer's ordering checks. Setup's IOSurface block has no
device cache, so a SURFACE_USE of it does nothing. Setup also makes one
queue, and every message is at seqno 0, while the order ops name another
queue's buffers by seqno.

The doorbell target now has framing to answer:
- Setup makes queue 0x100 and an IOSurface block with a device cache, for
  this target alone (doorbell_setup).
- One buffer in four is of queue 0x100. Each queue's buffers are at seqnos
  rising from 1, through command_buffer_on. command_buffer keeps seqno 0
  and the same draws, so the other targets' messages are unchanged.
- A buffer of queue 0x100 is a well-formed pass led by an empty
  SURFACE_ORDER, as the bundle sends for a buffer that uses IOSurfaces and
  names none. So it signals its queue's order as it ends, and a buffer that
  names it can be seen finished. A plain buffer never signals, and a video
  op's wait on the CPU for one named that way never ended (m3-max-81240).
- A buffer of queue 1 leads, one in three, with a SURFACE_USE of the cached
  block, at a generation that rises one use in four. One in two leads with
  a SURFACE_ORDER naming one or two carried-out buffers of queue 0x100, and
  one in three with a COMMIT_ORDER naming one. Three names in four are of a
  buffer already finished. None names one not yet taken, whose wait at the
  take only another thread could end. A buffer with framing is a
  well-formed pass and asks for its CB_SUBMITTED.
- Where a named buffer's work is still held, the target lets the platform
  take it before the naming buffer's take, after the answer. A video op's
  wait on the CPU for the named buffer would otherwise wait on the one
  thread that releases it (case 392, m3-max-81229, a stack under gdb).

The answering run asserts two more of the answer's checks (cmdbuf.rs,
answer_at_doorbell):
- No buffer is answered that uses the cache at a generation no buffer taken
  before it used it at, which owes the cache a fill.
- No buffer is answered whose SURFACE_ORDER names a buffer of queue 0x100
  not yet finished, its work still held, while that queue lives.
Above 100 cases, the target fails where neither was offered, or where no
answered buffer had a SURFACE_USE, a SURFACE_ORDER or a COMMIT_ORDER.

Tests (homelab-um870-1, fake platform; counts measured):
- m3-max-81281: cargo fmt, the header check and clippy (host and Windows)
  are clean. graphics::decode and graphics::tests: 996 pass. The fuzz's six
  targets pass.
- At 256 cases, the doorbell target:
  - offered 138 buffers owing the cache a fill and 12 naming an unfinished
    buffer, none answered;
  - answered 15 with a SURFACE_USE, 31 with a SURFACE_ORDER and 20 with a
    COMMIT_ORDER, and 191 in all.
  It runs in 2.7 s, up from 1.6 s.
- At 4,000 cases: 2,100 and 257 offered, none answered; 255, 475 and 346
  answered with framing, and 2,946 in all. Every case's answered run
  matched its taken run.
- The command buffer and message targets print the same counts as on the
  parent's fuzz.rs.
- Red, the answer's cache check removed: the target fails at case 0, a
  buffer owing a fill answered.
- Red, the answer's SURFACE_ORDER readiness check removed: it fails at case
  31, a buffer naming an unfinished one answered.
- Red, no framing seeds: it fails, naming 0, 0 and [0, 0, 0].
- The thinnest of the target's guarded counts, buffers answered behind an
  owed CB_SCHEDULED, is 2 at 256 cases (50 at 4,000).
2026-12-02 18:47:37 -08:00
Anees Iqbal 35c2057a23 ✅ Hold the platform's take in the doorbell fuzz
The fake platform takes a buffer's work at its commit, even one that waits
for an event. Metal schedules such a buffer only once the event is
signalled: measured on the M3 Max (design.md, "Submitted") and on the 5300M
and 630 (dgpu-oracle.md). So in the doorbell fuzz target a queue was never
held when the next buffer came, and no buffer before it owed its
CB_SCHEDULED. A per-branch count at 4,000 cases took neither refusal
(m3-max-81043). The fake's model stays as it is: 217 of the decoder's tests
wait on an event not yet reached (m3-max-81070).

The target now uses the fake's hold of the platform's take
(World::hold_submissions). From a waiting buffer's commit on, the platform
takes no buffer's work. One other buffer in three holds the take too, as a
platform may take a buffer's work after its commit. The held work is taken
at one step in four, and at the case's end, then completed. Both runs draw
alike.

In the answering run, the target asserts the answer's contract
(cmdbuf.rs, answer_at_doorbell), reading queue 1's counts before the answer:
- No buffer is answered while a waiting buffer of its queue is not yet
  scheduled.
- An answer behind a buffer of its queue that owes its CB_SCHEDULED posts
  no CB_SCHEDULED of its own.
Above 100 cases, it fails where neither was reached.

Rates were picked from a grid (m3-max-81094). With a hold at waiting buffers
alone, no answer came behind an owed CB_SCHEDULED. With another buffer in
three holding too and one step in four taking the work, 83 did at 4,000
cases.

Tests (m3-max-81114, homelab-um870-1, fake platform):
- cargo fmt, the header check and clippy (host and Windows) are clean.
- graphics::decode and graphics::tests: 987 pass. The fuzz's six targets
  pass.
- At 256 cases: 58 buffers were offered behind a waiting one not yet
  scheduled, none answered; 6 were answered behind one that owes its
  CB_SCHEDULED; 165 were answered in all. Every case's answered run matched
  its taken run.
- At 4,000 cases: 913 offered behind a waiting one, none answered; 83
  answered behind an owed CB_SCHEDULED; 2,530 answered in all, every case
  matching.
- Red, with no holds: the target fails, naming 0 and 0.
- Red, with the answer's held-queue check removed: it fails at case 3, a
  buffer behind a waiting one answered.
- Red, with the answer's owed check removed: it fails at case 43, a
  CB_SCHEDULED posted ahead of an owed one.
2026-12-02 18:47:37 -08:00
Anees Iqbal 0804c8a53a ⬆️ Build on metal2vulkan development dddd91b993
Pin K, twenty commits past pin J (15898e612e), with no change to the
runtime's public API (tests/api_signatures.tsv is the same). For the guest:
air.mad computes the multiply and the add unfused, as Metal's mad does
without fma; half arithmetic stays in 16 bits on devices that lack only
denormal preservation for halves; the replay player draws patches, prints
its progress and stops cleanly.
2026-12-02 18:20:52 -08:00
Anees Iqbal 3eb5983fb5 🐛 Count a promoted plain image until its last old texture goes
A promotion took the plain image's bytes out of the caches' count and let go
of the image at once, but every guest texture made over the plain shape before
the promotion keeps the plain image's memory for its own life: its RtTexture
keeps its first rt texture, a view of the plain image, so a read of it another
thread began before the retarget stays good. The caches' count fell while the
memory stayed held.

Now the storage shape holds the plain image and counts its bytes with its own
until no texture made over the plain shape before the promotion references it
(the plain shape's tag, which command buffers that name it hold too), then lets
it go: at the next begin that uses the cache, at a sweep, or with the storage
shape. The caches' count, and so their peak, falls when the memory goes. A
"plain images let go of" count joins the promoted line in the caches' log.

What the guest sees: nothing; the host's count of the caches' bytes holds a
promoted plain image's while its memory is held. Tests: the shapes table holds
the image until its plain shape's last reference goes; a promoted image stays
counted while a texture from before lives and goes, the count falling by its
bytes, at the first begin after that texture's release, a texture made after
the promotion keeping nothing of it.
2026-12-02 18:00:55 -08:00
Anees Iqbal cee66505b5 🐎 Promote a plain shape into its plane's storage shape
Where a plane held a plain shape and a texture that takes storage made a storage
shape of the same extent, rule 1 kept the two images current: each write
through one was copied into the cache's buffer and into the other (census B's
M3 boot: 3,714 such copies, 5.8 GB). Now the plain shape is promoted into the
storage shape: its bytes are copied into the storage image where that one owes
its fill, its views move onto the storage image (Texture::retarget_views), and
it goes. The plane holds one image from then on.

What the guest sees: the same bytes through every texture over the plane, the
same objects, resource indices and gpuResourceIDs, and none of those copies.

A promotion is made where the cache is idle: no command buffer begun and not
finished uses it, no copy of it is deferred, and every committed user has ended
on the GPU. rt's rule for a texture placed at an index another holds
(arrays.rs place_texture: no work in flight uses the index's elements) makes a
committed user that has not ended count, as it reads the texture through its
index when it runs. Otherwise the promotion is owed and made at the next begin
that finds the cache idle, before its walk. Where only committed users keep the
cache from idle, a begin waits for them on the CPU, at most 8 ms, once per plane
for the cache's life, never per frame; past that its walk encodes as before.

A cache keeps its last 8 promoted extents, and a plain texture of one takes the
storage shape at its make. While the process records, no promotion is asked: a
stream holds no retarget, so a recording keeps both shapes and rule 1's copies
and replays as it ran (rt-shape-promotions-unrecorded counts them; rt's own
retarget refuses while recording too).

Counts: rt-shape-promotions, -promotion-bytes, -promotions-owed,
-promotion-waits, -promotion-wait-ns and its -most, -promotion-owed-ns and its
-most, -promotions-refused, -promotions-unrecorded, -promoted-at-make and
-promoted-makes, and a "shapes promoted" line in the caches' log.

Tests changed with it: a storage texture over an idle cache's plain shape now
promotes it, where it made a second shape; the FORMAT_STORAGE test promotes at
idle; the unseen-write test puts its plain texture at another extent, as one of
the storage shape's extent is now promoted. New tests: a write in flight
through the plain texture promoted at the next begin after it, in order (the
red test first); a begin's one wait ending with its user; a cache never idle
waiting once and keeping rule 1's copies until it is; a refused promotion; the
kept extents.
2026-12-02 18:00:55 -08:00
Anees Iqbal 7b5529b75d 🆕 Let a texture's views move onto another image at their indices
The per-shape form gives an IOSurface plane a plain image and, once a texture
that takes storage arrives, a storage image beside it, which rule 1 keeps
current by copies between the two. Promoting the plain shape into the storage
shape needs the plain image's live views moved onto the storage image with
nothing the guest names changing.

Texture::retarget_views (no Metal counterpart) does that. On rt it makes each
view of an image for views, and each view of such a view, again of the other
image, in its own format, type, levels, slices and swizzle, at its own resource
index, which the new texture takes from the old one as rt places a texture at
an index another holds. The view's object, resourceIndex and gpuResourceID stay
as they were. An RtTexture reads its rt texture by one plain atomic load and
keeps a replaced one until it goes, so a reference read before a retarget stays
good. A retarget is made once per image; it is refused, every view left as it
was, where rt refuses a view and while the process records, as a stream holds
no retarget. The fake moves each view's parent and logs each move.

Nothing calls it yet, so the guest sees no change from this commit. Tests: the
retarget on Vulkan (the ids unchanged, reads give the other image's bytes, a
later view is of the other image, a second retarget and a view's are refused),
and an argument buffer's texture read across a retarget, its gpuResourceID in
the buffer unchanged.
2026-12-02 18:00:55 -08:00
YXC0915 1bac132e21 🐛 Keep the Windows QMP socket path usable
Pass the absolute AF_UNIX socket path to the relay without resolving its Windows reparse point. Exercise the actual CLI path in the WHPX smoke.
2026-12-03 09:51:25 +08:00
YXC0915 d3ceaeaa0b 🆕 Add the Windows iPad Air M3 USB enumeration helper
Keep the filtered iPad session tied to the selected USB port and the
guest's QEMU process. Use manual reconnect for driver activation and
release, with a recovery record for interrupted sessions.

Adapt the Windows device transaction and exporter from
steelbrain/reims-vgpu#201 for the Air M3 enumeration test.
2026-12-03 09:50:03 +08:00
棠渚听潮 64c0e9a32a 🐎 Batch Vulkan vertex draws with opt-in multi-draw indirect 2026-12-03 09:47:18 +08:00
Anees Iqbal b84c18e632 🔥 Give every command queue's counts their lane, not an Option
QueueCounts::lane was an Option. Its doc said a queue had none where its
buffers were carried out whole where they were taken, in the decoder's own
tests. Since e9e2b69241, QUEUE_CREATE builds a queue's counts with
QueueCounts::on, which always gives them a lane, and nothing builds them any
other way. The None arms were dead. A count of the doorbell answer's
branches over 4,000 fuzz cases never took its no-lane arm (m3-max-81015).

The lane is now an Arc<Lane>, and the answer's kept turn a Turn:
- the answer takes its turn and ticket from the lane alone;
- a begin wakes the lane where its work goes there;
- the queue's drop closes its lane.
The docs that named a queue with no lane go, and so does QueueCounts'
derive(Default), which nothing used. Behaviour is unchanged.

Tests (m3-max-81059, homelab-um870-1, fake platform): cargo fmt, the header
check and clippy (host and Windows) are clean, and graphics::decode and
graphics::tests pass, 987 tests.
2026-12-02 17:44:02 -08:00
Anees Iqbal 41c37fb787 ✅ Seed event waits in the doorbell fuzz
No buffer the doorbell fuzz target offered to the answer waited for an event.
Its streams hold no WAIT_EVENT: the fuzzed ones turn every framing event op
into an ask. So the answer's refusal of a buffer that waits (it answers only
one that waits for no event) never ran there. A per-branch count at 4,000
cases found it 0 times (m3-max-81015).

One buffer in eight now starts with a well-formed WAIT_EVENT on event 6 or
shared event 7, at a value of 0 to 3. Both runs draw it. In the answering
run, the target asserts the answer's contract: a buffer that waits for an
event is never answered. It also fails where no such buffer was offered to
the answer at more than 100 cases.

Completions stay at once. A run that held them back (m3-max-81043) reached
nothing more: the fake schedules a buffer at its commit, so a waiting buffer
lets its queue go before the next one is offered.

Tests (m3-max-81059, homelab-um870-1, fake platform, with the commit after
this one):
- cargo fmt (after its layout of one call, taken here), the header check and
  clippy (host and Windows) are clean.
- graphics::decode and graphics::tests: 987 pass. The fuzz's six targets
  pass.
- At 256 cases, the doorbell target offered 88 waiting buffers, none
  answered, and answered 177 others.
- At 4,000 cases, it offered 1,347 waiting buffers, none answered, and
  answered 2,788 others. Every case's answered run matched its taken run.
- Red, with no buffer waiting: the target fails, naming no waiting buffer
  offered.
- Red, with the answer taking a waiting buffer (its waits check removed):
  the target fails at case 16, naming a waiting buffer answered.
2026-12-02 17:44:02 -08:00
Anees Iqbal 63c654fb04 ✅ Refuse the doorbell answer's posts in its fuzz
The doorbell fuzz target posted every record the answer offered it, so a
refused post never ran inside its check. A refused post is what a busy or
full ring does. It leaves the answered buffer's CB_SUBMITTED, or its
CB_SCHEDULED, to its begin. A per-branch count at 4,000 cases found 3,182
answered buffers, and none had a post refused (m3-max-81015, a scratch count
of the answer's returns).

The target's ring now refuses one record in four: the CB_SUBMITTED and the
CB_SCHEDULED are each taken or refused by their own draw. Both runs make the
draws, so their streams stay the same. The target counts the answered
buffers whose records were refused, and fails where none of either was.
The unit test that refuses a post refuses one buffer's CB_SUBMITTED:
a_buffer_answered_at_the_doorbell_is_carried_out_as_one_decoded.

Tests (m3-max-81032, homelab-um870-1, fake platform):
- cargo fmt, the header check and clippy (host and Windows) are clean.
- The fuzz's six targets pass. At its 256 cases, the doorbell target answered
  207 buffers; the ring refused the CB_SUBMITTED of 53 and the CB_SCHEDULED
  of 26. Each answered run matched its taken run.
- At 4,000 cases it answered 3,284; the ring refused the CB_SUBMITTED of 791
  and the CB_SCHEDULED of 642, and every case matched.
- Red, with the ring taking every record: the target fails, naming [0, 0].
2026-12-02 17:44:02 -08:00
Anees Iqbal 2221a41c20 📝 Record the slots boot's reading in the memory slots row [ci skip]
The memory slots row said what an iMac20,1 VM's System Information lists with
reims-ctl's slots; this records the boot that read it: one slot before
(m3-max-80826), and with the installed reims-ctl's command four, DIMM 1 to 3
"Empty", on um870's 780M (m3-max-80887).
2026-12-02 17:23:00 -08:00
Anees Iqbal 3e8cbbff4a 🐛 List an iMac20,1 VM's four memory slots, not QEMU's one
An x86-64 guest's System Information listed one memory slot, "DIMM 0": QEMU
makes only the memory devices RAM fills, one on current machines, and
OpenCore copies them into the guest's SMBIOS. An iMac20,1 has four SO-DIMM
slots.

reims-ctl gives -smbios type=17's slots=4,form_factor=13 for an iMac20,1,
read from the VM's OpenCore image at each start, as it gives the memory's
error correction: vendor/qemu's 445170b5 makes the slots past the RAM's
empty. A guest given four such devices lists DIMM 0 with the VM's RAM and
DIMM 1 to 3 as "Empty" (m3-max-80846; with reims-ctl's command,
m3-max-80887). The options go only to a QEMU that takes them, asked once
per binary; another model, an iMacPro1,1 among them, and another QEMU keep
one slot, the command as before.
2026-12-02 17:23:00 -08:00
Anees Iqbal 3260654561 🆕 Count every copy between a cache's buffer and its shapes, in bytes
A run's copies between a device cache's buffer and its shapes were told only
on the periodic shapes line, whose last snapshot falls at a different moment
in each boot, and rule 1's copy of a written shape into the buffer, of its
overlap or of its whole extent while a texture over the buffer lives, had no
bytes anywhere. Two boots' nets could not be read at one cut.

Each such copy is now counted on the counts line with the bytes it moved:
fills from the buffer (rt-shape-fills, -fill-bytes), write-backs
(rt-shape-written-back, -bytes), rule 1's source copies of an overlap
(rt-shape-overlap-sources, -source-bytes) or of a whole extent
(rt-shape-whole-outs, -whole-out-bytes), and its copies into the other
shapes (rt-shape-overlap-copies, -copy-bytes), of which the order copies
are a part as before.

What changes for the guest: nothing. The host's counts line has ten more
codes where the per-shape form copies.
2026-12-02 17:23:00 -08:00
Anees Iqbal b89efe1cd5 ✅ Seed the fuzz's thin message types
The message target carried out four of its message types only by chance:
- a heap over host memory;
- a buffer over host memory;
- a shared event's value;
- a shared event's name.
Their fuzzed ids and offsets missed what setup makes. At 4,000 cases each was
carried out 20 to 48 times in about 900 messages (m3-max-80949).

The target's seeded messages now name each of them:
- HEAP_OVER_HOST_MEMORY and BUFFER_OVER_HOST_MEMORY lie over one to four heap
  pages of the block's first half, which setup lays nothing out in. Each is at
  the guest's GPU address or at the host's (a zero address, which the decoder
  leaves unpinned).
- SHARED_EVENT_SET_VALUE gives shared event 7 a value above the last.
- SHARED_EVENT_NAME names shared event 35, its values going to queue 1. Setup
  now makes that event and leaves it unnamed. The names are ones no
  SHARED_EVENT_IMPORT asks for.

Tests (homelab-um870-1, fake platform):
- m3-max-80964: the header check and clippy (host and Windows) are clean.
- m3-max-81008: cargo fmt is clean, and the fuzz's six targets pass. At the
  message target's 384 cases the four types were carried out 46 to 72
  times.
- At 4,000 cases (m3-max-80964), each was carried out 564 to 633 times in
  1,616 to 1,682 messages.

The red, with the four types left out of the seeds, still passes. Fuzzed
messages carried them out 2 to 8 times at 384 cases (m3-max-81008), and the
guard fails only where a type was never carried out. The counts above show
what the seeds add; the guard cannot.
2026-12-02 17:23:00 -08:00
Anees Iqbal b584d2635c ✅ Seed the fuzz's video ops
The command buffer target carried out none of the four video ops in 4,000
cases (m3-max-80736): a video encoder needs a session of its op's codec and
direction, and planes over an IOSurface, and setup made neither.

Setup now makes a buffer, and over it the planes of a 64 by 64 IOSurface,
4:2:0 at 8 bits (an R8Unorm luma texture, and an RG8Unorm chroma texture
after it, 64 bytes a row), and a video session of H.264 and of HEVC in each
direction, on the fuzz's video, whose sessions land nothing. A seeded video
stream opens the session of one op's codec and direction and holds one to
eight of that op:
- a decode of an access unit in buffer 2 or 3 into the planes, with an SPS
  and a PPS NAL unit's headers in Annex-B form, the codec's, or none;
- an encode of the planes into buffer 2 or 3, its result into the other, a
  keyframe or not, with settings or none.
A video op is drawn five times as often as another group's, as its stream
holds it alone, where another group's holds four and a half ops of its
group on average; at the same weight, ENCODE_H265 was carried out once at
768 cases (m3-max-80915).

Tests (m3-max-80939, homelab-um870-1, fake platform):
- cargo fmt, the header check and clippy (host and Windows) are clean, and
  the tests build.
- The fuzz's six targets pass. The command buffer target carried out 449 of
  1,916 buffers, and each video op 49 to 86 times. Each seeded video stream
  it did not carry out was one whose message the target fuzzed: its
  op_bytes (Malformed) or its queue (BadReference), from a run printing
  them in the same job.
- Red, with the seeds replaced by fuzzed streams: the target fails, naming
  81 render ops, 25 compute ops, 26 blit ops and the 4 video ops never
  carried out.
2026-12-02 17:23:00 -08:00
Anees Iqbal dee8841df3 ✅ Seed the fuzz's UPLOADS_WRITTEN
The command buffer target carried out no UPLOADS_WRITTEN in 4,000 cases
(m3-max-80736): the host carries the op out as it begins the buffer,
dropping the records it cannot take, but the fuzzed streams that hold one
hold an op the walk refuses too.

One seeded stream in two now starts with one, before its encoder, as the
bundle puts it: one or two records of the bytes the buffer's encoders put
in the Managed buffer from its start, none to all of its 0x4000. The target
fails where it was never carried out, as it does for the seeded groups' ops.

It takes the place QUEUE_BARRIER and SCHEDULED_WANTED had in the plan for the
framing ops, which every host faults (the previous commit).

Tests (m3-max-80910, homelab-um870-1, fake platform):
- cargo fmt, the header check and clippy (host and Windows) are clean, and
  the tests build.
- The fuzz's six targets pass. The command buffer target carried out 454 of
  1,916 buffers, and UPLOADS_WRITTEN in 181 of them.
- Red, with the seeds replaced by fuzzed streams: the target fails, naming
  82 render ops, 26 compute ops and 26 blit ops never carried out; a fuzzed
  UPLOADS_WRITTEN was carried out once by chance.
2026-12-02 17:23:00 -08:00
Anees Iqbal 2af898fea1 ✅ Seed the fuzz's render ops
The command buffer target carried out 58 of the 95 render ops never in 4,000
cases (m3-max-80736), and the rest once or twice each at its 768 cases, by
chance: a render stream holds a fuzzed op the decoder refuses almost always.

The seeded streams now open a render pass too, over texture 4, its
visibility results going to buffer 3. A seeded render pass sets the render
pipeline first, as the guest's do before they draw, then holds one to eight
well-formed ops over setup's objects, which now include a render pipeline
of the library's vmain and fmain into one BGRA8 attachment and a depth and
stencil state:
- the render pipeline and the depth and stencil state set;
- buffers 2 and 3, or nil, bound to each stage at offsets in them, with
  strides, and offsets moved; textures 4 and 5 and the Managed one, and the
  sampler, with LOD clamps, bound to each stage;
- viewports, scissor rects, vertex amplification and each fixed-function
  state;
- draws of up to 64 vertices or indices and 4 instances, given or read from
  buffer 2 or 3; patches, of a patch index buffer or none; mesh draws; tile
  dispatches;
- texture 5 to resolve into, a tessellation factor buffer, the depth and
  stencil attachments cleared;
- buffers, textures and the render indirect command buffer used, and the
  three heaps, of stages or not; a barrier between stages; the fence
  updated or waited for at stages;
- a range of the render indirect command buffer's commands carried out,
  given or read from buffer 2 or 3;
- visibility results counted at offsets in buffer 3.
One in four of a fuzzed render stream's ops is such an op too.

RENDER_RESET_STATE is not seeded: every host faults it, since none offers
RGFX_FEATURE_CB_PARTS yet (its doc in reims-vgpu-graphics' ops/render.rs).
QUEUE_BARRIER and SCHEDULED_WANTED are not either, for the same reason
(their docs in ops.rs): nothing in the host names them or their features.

A seeded stream now opens each group as often as the group has ops, so each
seeded op is about as frequent as any other: with the groups taken evenly,
each render op was carried out 1 to 8 times at 768 cases (m3-max-80834). The
target fails where a seeded op was never carried out only in a run of its
default 768 cases or more, as a run of fewer may miss one by chance.

Tests (m3-max-80866, homelab-um870-1, fake platform; m3-max-80854 before
the commits were split):
- cargo fmt, the header check and clippy (host and Windows) are clean, and
  the tests build.
- The fuzz's six targets pass. The command buffer target carried out 445 of
  1,916 buffers; each render op 2 to 25 times (the pipeline's set 268), each
  compute op 5 to 21, and each blit op 4 to 19, the groups now taking the
  seeded streams by their ops' count.
- Red, with the seeds replaced by fuzzed streams: the target fails, naming
  81 render ops, 25 compute ops and 26 blit ops never carried out.
2026-12-02 17:23:00 -08:00
Anees Iqbal f1384e8503 🐎 Keep the fake's function tables' entries sparse
The fake platform kept every entry of a visible function table, 16 bytes of
the test's memory each, and the Vulkan platform takes tables of up to 536
million entries (2 GiB of 4-byte entries, rt_refuses_function_table). The
decoder's message fuzz makes such tables. Once the next commit moved the
fuzz's inputs onto them, a FUNCTION_TABLE_CREATE of 139 million entries took
1.2 s, and one of 517 million (8.3 GB of entries) took 4.4 s: the message
target ran 18.6 s, against 2 s, and peaked at 10.5 GiB (m3-max-80840).

The model now keeps the entries' count and, by index, the entries set to a
handle. The fake's answers are unchanged: the entries read the same, and
allocatedSize is still 256 bytes and 8 per entry.

Tests (m3-max-80866, homelab-um870-1, with the next commit): cargo fmt, the
header check and clippy (host and Windows) are clean; the fuzz's targets,
the decoder's function table tests and the testkit's, 131 tests, pass. The
message target ran 1.7 s, and the job, its build included, peaked at 5.4 GiB.
2026-12-02 17:23:00 -08:00
Anees Iqbal d1b9de97d4 🎨 Lay out the oversized config test as rustfmt does
The copy into the oversized config fits on one line.
2026-12-02 17:19:47 -08:00
Anees Iqbal 7c9c1f0df6 ✅ Build the oversized config test from the config's size
refused_graphics_configs gave a 96-byte config, struct_size 96, with byte 88
set, to show that a set byte past the library's size is RVG_ERR_UNSUPPORTED.
cf394032bd's headless_modes made the library's size 96, so byte 88 became the
pointer's low byte, inside the config: the create took 0x1 as the array and
aborted on its alignment. The library reads a config only up to its
struct_size (sized::read zeroes the rest), so the test was wrong, not the read.
The test now builds its config from the library's size plus 8, aligned as the
config is, and sets the first byte past it.

each_headless_display_offers_its_own_of_the_configs_modes also gives a config
ending before headless_modes a pointer no array of sizes can start at past its
size: every display keeps the one mode, so the field past a host's size is
never read.
2026-12-02 17:19:47 -08:00
Anees Iqbal ff02ad0a20 ✅ Give the C harness's device configs headless_modes
cf394032bd appended headless_modes to RvgGraphicsDeviceConfig, and the C
harness's three configs, positional initializers, end before it: clang's
-Wmissing-field-initializers under -Werror refused harness.c at each, failing
c_harness_passes, c_harness_null_handle_aborts and
the_dylib_is_found_by_rpath. Each config now gives NULL, every display at the
one headless mode, as before.
2026-12-02 17:19:47 -08:00
Anees Iqbal 6f194295fb 🎨 Lay out the resolution tests as rustfmt does
make check-ctl's rustfmt (m3-max-80785) refused the per-display resolution
tests' layout in reims-ctl: a call chain and an array past rustfmt's widths,
and two chains that fit on one line. The tests are unchanged.
2026-12-02 17:19:47 -08:00
Anees Iqbal 4ce2543a5e 🆕 Let reims-ctl's resolution give each display a size
A VM's resolution was one size, every window's first size and, on a
headless start, every display's mode, so a VM of displays on screens of
different sizes opened every window at the same size. The resolution
setting now takes one size for every display, as before, or one for each
display, comma-separated in the displays' order (--resolution
2560x1440,1920x1080 on create and set, and the same in the interface's
form). Another count of sizes than the VM's displays is refused with a
message that says what to give. It applies at the next start: the fork's
1d614106 lets reims-graphics-pci's resolution take the list, which
reims-ctl writes with each comma doubled (resolution=2560x1440,,1920x1080).
One size, or sizes that are all one, gives the device string reims-ctl gave
before, byte for byte (each_display_s_size_reaches_the_device). A VM's
summary names each window's size where they differ.

What the user sees: each display's window opens at its own size, and a
headless start offers each display its own mode.
2026-12-02 17:19:47 -08:00
Anees Iqbal dc87082ea8 🆕 Let a windowless device give each display its own first mode
A device without a window offered every display the one headless mode its
config gave (headless_mode_width and _height), so a host could not give a
VM's displays different sizes without windows. RvgGraphicsDeviceConfig's
eighth version appends headless_modes: NULL, or an array of display_count
sizes, display i's at i, each taken as the one mode is (a 0 in either side
is 1920 x 1080), in its place. NULL, and a host built before the field,
keeps every display at the one mode; with a window the field is unread, as
the one mode is. The Rust API's GraphicsConfig gains headless_modes beside
headless_mode, and refuses a list of another count than the displays.

What a host sees: a new optional field; a host that leaves it NULL gets the
device it got before.
2026-12-02 17:19:47 -08:00
Anees Iqbal c5a3079426 📝 Drop indexed patch draws from the unbuilt render commands [ci skip]
The accuracy ledger listed drawIndexedPatches, direct and indirect, under
rt-unbuilt-render-command. The platform draws them through rt since the
commit before this one, so the row lists only what is still not built.
2026-12-02 17:04:32 -08:00
Anees Iqbal 8a7249ed5d 🆕 Draw indexed patches through rt's drawIndexedPatches
A guest's drawIndexedPatches, direct and indirect, encoded nothing: the rt
platform counted it under rt-unbuilt-render-command, since rt had no
indexed patch draw and refused every state of a control-point index type.
Pin J has both, and the platform now calls rt's draw_indexed_patches and
draw_indexed_patches_indirect, as the patch draws call theirs: the counts
and starts through small(), the state set, the buffers as rt's.

What the guest sees: an indexed patch draw draws its patches, control
point j of a patch being the vertex the index at patch_id * N + j of the
control-point index buffer names, in the state's index type, and patch_id
the patch index buffer's uint at the patch's position where the draw has
one. Metal's refusals, each drawing nothing, counted as rt-refused-metal:
an indexed patch draw through a state of no index type, a patch draw
through a state of one, a control-point index buffer offset off a
multiple of the index size and a patch index buffer offset off a multiple
of 4. rt-unbuilt-render-command no longer counts indexed patch draws.

indexed_patch_draws_on_vulkan holds it, drawing through the 16-bit and
32-bit index types, with and without a patch index buffer, directly and
indirectly, each against a patch draw of the vertices the indices name
(tests/shaders/render_tess_bump.metallib's stage-in function); before
this commit it fails at its first indexed draw, which draws nothing.

An indirect command buffer's indexed patch commands stay rt's gap: rt
builds indexed triangle draws alone (IndirectCommandBufferDescriptor), and
refuses a buffer of other command types as it is made.
2026-12-02 17:04:32 -08:00
Anees Iqbal cac3310ea0 ⬆️ Build on metal2vulkan development 15898e612e
metal2vulkan-runtime at its development commit 15898e612e (pin J), 20
commits past I. Among them, by metal2vulkan's notes: drawIndexedPatches
direct and indirect, patch draws through a patch index buffer, texture
buffers made in place in a heap, one 16-byte store for four aligned word
stores, and the CLI's --tessellation. Its API changes reach the rt
platform in what the guest sees of patch draws.

- A patch draw through a patch index buffer, direct or indirect, which rt
  refused as a gap (Draw-PatchIndexBuffer, rt-refused-gap) and so drew
  nothing, now draws: each patch takes its [[patch_id]] from the uint at
  its position there. A patch index buffer offset off a multiple of 4 is
  Metal's refusal (PatchIndexBufferOffset, rt-refused-metal).
  indirect_draws_on_vulkan held the gap; it now holds the draws through
  the patch indices and the refused offset.
- A render pipeline state of a control-point index type (UInt16, UInt32),
  which rt refused as it was made, is now made, and drawPatches through
  one is Metal's refusal (PatchDrawWithIndexType). Its indexed patch draws
  stay unbuilt here (rt-unbuilt-render-command) until the platform calls
  rt's draw_indexed_patches, in the next commit.

metal2vulkan's manifests did not change: Cargo.lock is unchanged, still
without metal2vulkan's source lines.

Checks the move cannot reach: the guest's sets, the option ROM, QEMU and
reims-ctl link nothing of the runtime.
2026-12-02 17:04:31 -08:00
YXC0915 914debd758 🆕 Enable Windows USB redirection in the portable runtime
Port the Windows usbredir build dependency and staged QEMU check from steelbrain/reims-vgpu#200 so the runtime can support device-scoped USB forwarding.
2026-12-03 08:52:03 +08:00
Anees Iqbal bc82f942e5 ✅ Seed the fuzz's compute ops
The command buffer target carried out 21 of the 32 compute ops never in 4,000
cases (m3-max-80736), and the rest once or twice each at its 768 cases, by
chance: a compute stream holds a fuzzed op the decoder refuses almost always.

The seeded streams now open a compute pass as often as a blit pass. A seeded
compute pass sets the library's compute pipeline first, as the guest's do
before they dispatch, then holds one to eight well-formed ops over setup's
objects, which now include a sampler of Metal's default descriptor:
- buffers 2 and 3, or nil, bound at offsets in them, with strides, and
  offsets moved; textures 4 and 5 and the Managed one, the sampler, with
  LOD clamps, and the function table bound;
- threadgroup memory, a stage-in region, given or read from buffer 2 or 3,
  and an imageblock size;
- dispatches of up to 8 by 8 by 8 threadgroups of up to 4 by 4 by 4
  threads, given or read from buffer 2 or 3;
- buffers, textures and the compute indirect command buffer used or behind
  a barrier, the three heaps used, and a barrier of a scope;
- the fence updated or waited for;
- a range of the compute indirect command buffer's commands carried out,
  given or read from buffer 2 or 3;
- predication's starts, of a word of buffer 2 or 3 where they read one, and
  the compressed textures' flush.
One in four of a fuzzed compute stream's ops is such an op too, and the
target fails where a compute op was never carried out, as it does for blit.

Tests (m3-max-80806, then m3-max-80816 with rustfmt's layout applied;
homelab-um870-1, fake platform):
- cargo fmt, the header check and clippy (host and Windows) are clean, and
  the tests build.
- The fuzz's six targets pass. The command buffer target carried out 430 of
  1,916 buffers; each compute op 19 to 38 times (the pipeline's set 215),
  and each blit op 20 to 54.
- Red, with the seeds replaced by fuzzed streams: the target fails, naming
  23 compute ops and 25 blit ops never carried out.
2026-12-02 16:40:51 -08:00
Anees Iqbal 6befdefe64 ✅ Seed the fuzz's blit ops
The command buffer target carried out no blit op at all: every blit stream
held at least one fuzzed op the decoder refuses, so of the 172 op tags the
wire names, the 26 blit ops and ENCODER_BEGIN_BLIT were never carried out
(a per-op count at 4,000 cases, m3-max-80736), and the target carried out 37
of 1,916 buffers at its 768 cases.

A quarter of the target's streams are now seeded: a blit pass of one to
eight well-formed ops over setup's objects, which the decoder carries out:
- copies between buffers 2 and 3, between them and textures 4 and 5, and
  between the textures, within their bytes and texels;
- a copy, an optimization and a reset of a range of an indirect command
  buffer's commands;
- fills of a buffer's range and of a texture's region, with bytes or a
  colour;
- a texture's mipmaps, invalidations and optimizations, whole or of its one
  slice and level;
- synchronizations of the Managed buffer and texture, buffer 2, texture 4,
  the compute indirect command buffer or nil;
- the fence updated or waited for.
One in four of a fuzzed blit stream's ops is such an op too. The target
prints each op tag's count, in buffers carried out and in all, and fails
where a seeded group's op was never carried out.

Tests (m3-max-80776, homelab-um870-1, fake platform):
- cargo fmt, the header check and clippy (host and Windows) are clean, and
  the tests build.
- The fuzz's six targets pass. The command buffer target carried out 425 of
  1,916 buffers, and each blit op 58 to 92 times.
- Red, with the seeds replaced by fuzzed streams: the target fails, naming
  25 blit ops never carried out. FILL_TEXTURE was carried out once without
  its seed.

The fuzzed streams are now three in four of the target's. The render and
compute ops they carried out by chance at 768 cases, once or twice each,
went from 26 tags to 16; the compute and render seeds that follow cover
those groups.
2026-12-02 16:40:51 -08:00
Anees Iqbal 23111b3469 🐛 Place a texture in a Shared heap where the device's image takes it
At pin I the runtime binds a texture in a Shared heap as it does in a Private
one, where the device's image takes the heap's Shared memory type: the M3
Max under KosmicKrisp, Intel's Iris Xe and AMD's RX 7900 XTX (rt's README).
Where the image takes no such type, which rt's README expects on NVIDIA's RTX
3090, it stays rt's Gap::HeapTexture, counted. Until now every Shared heap's
texture was that gap.

What the guest sees: on an arm64 guest, whose Metal places textures in a
Shared heap as an M3 Max's does, newTextureWithDescriptor:offset: on a Shared
heap now answers a texture with the heap's modes where the host's device
takes it, instead of nil. An x86-64 guest makes no Shared heap (its bundle
refuses one, as its Mac makes none), so it sees no change. The heap test now
holds the texture placed with the heap's options and no gap where the device
places it, and the gap where it does not.
2026-12-02 16:08:20 -08:00
Anees Iqbal 179324bb46 🐛 Write an Accumulate pass's visibility results as a Reset pass does
At pin I the runtime writes a visibility mode's result in a pass whose
visibilityResultType is Accumulate as it does in a Reset pass, in place of the
word at the mode's offset. Until now such a mode was rt's gap: it encoded
nothing, was counted under rt-refused-gap, and the guest's buffer kept its
bytes.

What the guest sees: an occlusion query in an Accumulate pass now answers its
count, or a non-zero Boolean, at its offset. That is Metal's answer on a
Radeon Pro 5300M and a UHD Graphics 630. Metal on an Apple M3 Max adds a
Counting result into the word and ORs a Boolean one; the accuracy ledger
records the difference. The render test that held the gap now holds the
written results with no gap counted.
2026-12-02 16:08:20 -08:00
Anees Iqbal 7bab9e3547 ⬆️ Build on metal2vulkan development b12d57dc98
metal2vulkan-runtime at its development commit b12d57dc98 (pin I), 91
commits past H. Among them, by metal2vulkan's notes: post-tessellation
draws (drawIndexedPatches still unbuilt), blits with a texture buffer on
either side, Int64, TextureBytes and TextureCopy causes, an index past an
array field's array sent to the sink rather than onto its last element, and
the macOS AIR 2.9 fix. Its API changes reach the rt platform in two places.

- A function keeps its own module, not its library (L52): Function::library()
  answers None once the guest released the library, library_content_hash()
  names it either way, and bitcode() is the function's own module. The kept-AIR
  bundle writes the library while it lives and the function's module once it
  is gone, naming which it holds.
- Refusals carry their causes: a render pipeline's DrawInput names what the
  function reads, and a translator refusal of a feature of several causes
  names the cause. The refusal keys take them (RenderPipeline-DrawInput-<cause>
  and Translation-<feature>-<cause>), as does the unbuilt line.

Checks the move cannot reach: the guest's sets, the option ROM, QEMU and
reims-ctl link nothing of the runtime.
2026-12-02 16:08:20 -08:00
Anees Iqbal 3a83886cc7 🎨 Format the SMBIOS probe test's answers as rustfmt lays them out
rustfmt lays the tuple out one answer a line: make check-ctl's rustfmt check
failed on 5ee1908048's single line (m3-max-80654).
2026-12-02 15:53:57 -08:00
Anees Iqbal 260cdc8789 🐛 Give an x86-64 VM's memory the presented Mac's ECC, not QEMU's
System Information showed an x86-64 guest's memory as "ECC: Enabled": QEMU's
SMBIOS type 16 says multi-bit ECC on every machine, and OpenCore copies it
into the guest's tables, where an iMac20,1, the Mac a VM presents for macOS
10.15.6 and later, has RAM without ECC. vendor/qemu's d72b4ac3 lets
-smbios type=16,error_correction set the field, and reims-ctl now gives the
presented Mac's: 3, none, for an iMac20,1, and 6 for an iMacPro1,1, whose RAM
has ECC. It reads the model from the OpenCore image's PlatformInfo at each
start, gives nothing for a model whose RAM it does not know, and asks each
QEMU once whether it takes the option (-smbios type=16,error_correction=3
-version), as it asks for memory_type; another QEMU's guest keeps ECC.

What the guest sees: an iMac20,1 VM's memory reads "ECC: Disabled" in
System Information. The part number stays OpenCore's "Unknown": a made-up
one would be a false answer.
2026-12-02 15:53:57 -08:00
Anees Iqbal 33784022f1 🎨 Lay out the fuzz's wire imports as rustfmt does
rustfmt's check (m3-max-80649) asked for the wire import list's layout with the
video names in it.
2026-12-02 15:35:55 -08:00
Anees Iqbal 3e97036438 🎨 Lay out the fuzz's video session counter as rustfmt does
rustfmt's check asked for FuzzSession::next's layout.
2026-12-02 15:35:55 -08:00
Anees Iqbal 5dcf3784a9 ✅ Seed the fuzz's video session creates
The fuzz's messages target carried VIDEO_SESSION_CREATE out 0 times, the last
type it fuzzes at 0: setup gave the decoder no host video, so every session's
create was refused, and the command buffers' video encoders never reached a
session.

setup now gives the decoder a video of its own, FuzzVideo. It makes a session
of each codec the wire names (H.264, HEVC, VP9), in either direction. Each
session's decodes and encodes land nothing and answer the next value of its
event. VIDEO_SESSION_CREATE joins SEEDED: a session of one of those codecs and
directions, of an object after setup's, so the target fails where it is never
carried out.

Tests (m3-max-80649, homelab-um790-xtx-1, fake platform):
- clippy -D warnings on reims-vgpu's tests with the testkit features is clean.
- The fuzz's six targets pass. The messages target carried VIDEO_SESSION_CREATE
  out 56 times and refused it 98 times, and nothing faulted.
- Red, with the seed generator never making the video create: the target fails,
  naming 0x21d among the seeded types never carried out (0 of 85).
- Red, with setup giving the decoder no video: the target fails the same way
  (0 of 117).
2026-12-02 15:35:55 -08:00
Anees Iqbal 414f2224b6 ✅ Seed the fuzz's range and dynamic library messages
Two types the fuzz's messages target were carried out 0 times
(m3-max-80441: BUFFER_DID_MODIFY_RANGE 0 of 73, DYNAMIC_LIBRARY_CREATE 0 of
83). A range message must name a Managed buffer, which setup never made, and
a dynamic library create must name a library, which fuzzed words rarely do.
VIDEO_SESSION_CREATE, the last type at 0, is the video lane's.

setup now also makes a Managed buffer of 16 KiB whose CPU copy is the buffer
over host memory. The seeds:
- a range of that buffer's CPU copy brought over, from no bytes to all of
  them;
- a dynamic library of the library or of the keyed one.

Tests (m3-max-80569, homelab-um870-1, fake platform):
- The header check and clippy (host and Windows) are clean, and the tests
  build. cargo fmt asked for the import list's layout, applied here.
- The fuzz's six targets pass. The messages carried out BUFFER_DID_MODIFY_RANGE
  58 times and DYNAMIC_LIBRARY_CREATE 65 times, and nothing faulted.
- Red, with the seeds replaced by fuzzed messages: the target fails, naming 24
  seeded types never carried out, BUFFER_DID_MODIFY_RANGE among them.
  DYNAMIC_LIBRARY_CREATE was carried out once without its seed.
2026-12-02 15:32:22 -08:00
Anees Iqbal a3f0e6083f 🎨 Format the coded-rows tests as rustfmt lays them out
rustfmt lays out the new scratch and staging tests' closures and asserts
otherwise; the lint of the VA-API coded-rows commit failed on them.
2026-12-02 15:32:22 -08:00
Anees Iqbal 3da2f65489 🐛 Land VA-API's coded rows below the crop where a surface holds them
A guest that decodes H.264 1080p asks for a surface of the coded picture's
1088 rows (the decode op's output_rows), as a Mac's decoder writes its whole
coded picture there. Since 789 a download of the cache copies those rows out
to the pages, but each of VA-API's three ways wrote only the crop's rows, so
the rows below the crop held whatever the cache held before: the pages'
older bytes or zeros. On rt every reference picture lands by the first way.

What changes for the guest: where a plane's crop is no taller than the
picture's, the rows the plane holds below it (OutputPlane::rows_held) take
the picture's coded rows, as far as the decoded picture has them, on each way:

- the driver's video processing into the pages or a device cache lays the
  planes out with those rows (Place::coded);
- the GPU's copy through the session's scratch: the scratch holds those rows
  and the kernel copies them;
- the CPU's copy of the read back, through the video crate's new
  ReadBack::copy_coded_into.

A plane in a device cache that the CPU's copy reaches through the session's
staging is now staged with those rows, and the copy into the cache takes
the rows the CPU wrote (Landing::wrote_rows). NVDEC's read back into a cache
lands its coded rows that way too. A plane taller than the picture keeps
the zeros past its rows, as before ("A short picture").

New fake tests cover the layout, the scratch's copies and the staged
copies. The VA-API host's tests of the first two ways against the CPU's copy
now compare the coded rows below the crop as well.
2026-12-02 15:32:22 -08:00
Anees Iqbal 6317f0e84f 🐛 Keep a guest's emulated TPR write under WHPX without irqchip
The fork's 79d47edf: under WHPX with QEMU's own APIC (kernel-irqchip=off),
a TPR the guest wrote through an instruction QEMU emulates (a
read-modify-write of the xAPIC's TPR, an x2APIC WRMSR) never reached CR8,
and the next exit put the old TPR back, so the guest's write was undone.
reims-ctl starts WHPX with the in-kernel irqchip, which keeps the TPR in
Hyper-V's APIC, but QEMU keeps its own APIC on a Windows 10 host, where the
machine has a PIC, and on a Hyper-V that offers no local APIC emulation; a
command that turns the irqchip off gets it too. Those hosts' guests lost
such TPR writes. Now the TPR the guest wrote stays, as it does under
kernel-irqchip=on.

Checked on an i7-8700B under Windows 11 with QEMU built as install-ctl.sh
builds it in MSYS2's CLANG64, and a guest of our own that ORs 0x50 into the
TPR and reads it back: kernel-irqchip=off read 0x00 in 3 of 3 runs before
(m3-max-80368) and 0x50 in 3 of 3 after; kernel-irqchip=on read 0x50 in
every run (m3-max-80485).
2026-12-02 15:32:21 -08:00
Anees Iqbal db87b77b07 🎨 Wait in the zenity test without Instant, and link no Linux item on Windows
The merge lints of the zenity fix found two things. The test waited with
Instant::now, which the workspace leaves to the Clock; it now tries 500
times 10 ms apart. The dialog doc linked end_dialog_of, which is built on
Linux only, so rustdoc for the Windows target could not resolve it; it now
names it in plain code.
2026-12-02 15:22:28 -08:00
Anees Iqbal bd075dc116 🎨 Format the NVDEC coded-rows assertion as rustfmt lays it out
rustfmt breaks the H.264 rows assertion in the imported-cache hardware test
across lines; the lint of the coded-rows commit failed on it.
2026-12-02 15:12:02 -08:00
Anees Iqbal 010f6a44f8 🐛 Land NVDEC's coded rows below the crop where a surface holds them
A guest that decodes H.264 1080p asks for a surface of the coded picture's
1088 rows (the decode op's output_rows), as a Mac's decoder writes its whole
coded picture there. Since 789 a download of the cache copies those rows out
to the pages, but NVDEC wrote only the crop's rows on each of its routes, so
the rows below the crop held whatever the cache held before: the pages'
older bytes or zeros.

What changes for the guest: where a plane's crop is no taller than the
picture's, the rows the plane holds below it (OutputPlane::rows_held) take
the picture's coded rows on NVDEC's routes: the copy within the GPU into an
imported cache, the GPU's write into the pages, and the CPU's copy of the read
back into the pages. A plane in a device cache that the read back reaches
through the session's staging still takes the crop's rows alone, as the
staging holds only those. A plane taller than the picture keeps the zeros
past its rows, as before ("A short picture").

- The video crate's AnnexBPicture::take_rows lets a picture's writes and read
  back take rows below its crop, up to its coded size.
- Landing::copy_rows copies a source's rows up to the rows a plane holds.
  Only NVDEC's read back passes more rows than the crop's, so other
  backends' CPU copies are unchanged.

The hardware test of the imported cache now lands H.264's 1088 coded rows
and checks that the read back has them.
2026-12-02 15:12:02 -08:00
Anees Iqbal 84bd3b1841 📦 Rebuild both guest kext sets for the batch's kext and bundle fixes
The arm64e ReimsGraphics takes a carry's zeros to the 16 KiB page's end by
where they lie, and both RgfxGate builds carry the Metal bundle's changes in
this batch: the residency set's argument-buffer texture writes on arm64 and
the bundle's waits. Built on the M3 with Xcode alone (make -C guest prebuilt
and prebuilt-arm64e), and prebuilt-check passes at this tree.
2026-12-02 15:12:02 -08:00
Anees Iqbal d902d4dafe ✅ Seed eight more of the fuzz's message types
After the last seeding, nine types the messages target fuzzes were still
carried out 0 times. This seeds eight of them:
- TEXTURE_REPLACE_REGION, BUFFER_OVER_SURFACE_PAGES and
  LINEAR_TEXTURE_FROM_BUFFER, which read guest memory and surfaces;
- ARGUMENT_LAYOUT, SHARED_EVENT_IMPORT, RATE_MAP_RESET, RATE_MAP_QUERY and
  BUFFER_ESCAPED.
The ninth, VIDEO_SESSION_CREATE, is the video lane's and stays unseeded.

setup now also makes a Managed 32 by 32 BGRA8 texture over the buffer over
host memory and a rate map over a 64 by 64 screen, and names shared event 7
device-wide. The context's block keeps a page for an ARGUMENT_LAYOUT's answer.
The seeds:
- a region of the Managed texture brought over;
- a buffer over the IOSurface's pages;
- a linear texture over buffer 2, 2D or a 2D array of two slices;
- the layout of up to three descriptors, or of the library's cmain's argument
  buffer;
- an import of the event's name, or of a name no event has;
- the rate map reset with other samples, or asked each of its four queries;
- the buffer over host memory or over pages noted as escaped by each act.

Tests (m3-max-80441, homelab-um870-1, fake platform):
- cargo fmt, the header check and clippy (host and Windows) are clean, and
  the tests build.
- The fuzz's six targets pass. Over 384 cases the messages carried out each of
  the 29 seeded types 36 to 112 times, the eight new ones 37 to 86 times, and
  nothing faulted.
- Red, with the seeds replaced by fuzzed messages: the target fails, naming 23
  seeded types never carried out, seven of the eight new ones among them.
  LINEAR_TEXTURE_FROM_BUFFER was carried out once without its seed.

Of the types the fuzz picks, BUFFER_DID_MODIFY_RANGE, DYNAMIC_LIBRARY_CREATE
and VIDEO_SESSION_CREATE are carried out 0 times in this run.
2026-12-02 15:12:02 -08:00
Anees Iqbal 2c0ce160f9 🐛 End zenity's close question with the display on Linux
Where a Linux window draws no more (its GPU lost, or no swapchain), the
close's question shows in SDL's message box, which is zenity's where zenity
is installed: a window of another process, which SDL spawns and waits for,
and which our window does not own (SDL 3.4.18 passes zenity no parent).
When the VM ended while it was up (the guest's own shutdown, the host's
stop), QEMU's exit waited its bounded 2 s and 5 s for the UI thread, held
in SDL's wait, and left zenity's question on the screen after the VM, where
an answer did nothing.

Now the display's end, on the thread that ends it, ends the zenity child
of a window whose question shows in a dialog (SIGTERM, found by its name
and parent in /proc). SDL's wait ends, the question's answer is Cancel,
and the window closes as the display ends. SDL's own X11 dialog is the
process's own and was never left behind. For the person: no question is
left on the screen once the VM has ended. features.md's Leaving entry
says so, with its tests.
2026-12-02 15:12:02 -08:00
Anees Iqbal 8d22350fc0 🐎 Keep the views of a movie player's whole VideoToolbox pool
A VideoToolbox decoder kept the views of the last 8 surfaces it was lent, but a
movie player's decoder session of a 1080p H.264 or HEVC movie lends 11 to 14
surfaces in rotation, each again after up to 11 others (measured on an arm64
macOS 27 guest on an M3 Max, m3-max-80347). So 79 to 95% of those sessions'
pictures mapped the surface's pages again and had the arm import them again:
4,233 lent-view imports for 5,057 pictures in the M3's acceptance boot.

A decoder or encoder now keeps 32 views, past the measured pools with room for
a stream that keeps more reference pictures. A kept view holds a mapping of
guest RAM and the arm's import of it, no copy, and the surfaces never moved to
other pages, so keeping more costs no bytes moved. The keeping is split out of
view_of as kept_or_made, whose tests lend a pool of 14 in rotation and pass the
bound.

What changes for the guest: nothing it reads; each picture of a movie's
hardware decode lands without a new mapping and import of its surface.
2026-12-02 15:12:02 -08:00
Anees Iqbal 71921f93b2 🐛 Keep a cache's buffer current while a texture lies over it
In the per-shape form a guest texture that takes no shape (a 4:2:2,
compressed or depth format over an IOSurface, or one whose shape the
platform refused) lies over the device cache's buffer itself, while the
other textures over the surface are views of the shapes' images. Nothing
kept the two in step: a read through the unshaped texture missed what the
shapes held and the buffer lacked, and a write through it never reached the
shapes, so the guest read stale texels through either.

What changes for the guest: while such a texture lives, a write through any
texture over the surface is visible through every other one to the next
encoder, as on the Macs (dgpu-oracle.md, Q37).
- A command buffer that uses the cache has the dirty shapes copied into the
  buffer before it runs, as a video one does.
- At the end of an encoder that may have written a shape, the shape's whole
  extent goes into the buffer too, whether or not another shape takes it
  (counted unshaped_out).
- At the end of an encoder that may have written the buffer through such a
  texture (a blit's destination, a render pass's attachment, or, outside a
  blit encoder, one whose usage lets a shader write it), each shape over the
  bytes it covers that a texture references or that holds a write takes the
  buffer's bytes, after the writers' fence, and the rest go (counted
  unshaped_in).

Each such texture, and each view of one, holds its cache (Unshaped), so only
a cache with a live one pays for the copies.
2026-12-02 15:12:02 -08:00
Anees Iqbal 975aa9d49a 🐛 Name a residency set's argument-buffer texture writes on arm64
On arm64 guests a residency set makes an IOSurface texture resident with no
use naming it, and a draw or dispatch can write it through an argument
buffer. The bundle named such a texture used, not written, so a CPU lock of
the surface did not wait for the write, and the host saw no write at all: the
texture's shape stayed clean, its other shapes stale.

What changes for the guest: where an encoder's function may write a texture
through an argument buffer (its interface says so, or no interface is at
hand), the bundle names each shader-writable IOSurface texture of the command
buffer's residency sets written (RGFX_SURFACE_USE_WRITES), so a lock waits
for the command buffer and sees the write.

What changes on the host: a write the walk did not see is taken as the
block's storage shape's where the block has exactly one and the walk named
none of its views; that shape is marked dirty and the plane's other shapes
owe a fill from the buffer (ShapeTable::take_unseen, counted unseen_taken on
the counts line). With no storage shape or several, the write stays no
shape's, counted as before. The walk records the shapes whose views it named
(Uses::saw_named), so a write the walk judged by a view's access is not taken
again.

Both guest sets are rebuilt from the changed bundle.
2026-12-02 15:12:02 -08:00
Anees Iqbal 4a30fc9fd7 ✅ Seed 15 more of the fuzz's message types to carry out
After the creates were seeded, 25 types the messages target fuzzes were still
carried out 0 times. Among them was every type that reads or maps guest memory
or surfaces: BUFFER_OVER_PAGES, HEAP_OVER_PAGES, PAGES_BUFFER_ADDRESS, the
MANAGED_* creates, TEXTURE_FROM_IOSURFACE and HEAP_OVER_POOL. Also among them:
LIBRARY_FROM_REGION, LIBRARY_LOOKUP, TEXTURE_VIEW, ICB_WRITE and the function
handle and table messages. Their objects, guest pages, surface and pool are
rarely right in fuzzed words, so their paths, and every message mutated from
what they make, went unfuzzed.

setup now gives the context 20 pages of guest RAM and three pages blocks: one
run, two runs, and an IOSurface's. Over them it makes:
- a keyed library and a compute pipeline of its functions;
- a function table and handle;
- a compute and a render indirect command buffer;
- buffers and heaps over the pages and over the region;
- a buffer over the surface's pages.
The messages target runs over a Shared pool of the process's own memory, on a
clock that stands still. Each case takes a block of the pool for its context
and gives it back at its end. The types above join the seeded ones, made
well-formed over these objects, for 21 in all. The target fails where a seeded
type is never carried out.

Tests (m3-max-80400, homelab-um870-1, fake platform):
- The fuzz's six targets pass. Over 384 cases, the messages carried out each
  seeded type 63 to 149 times, and nothing faulted.
- Red, with the seeds replaced by fuzzed messages: the target fails, naming
  16 seeded types never carried out.
- The messages target takes 4.3 s. In m3-max-80350's timing its two slowest
  cases, 1.2 s each, make function tables of 0x844_d668 and 0x84e_87e0
  entries, which the fake holds at 16 bytes an entry.
- rustfmt is clean on the file.

Of the types the fuzz picks and does not seed, these are still carried out 0
times: 0x216, 0x219, 0x21b, 0x21c, 0x21d, 0x230, 0x234, 0x235 and 0x23b. 0x214
is now carried out 3 times.
2026-12-02 15:12:02 -08:00
Anees Iqbal bd97ee5905 🐛 Answer nil in the fake for a function table rt refuses
The fake made every visible function table a pipeline was asked for, with a
vector of `function_count` entries. A guest's count of 0x40a3_ca00_0000_0000,
which the fuzz's messages sent, overflowed the vector's capacity and panicked
the test. rt refuses a table whose words, its header and then four bytes an
entry, pass MAX_BUFFER_LENGTH (Refusal::BufferTooLong), and the Vulkan platform
answers nil for it.

The fake now matches rt. It answers nil by the same rule, read from rt's own
function_table_entry_offset and MAX_BUFFER_LENGTH, and still logs the call.
a_function_table_rt_refuses_is_nil pins the rule's edge and the nil answers.
2026-12-02 15:12:02 -08:00
Anees Iqbal 908ce16888 ✅ Ask the linear SPI's levels end of levels its size holds
The death test of the linear SPI's levels asked 7 levels of a 16 x 16
texture, which holds 5, so the descriptor's own validation ended the process
first, in other words, and the test failed against the end it was written for
(m3-max-80351). It asks 3 levels now, which the size holds, so the linear
form's end is the one it meets.
2026-12-02 15:12:02 -08:00
Anees Iqbal 4a61b65037 🆕 Add oracle_aborts and Q52, where Metal ends what the bundle refused
The probe asks each GPU what Metal answers at the calls where the bundle
answered nil or refused while Metal may end the process: the linear SPI at more
than one level, a texture over a buffer of rows shorter than its texels' bytes
by every form, a pipeline of a function made by name that declares a constant
(compute, render, mesh, a binary archive's add) and one linking such a
function, a view with a lowest level of detail, and the format view of a
linear 2D array's every slice, each against a control. Q52 records its answers
on the AMD 5300M, the Intel 630 and the M3 Max, which the five commits before
this one follow, and Q11's rows it corrects: a texture buffer's short rows end
the process on the three, and the M3 ends it at that format view.
2026-12-02 15:12:02 -08:00
Anees Iqbal c786702339 🐛 End the process at a format view of a linear array's every slice
A view of a linear 2D array over a buffer named by a pixel format alone, so of
its every slice, answered nil, where the view of a range of more than one of
its slices already ended the process. The M3 Max ends the process at the
format view too (IOGPUMetalTexture's `sliceRange.length == 1`), in the array's
own format, its sRGB twin and R32Uint alike, and makes a view of one slice
(oracle_aborts array.view.*, Q52); neither x86 Mac makes the array.

Both views now end the process, sending nothing, which the host's platform
would end the host's process at; the nil the format view answered is gone with
its log line.
2026-12-02 15:12:02 -08:00
Anees Iqbal cddff63f35 🐛 Refuse a pipeline linking an unspecialised function as Metal does
A pipeline that links a visible function made by name that declares a function
constant was refused with a stage function's validation words in our own error
domain. Metal makes no such pipeline either, but refuses it from its compiler,
never its validation, on the AMD 5300M, the Intel 630 and the M3 Max alike:
nil with "error: cannot lower module with unresolved function constants", in
CompilerError code 2 on both x86 GPUs and AGXMetalG15X_M1 code 3 on the M3
(oracle_aborts linked.required and linked.optional, Q52).

The refusal now carries those words, domain and code, the M3's where the
device answers as an Apple GPU, by every creator and from any of a stage's
lists; nothing is posted, as before.
2026-12-02 15:12:02 -08:00
Anees Iqbal da05fecb42 🐛 End the process at a pipeline of an unspecialised function
A pipeline of a function made by name that declares a function constant,
required or optional, was refused with an error in Metal's words. Metal's
validation of the descriptor ends the process there on the AMD 5300M, the
Intel 630 and the M3 Max alike, with no validation layer: compute (by a
function, by a descriptor, and at a binary archive's add of one), render (its
vertex and its fragment function) and mesh (oracle_aborts kernel.*, render.*,
mesh.mesh and archive.kernel, Q52).

The bundle now ends the process there too, sending nothing
(rgfxEndAtUnspecialised:role:pipeline:device:), at every pipeline creator and
at a binary archive's adds, a tile pipeline's among them, with each stage's
role and the line its validation names on an x86 Mac or on the M3. A pipeline
that links such a function keeps its refusal; the next commit gives it Metal's
words.
2026-12-02 15:12:02 -08:00
Anees Iqbal 4563e35244 🐛 End the process at a texture over a buffer of rows too short
A texture over a buffer's bytes whose rows hold fewer bytes than its texels'
was answered two ways, both off Metal's: a texture buffer's answered nil, and a
2D texture's, by the public form or the linear SPI, and a linear 2D array's
were sent to the host unchecked. Metal's validation ends the process at a
texture buffer's on the AMD 5300M, the Intel 630 and the M3 Max alike, and at
the others' on the Intel and the M3, where the AMD answers nil (oracle_aborts
tbuf.rows, public.rows, linear.rows and array.rows, Q52). The texture buffer's
nil came from rows of 1 byte, where the AMD's nil was likely its alignment
refusal.

Every form now ends the process at such rows, 0 among them, with Metal's words
(rgfxEndAtShortRows), sending nothing: the three's answer for a texture
buffer, and the Intel's and the M3's, inside the envelope on either guest, for
the rest. test_buffer_texture_buffers no longer holds the old nil.
2026-12-02 15:12:02 -08:00
Anees Iqbal 7bb66460f2 🐛 End the process at a linear SPI texture of more than one level
The buffer's linear texture SPI answered nil for a descriptor of more than one
level, where Metal's validation ends the process on the AMD 5300M, the Intel
630 and the M3 Max alike (oracle_aborts linear.levels.2 and .7, Q52), as it does
at the public form, which the bundle already ended the process at. Both forms
now end it with Metal's words (rgfxEndAtLinearLevels), sending nothing; a type
the host does not carry and no Mac's words name still answers nil.
2026-12-02 15:12:02 -08:00
Anees Iqbal eea177e2c8 🐛 Take a carry's zeros to the 16 KiB page's end by where they lie
A host whose page is 16 KiB offers PAGES_16K, as a Mac does to an arm64 guest.
There the arm64e kext names its runs in whole 16 KiB pages: writeRuns takes the
last run to its page's end by its address. A carrying deferral's last run is
RGFX_PAGE_RUN_ZEROS, whose address, UINT64_MAX, is no page's. The sum wrapped,
and the run's length came out one byte past a 16 KiB page, so it was not whole
4 KiB pages. The host refused each such SURFACE_PAGES as not whole guest pages.
The bundle then fell back to a copy of the surface in the device's region,
whose guest-picked GPU address rt cannot keep. The M3's vtacc boots counted 6
rt-gpu-address-unpinned-region each.

rgfxRunsToPageEnd now takes a last zeros run to its page's end by where it lies
in the span, after the runs before it. The runs then sum to the 16 KiB length
postPages sends. For the guest: a carrying deferral on a 16 KiB-page host is
taken, not refused, so the surface keeps its own pages and its guest-picked
address. x86-64 guests and 4 KiB-page hosts never round, and are unchanged.

pages_block_test pins a carry's runs at a 16 KiB-whole length and at one that
is whole only in 4 KiB pages, with page 0 or page 1 resident.
guest/prebuilt-arm64e is rebuilt, and its ReimsGraphics changes. guest/prebuilt
keeps its bytes and records the new header.
2026-12-02 15:12:01 -08:00
Anees Iqbal 118453efff 🎨 Wrap a recorder test line as rustfmt lays it out
The lint leg of the recorder fix found one line past the width rustfmt
keeps. Nothing else changes.
2026-12-02 14:59:51 -08:00
Anees Iqbal 4c90469746 🐛 Keep one comparison point for host bytes two recorded objects share
The recorder kept its comparison points (the bytes the stream holds of each
4 KiB chunk) per target: a block, or a buffer of host memory of its own. A
no-copy buffer the host makes over a block's pages (a pool buffer, which the
stream names by its own id and a player places in the block) had points of its
own over the block's bytes. A write through it changed what a player holds
there, but left the block's points as they were. So a later write of the guest
through the block, of bytes equal to the block's stale point (the GPU's bytes
of a read-back, taken at its completion with no write), was left out of the
stream, against REPLAY-STREAM.md section 6. A player then ran the next commit
on the pool buffer's bytes there: in a first-time setup walk, vertex floats a
kernel read as its loop counts (lavapipe spun; the 780M lost its device).

Each target's place in host memory is now known to the points. Where a write
or a completion moves a target's points, every other target's chunks over any
of those bytes lose theirs, so the next commit that reaches them through that
target writes them. A replay now holds, at each commit, the bytes the guest
left in every chunk the command buffer reaches, whichever object named them
last. Streams grow only by those chunks, written again where the guest moves
between the names.
2026-12-02 14:54:01 -08:00
Anees Iqbal 58fb475b6c 📦 Rebuild both guest kext sets for reused context numbers
The kext now gives a context's number out again once its close is answered
(1155), so ReimsGraphics is rebuilt in the x86-64 set and the arm64e set, with
their records of the sources they were built from.
2026-12-02 14:35:27 -08:00
Anees Iqbal bcd48cd69f 📝 Record that Metal orders no write across aliased no-copy buffers
The host's runtime holds two imports of the same guest pages for two pages
blocks that overlap, and its hazard tracking does not tie them together
(row 403). oracle_aliasbuf asks what Metal does with a write through one
no-copy buffer and a read through another over the same pages: the M3 Max
never orders the read after the write, not even in the next command buffer
of the queue; the 5300M does not before a blit's read; the UHD 630 orders
every encoder (m3-max-80200, 80202 and 80204). Metal's tracking is the
resources', and the Macs differ past it, so the runtime's answer is the
M3's. dgpu-oracle.md Q51 holds the table, and overlaps.rs's doc the fact.
Nothing changes in what the host does.
2026-12-02 14:31:10 -08:00
Anees Iqbal 7b1b718b21 🐛 Lift held keys as a window's move, size or menu starts on Windows
Moving or sizing a window on a Windows host, or opening its system menu,
runs a modal loop of Windows' inside the window's message, which holds the
UI thread until the loop ends. SDL lifts its own keys as the loop starts,
but their ups reach the window's input only once the loop ends (read from
SDL 3.4.18's WIN_WindowProc), so a key held in the guest stayed held there,
repeating, for as long as the person dragged the window or kept the menu
open.

The UI thread now sets SDL's Windows message hook, which SDL calls with
WM_ENTERSIZEMOVE and WM_ENTERMENULOOP before its reset: the window's input
lifts every key and button it holds and sends their ups at once, capture
kept, and SDL's own ups send nothing when the loop ends. For the guest, the
held keys and buttons come up as the move, size or menu starts instead of
when it ends. features.md's entry says so, with its tests and a manual walk
on a Windows host.
2026-12-02 14:31:10 -08:00
Anees Iqbal 054f8a71d0 🐛 Pause a VM where an NVMe or firmware-variable write fills the disk
The fork's nvme device completed a write that found the host disk full to the
guest as Write Fault, and pflash_cfi01 logged 'Could not update PFLASH' and
dropped the variable. Both now follow the drive's error action: under -drive's
default werror=enospc the VM pauses (io-error, the drive's io-status nospace,
which reims-ctl reads to name the file), and the resume runs the write again
(fork 51d47e28, 1e223049, 0beafad0).
2026-12-02 14:31:10 -08:00
Anees Iqbal 81c12ee542 🐛 Give a context's number out again once its close is answered
The kext gave each process's context a number once, counting up from 1, and
never again. A number is the top 24 bits of the context's 64-bit object ids
(RGFX_CONTEXT_OBJ_ID_SHIFT) and of its doorbell page's bind, so the 2^24th open
of a boot carried ids past 64 bits, onto other contexts' ids.

Numbers now run below 2^24, in turn from where the last was taken, wrapping
past the last to 1 and skipping those held. A number is held from its open
until both the device has answered its close OK (no framebuffer started, or a
late answer, counts as well; a refused close keeps it) and its user client is
freed, so no call of the client's, and no create it posted behind its close,
can reach the device once another process takes the number. Where every number
is held, or the 2048 the kext keeps, the open is refused with
kIOReturnNoResources, as when no unit of GPU addresses is free: the bundle
answers that process no Metal device, and a later open takes a number once one
is given back. A live number is never given out twice.

context_numbers_test pins it near the top: the last numbers below 2^24, the
wrap to 1 past those held, a number reused only after both holds drop, and
every number held refused with nothing changed.
2026-12-02 14:31:03 -08:00
Anees Iqbal 908fd6f1ef 🐛 Hand a closed context's queue destroy before its close, or never
A queue's service thread hands the host its queue's OBJECT_DESTROY when its
loop ends, in no order against its context's CONTEXT_CLOSE. A thread held in a
command buffer while the guest destroys the queue and its process closes went
on to hand that destroy after the close was answered, and once the kext gives
the context's number to another process (the next commit), such a late destroy
could end that process's queue of the same id.

The close now marks every queue of its context whose thread has not yet handed
its destroy, a queue the guest destroyed first among them, under a lock of the
queue's that the thread hands the destroy under: the destroy reaches the host
before the close, or not at all, as the host drops the queue with the
context's objects at the close. Pinned by
a_closed_context_s_queue_hands_no_destroy_after_the_close, which fails with the
check taken out (the destroy handed after the close).
2026-12-02 14:31:03 -08:00
Anees Iqbal 20377861a8 🎨 Format the batch's new lines and name the caps table's row type
rustfmt joins two assignments the batch's commits left split, and clippy's
type_complexity refuses the VideoToolbox caps table's inline tuple type, so the
table's row gets a type of its own. Nothing changes for the guest or the host.
2026-12-02 14:19:14 -08:00
Anees Iqbal 5920d183db 📦 Rebuild both guest kext sets for linked constants and views
RgfxGate carries the Metal bundle, which now refuses a pipeline that links a
function made by name that declares constants, and ends the process at a
view of several slices of a linear 2D array. make -C guest prebuilt and
prebuilt-arm64e rebuilt both sets from this tree (m3-max-80177), and
prebuilt-check passed on them.
2026-12-02 14:03:22 -08:00
Anees Iqbal 7399b4fc60 🐛 End the process at a view of several slices of a linear array
A view of a range of more than one slice of a 2D array over a buffer, made
by the linear form, answered nil. Metal asserts at it on the M3 Max and an M4,
plain and validated ("sliceRange.length == 1", measured by metal2vulkan), and
neither x86 Mac makes such an array, so every Mac on record ends the process
there. The bundle now ends it too, before anything is sent, after the view
rules both x86 Macs share.

A view of every slice named by its pixel format alone still answers nil:
Metal's answer for that form is not measured, and it goes to the oracle
probe.

For the guest: a process that asks for such a view now ends at the call, as
on a Mac, where it went on with nil. The shell test that held the nil keeps
only the pixel-format form, and a death test checks the range.
2026-12-02 14:03:22 -08:00
Anees Iqbal 4b7790b4ef 🐛 Make a linked function with its constant values, none too
A linked function made with constant values that set none of the constants
it declares, or by a descriptor without values, options or a specialized
name, reached the host with no constants. The host then made it by its name,
and the Vulkan runtime refused the pipeline that linked it, where Metal makes
that pipeline and the function reads its unset constants as undefined. Stage
functions were fixed the same way in e6d1572dd5. This was the last path that
still made a function by name.

The host now makes each linked function as it makes a stage's function: with
its constant values, even when there are none. That covers pipelines and
function handles. A function made by name that declares constants would then
be made with them undefined. So the bundle now refuses a pipeline that links
such a function, as it refuses one of such a stage function, in the same
words with the role "linked function", and sends nothing. Metal's answer for
a linked function made that way is not measured; the host's runtime refused
that pipeline before this change too.

For the guest: a pipeline that links a function made with values that set
none is made, and the function reads its unset constants as undefined, as on
Metal. The decoder test links tests/shaders/linked_optional.metal's function
by name, sent with no constants and then with one, on the Vulkan platform.
The two fake-platform tests that held the by-name make now expect the make
with constant values. The bundle's shell test checks the refusal in each list
of each creator, and the record sent for a function made with no values.
2026-12-02 14:03:22 -08:00
Anees Iqbal 5b1067a787 📝 Say Metal leaves a write into read-only memory undefined [ci skip]
No header of the macOS 27.2 SDK states what a GPU write into memory a
process maps read-only, or into a no-copy buffer of bit 24, does:
MTLDevice.h says only that newBufferWithBytesNoCopy wraps an existing part
of the address space, and bit 24 is no public MTLResourceOptions value. The
accuracy ledger's read-only-pages-written entry now says so, and words the
known gap as the planner ruled it: a GPU write into memory the guest mapped
read-only stays visible until the next commit that uses the copy.
2026-12-02 13:57:07 -08:00
Anees Iqbal 0c22ebdbd4 📝 Name the video crate's VideoToolbox module and its check [ci skip]
The video crate gained a macOS module, videotoolbox, and reims-vgpu its arm,
graphics/videotoolbox.rs, with the Mac host's decode. AGENTS.md's "Where
things are" named only the Linux and Windows modules and arms, and the
checks table had no check for the new module: a change to it or its arm is
checked by tools/vt-check.sh on a Mac, which decodes its streams on the
hardware against ffmpeg's MD5s.
2026-12-02 13:56:31 -08:00
Anees Iqbal 5deffb45a2 📝 Record the arm64 guest's boot on the M3 for the Mac arm [ci skip]
An arm64 macOS 27.0.1 guest's boot on the M3 (m3-max-80121) decoded seven
H.264 and HEVC streams to ffmpeg's MD5s on the arm and played and recorded a
movie of each codec with no bad frame, so formats.md's H.264 and HEVC Main and
Main 10 cells name it, and D29 gives its count of GPU-copied pictures and KiB.
formats.md also names the arm's caps_of among the arms' caps.
2026-12-02 13:55:34 -08:00
Anees Iqbal c83dc74d31 📝 Say which video caps the Mac arm writes [ci skip]
devices.md's Mac arm paragraph now says which caps entries the arm writes and
that the arm64 kext serves its paravirtual decoders from them.
2026-12-02 13:55:34 -08:00
Anees Iqbal 089a49ab6d 🐛 Write the VideoToolbox arm's video caps for the guest's kext
The arm64 kext serves its paravirtual VideoToolbox decoders only where the
device's video caps hold an H.264 or HEVC decode entry with a profile
(rgfxVtServesDecoders), so with no caps written an arm64 guest on a Mac host
decoded in software. The arm now writes one decode entry per codec the host's
hardware decoder answers a profile of: H.264 Baseline, Main and High at level
6.2 and HEVC Main and Main 10 at level 6.2, with NV12 where a 4:2:0 8-bit
profile is offered and P010 where a 10-bit one is, all from the probe's
answers.
2026-12-02 13:55:34 -08:00
Anees Iqbal f9af79118f 📝 Document the VideoToolbox arm on Mac hosts [ci skip]
devices.md says what the arm offers, how the host answers it and how a
picture lands; formats.md fills the M3 Max's column and narrows N2 to what is
not built; bugs.md records the GPU copy as D29 with its bytes a picture; and
conventions.md and answer.rs name the arm's counts' codes.
2026-12-02 13:55:34 -08:00
Anees Iqbal 795a9d417f 🐛 Run vt-check.sh under macOS's bash 3.2
An empty array expanded under set -u stops bash 3.2, the system's, which a
job's shell on the Mac is: every 8-bit stream's encode failed. The arrays now
expand as ${a[@]+"${a[@]}"}.
2026-12-02 13:55:34 -08:00
Anees Iqbal a90f1cf70e ✅ Make vt-check.sh's streams in a step of their own
--make writes the streams and their references and decodes none, so the
encoders run in a job that holds no GPU and only the decodes hold the Mac's.
2026-12-02 13:55:34 -08:00
Anees Iqbal 5eff748db4 ✅ Check VideoToolbox's hardware decoders against ffmpeg
The planner's acceptance of the Mac arm asks for MD5 conformance.
tools/vt-check.sh writes the streams of h264-check.sh and hevc-check.sh of
each profile, chroma format and depth the arm offers, with their encoder
options, decodes each on a session that requires the hardware decoder, and
compares its frames with ffmpeg's MD5s, or x265's reconstruction where
ffmpeg's decode differs, as hevc-check.sh does. lib.sh now says it serves the
decoder checks, not VA-API's alone.
2026-12-02 13:55:34 -08:00
Anees Iqbal 7bc2e12d27 🎨 Format the VideoToolbox modules
rustfmt's layout of the new modules and their tests.
2026-12-02 13:55:34 -08:00
Anees Iqbal e336b6503b 🐛 Decline a VideoToolbox stream unless its profile is offered
declines matched a stream by chroma format and depth alone, so an HEVC range
extensions stream at 4:2:0 and 8 bits passed on Main's offer and failed only
at its first decode, where the host's session refused it. The host answered
for a profile, chroma format and depth together, and a stream is now taken
only where one offer has all three.
2026-12-02 13:55:34 -08:00
Anees Iqbal 34a4454cb4 🆕 Count the VideoToolbox arm's GPU copies and their KiB
The planner's ruling records the GPU copy as a known gap with its bytes
(docs/video/bugs.md, D29) and gates the CPU's copy as a degradation.
video-vt-pictures-gpu-copied and video-vt-gpu-copied-kib count each picture
the GPU copied and its rows' KiB, and the CPU's code becomes
video-vt-pictures-cpu-copied, named as the other arms' picture codes are.
2026-12-02 13:55:34 -08:00
Anees Iqbal 21d98b1e8a ✅ Test the VideoToolbox arm on the hardware
The decoder keeps one command queue for its copies, where one was made for
each picture. The ignored test lands a stream's pictures through the arm into
a lent surface's pages, in VideoToolbox's layout (one copy a plane) and at
rows 256 bytes wider (one a row), and by the CPU's copy with no buffer handed
over, each byte against VideoToolbox's own read back and the bytes outside
the planes untouched (m3-max-80012: H.264 8-bit, HEVC Main 10, H.264 High 10
and HEVC Main 4:2:2 10).
2026-12-02 13:55:34 -08:00
Anees Iqbal a163d6d703 🆕 Land a Mac host's VideoToolbox pictures by one GPU copy
reims-vgpu's new graphics::videotoolbox arm serves an arm64 guest's
paravirtual decoders on a Mac host. It lists the probe's answers by profile
at each codec's top level, declines any other stream at its session's start,
and copies each picture from a buffer over VideoToolbox's IOSurface into the
Shared buffer over the guest's lent surface on the device's GPU: one copy a
plane where the pitches agree, else one a row. VideoToolbox takes no memory
of the caller's for its pictures, so the copy is the one a picture the
planner accepted. The CPU's copy through the host's view of the pages is the
fallback, counted and logged once a reason.

GuestDecoder gains lands_by_gpu, so vt.rs hands the buffer over for every
surface of such a decoder, and GraphicsVideo gains guest_decoder_list, so the
arm's decoder list comes from its offers, not from caps it does not write: no
x86-64 guest runs on a Mac host.
2026-12-02 13:55:34 -08:00
Anees Iqbal 17b2563593 🆕 Ask the host which streams its VideoToolbox hardware decodes
VideoToolbox lists no profiles of its decoders. The probe makes a session
that requires the hardware decoder for each stream the arm would list (H.264
Baseline, Main and High at 8 bits and High 10; HEVC Main, Main 10 and Main
4:2:2 10), from parameter sets of its own for a 64x64 picture, and the host's
answer is the sessions it makes, so the arm offers only what the host takes,
with no model names in code. The M3 Max makes all seven (m3-max-79934).
2026-12-02 13:55:34 -08:00
Anees Iqbal dc3cb7a54c 🎨 Drop two VideoToolbox bindings nothing calls
kCVPixelBufferLock_ReadOnly and kCFAllocatorNull were bound for a read path
the session does not take, and warned as unused.
2026-12-02 13:55:34 -08:00
Anees Iqbal 64b213723f 🆕 Decode H.264 and HEVC on VideoToolbox's hardware on a Mac host
A Mac host had no video arm, so an arm64 guest's paravirtual VideoToolbox
decoded in software there (owner 3447). The video crate's new videotoolbox
module, built on macOS, makes a decoder session that requires the hardware
decoder from a stream's parameter sets, for a destination of the guest's own
buffer attributes (its format and size, rows aligned to 64 bytes and planes to
256), decodes each access unit synchronously, and hands out the picture's
IOSurface and its planes. The bindings are hand-written extern "C" of
VideoToolbox's, CoreMedia's, CoreVideo's, IOSurface's and CoreFoundation's C
API: no new crate. Its ignored test decodes a stream on the hardware against
ffmpeg's framemd5 (m3-max-79925).
2026-12-02 13:55:33 -08:00
Anees Iqbal cba3a88875 📝 Say a pinned bit-24 buffer takes writes as the x86 Macs do
A no-copy buffer or heap of option bit 24 pinned in a known block of
writable pages keeps the GPU's writes. The docs and the line counted under
rt-no-copy-read-only said Metal's GPU drops them, which is the M3 Max's
answer alone: on the 5300M and the UHD 630 bit 24 does nothing, and every
GPU write lands in the buffer's pages (dgpu-oracle.md, Q38). The case is
inside what the Macs answer, so nothing changes in what it does; the docs,
the accuracy ledger and the line now say whose answer it is.
2026-12-02 13:51:13 -08:00
Anees Iqbal c8f98646a2 🎨 Name the copy's rounds queues for clippy's type complexity
copy_on's last argument, the rounds' queues beside whether it ends its
encoder, is a type clippy's type_complexity refuses under -D warnings: a
type alias names the queues.
2026-12-02 13:51:13 -08:00
Anees Iqbal c2701670ab ✅ Probe a texture's synchronize on an IOSurface
oracle_iosurface gains three steps: sy (a blit's synchronizeResource: of the
process's texture, alone in its command buffer), and gws and gcs (a blit's
write and a render pass's clear, each followed by synchronizeResource: in
the same command buffer). sync365.txt runs them against a control with no
synchronize: the 5300M answered (m3-max-79926) that after the synchronize
and the buffer's completion a read with no lock sees the GPU's write, and
without it the old bytes until the surface's lock. The host's synchronize
copy follows that answer.
2026-12-02 13:51:13 -08:00
Anees Iqbal 89c0e11caa 🐛 Copy a synchronized surface's write into its pages in the encoder
A guest's synchronizeResource: or synchronizeTexture:slice:level: of a
texture over an IOSurface did nothing on the host for a cached surface: the
write stayed in the device cache (or the texture's shape image) until a CPU
lock asked for a download. A Mac's synchronize makes the write reach the
surface's memory once the command buffer completes: measured on the 5300M
(macOS 26.7.1, m3-max-79926), a read with no lock saw the GPU's write after
the command buffer completed when it synchronized, and the old bytes until
the surface's lock when it did not.

What the guest sees now: after synchronizeResource: (or
synchronizeTexture:slice:level:) and the command buffer's completion, a read
of the IOSurface with no lock sees the GPU's write, as on the 5300M.

The walk encodes the copy at the sync op, inside the guest's own blit
encoder, after the work before the op: the shapes the walk saw written so
far and the dirty ones go into the cache's buffer (which takes the pages
first where a straight fill left it lacking them), and the buffer goes into
the pages, through their view or by their runs. Where the pages are
copied (staged), the copy goes into staging pieces, and the CPU lands them
in the pages once the command buffer completes, before its CB_COMPLETE is
posted. The cache keeps its record, so the next download copies the write
again. A refused copy fails the command buffer as a refused download
would. Counted as synchronized.
2026-12-02 13:51:13 -08:00
Anees Iqbal 0898313d14 🐛 Answer raster order groups only where rt orders them
The device answered areRasterOrderGroupsSupported yes on every host, the
M3 Max's answer. But rt's translator orders a fragment function's raster
order groups only inside the fragment shader pixel interlock, and refuses
a pipeline of them on a device without it. An RX 550 on RADV (Mesa
26.2.6) reports no pixel interlock, so a guest there that was told yes
had its raster-ordered pipelines refused.

The device now answers yes where rt's device creation enabled
fragmentShaderPixelInterlock, and no elsewhere, as Metal has a GPU
without raster order groups answer; the bundle's SPI raster order groups
feature follows the same flag. The answer stays yes on the 780M, the RX
7900 XTX, the Iris Xe and the NVIDIA cards, and is now no on the RX 550
(RADV POLARIS12) and on a Mac host over KosmicKrisp, which lists neither
VK_EXT_fragment_shader_interlock nor the feature. x86-64 and arm64 guests
read the same flag, so both are told no there.
The AMD Radeon Pro 5300M and the Intel UHD 630 answer yes (macOS 26.7.1,
oracle_caps, potluck jobs m3-max-79873 and 79874); neither lacks them.
raster_order_groups_are_rt_s_answer holds the answer; no test held the
old one.
2026-12-02 13:49:00 -08:00
Anees Iqbal cd29f248e3 ✅ Seed the fuzz's messages with creates that carry out
The messages target fuzzes every type ring 0 carries out, but six creates
never got past the decoder's first checks at random: a texture's resource id
and pixel format, a heap to place a buffer in, a buffer to lay a texture
over, and a pipeline's library and function names are rarely right in
fuzzed words. In m3-max-79886's run TEXTURE_CREATE, BUFFER_AT_OFFSET,
TEXTURE_FROM_BUFFER and the render, compute and mesh pipeline creates were
carried out 0 times in 98 to 115 tries each, so their make paths and every
message mutated from a made object of theirs went unfuzzed.

setup now also makes library 9 (bytes the fake platform takes as a library,
which finds every function name) and placement heap 10 (1 MiB, Private), and
one in four of the messages not mutated from earlier ones is a well-formed
create of one of the six (seeded) over setup's objects: a 64x64 BGRA8
texture, a Private buffer at a page of the heap, a texture over buffer 2's
first bytes, or a render, compute or mesh pipeline of the library's
functions. What the decoder carries out of them joins the case's messages
that later ones are mutated from. The target now also fails where a seeded
create is never carried out.

Tests (m3-max-80112, homelab-um870-1, fake platform): the fuzz's six targets
pass; the messages carried out each create 238 to 378 times over 384 cases.
Red, with the seeds replaced by fuzzed messages: the target fails, naming
the render, compute and mesh pipeline creates (0 carried out); the other
three were carried out 1 to 3 times, through setup's new library and heap.
rustfmt is clean on the file.
2026-12-02 13:45:15 -08:00
Anees Iqbal 65cbf3220e 🐛 Make a pages block's view after its answer on a worker of its own
Where the guest took IMPORT_ADDRESSES_LATER, a pages block's SURFACE_PAGES was
answered as soon as its runs were carried out, and its view was then mapped
and imported on the same surface worker job before the block settled. The
surface worker runs at most four threads, so four blocks' view makes held
every thread, and the next block's SURFACE_PAGES waited for one behind them,
however short its own carry-out. On the RTX 3090's gcl boot (rowb-3090,
m3-max-79853) carry-outs took at most 2.1 ms, view makes 14.9 ms at the
median and up to 351 ms, and 64 answers took over 50 ms, up to 133 ms: of the
225 over 20 ms, 163 waited while four or more other blocks' views were being
made.

The view made after the answer now runs on the views worker
(reims-vgpu.graphics-views-<i>), a worker of its own under the block's key,
which holds the block's settle until the view is made: the messages that
name the block wait for it as before, and the surface worker's thread goes
on to other blocks' SURFACE_PAGES. A job of the block's on the surface worker
(its BUFFER_OVER_PAGES, or its next SURFACE_PAGES) that finds one of the
block's on the views worker runs behind it there (Worker::behind, one step
under the worker's lock), so the block's jobs keep their order across the two
workers; a SURFACE_PAGES run there makes its view itself, so no views
worker's job hands one to the views worker. The views worker runs at most
POOL_THREADS (4) threads, as every worker does, and holds at most
VIEWS_WAITING (256) jobs waiting (Worker::bounded): a hand-over that finds
that many waits on its surface worker's thread until one is taken, counted
and logged at debug. The busiest 100 ms of the same boot carried out 140
SURFACE_PAGES. No setting changes either number. The view's make takes the
reset gate shared, recursively, as the surface worker's jobs do, and where
the device was reset since the SURFACE_PAGES' begin it makes nothing.

What the guest observes: a LATER SURFACE_PAGES is answered without waiting
for other blocks' views; its own block's later messages wait for its view as
before. What the host observes: raise_interrupt may come on a views worker's
thread (a SURFACE_PAGES or a BUFFER_OVER_PAGES run behind a view there posts
its answer or its command buffer's failure), named in reims_vgpu.h, api.md
and RAISE_THREADS. QEMU's raise_interrupt callback takes a call from any of
the library's threads (the irqfd's write, the WHPX request under msi_lock, or
a BH), as it does from the surface workers', so its side needs no change.
Nothing changes where the guest did not take IMPORT_ADDRESSES_LATER.

Tests:
- a_pages_block_s_answer_waits_for_no_other_block_s_view: four blocks' view
  imports held, a fifth block's SURFACE_PAGES is answered, no surface worker
  cap hit, the views worker at four threads, and a BUFFER_OVER_PAGES over a
  held block made only after its view.
- a_reset_ends_pages_views_made_after_their_answers_cleanly: a reset waits
  for the view being made; the view waiting on the views worker and the
  buffer behind it make nothing after the reset; both blocks settle.
- a_device_released_while_pages_views_are_made_after_their_answers_ends_clean:
  the release waits for neither view, and the device's control goes once
  both views' jobs end.
- worker: a_bounded_worker_s_hand_over_waits_for_room,
  a_job_behind_a_key_runs_after_its_jobs_or_here_where_it_has_none.
2026-12-02 13:39:08 -08:00
Anees Iqbal fac853ad75 📦 Rebuild both guest kext sets for the refused-writes queue
make -C guest prebuilt and prebuilt-arm64e on the M3 (job m3-max-80045) at
the class's tree. In both sets, RgfxGate's Metal bundle now keeps every write
the kext refuses in one queue until it goes, failing commits behind it with
MTLCommandBufferErrorInternal. Nothing else in the sets changed: Graft and
ReimsGraphics are byte for byte as before.
2026-12-02 13:39:07 -08:00
Anees Iqbal 3d37c928b4 🐛 Keep every write the kext refuses in order until it goes
A refused write into an object was lost. An indirect command buffer's
records and slots and a visible function table's entries were dropped with a
log line, and a shared event's setSignaledValue: was dropped with none. The
kext refuses a control-ring post once its ring has stayed full for 5 s, or
once the device has stopped. Later command buffers then ran the ICB's old
commands or the table's old entries. A buffer already posted that waited on
the event's value never ran, even once the host read again.

Row 318's queue of refused Managed notes now holds every such write, in one
first-in-first-out order: ICB_WRITE, ICB_SLOTS(_IN_PAGES), FUNCTION_TABLE_SET
and SHARED_EVENT_SET_VALUE besides the range, region and didModifyData. A
waiting write is posted before the next write, a destroy or a commit, and
from a timer once a second while any waits. The timer means an event's value
still reaches the host when nothing else is posted. A destroy now waits behind
the waiting writes, since a record or a table entry may name its object, and
drops the writes into its own object. A refused ICB_SLOTS of several buffers
waits as one message for each buffer. The device's stop ends the timer and
drops what waits.

What changes for the guest: while such a write waits, a commit fails its
command buffer unposted with MTLCommandBufferStatusError and
MTLCommandBufferErrorInternal, as for a refused Managed note before. Once the
kext takes posts again, the writes go in order before the next buffer. At
most 4096 writes or 16 MiB wait. Past that, a write is lost and every later
commit fails Internal. After the device's stop every commit fails the same
way. A write is never dropped while later work runs. Nothing changes where
the kext takes every post.
2026-12-02 13:39:07 -08:00
Anees Iqbal 5c9f944bee 🐛 Copy a decode's coded rows below its crop into the pages
What the guest sees now: after a decode into an IOSurface whose device
cache knows the surface's layout (the kext gave it, or a decode wrote the
surface whole), where the decode op says the surface holds the coded
picture's rows past its crop (output_rows), a download or a release copies
those rows into the pages too, as far as the surface holds rows for each
plane: a 1080p 420v output's luma rows 1080 to 1087 and chroma rows 540 to
543. Before, the cache's copies moved each plane's crop rows alone, so the
pages kept what they held below the crop, where a Mac's decoder writes the
coded rows into the surface. That held both in a cache laid out at the
GPU's pitch (radeonsi's 2048-byte rows for NV12's 1920) and in a cache in
the pages' layout whose layout is known.

From that decode on, a fill moves the same rows into the cache, so both
directions move the same bytes. A decode whose picture lands in the cache's
own surface writes nothing of the buffer and records nothing. A decode that
lands the crop alone by a copy leaves those rows as the cache held them
(the pages' after a fill, else the make's zeros), and the download moves
those. The caches' counts line counts the decodes that widened a cache's
copies. Ledger row 789.
2026-12-02 13:39:07 -08:00
Anees Iqbal 358c9475e1 ⬆️ Build on metal2vulkan development cffa762bda
metal2vulkan-runtime at its development commit cffa762bda: G (9a89d5e25c,
CI only) and the heap-alias fix. A heap texture placed over another's bytes
now leaves the undefined layout at its first use rather than in an upload,
which ends AMDVLK's loss of texels over aliased heap textures. RADV, ANV
and NVIDIA keep their answers; the runtime's public API is unchanged, so
nothing here changes with it.
2026-12-02 13:37:43 -08:00
Anees Iqbal 0f3901bcc3 ✅ Test refused memory on a cache that lacks no pages
187b37f1c9 drops a command naming a cache's buffer that lacks its pages
before its memory is asked. The refused-memory test's shaped cache, whose
first use filled its shapes straight from the pages, met that drop first
and never reached the refused memory it checks. A deferred block's cache,
whose pages are not named, lacks none, so its blit still meets the refused
memory and fails with MTLCommandBufferErrorOutOfMemory. Ledger row 1115.
2026-12-02 13:24:26 -08:00
Anees Iqbal 798fbfc834 🐛 Drop an op naming a cache's buffer that lacks the pages
What the guest sees now: an op that names an IOSurface device cache's
buffer itself, while that buffer lacks the pages its shapes took straight
from them and no begin has readied it, is dropped, and its command buffer
fails with MTLCommandBufferErrorInternal. It used to run over the zeros of
the buffer's memory's make and complete as if it had read the surface.
The op is met inside its encoder, where no copy of the pages can go ahead
of it, so failing the buffer is the one answer that does not hand the guest
wrong bytes as done. It is counted under rt-shape-lacking-named as before,
its first logged, and the buffer's memory stays unmade, so the next copy
through it takes the pages first.

The bundle never names such a buffer: its id goes out only in
TEXTURE_FROM_IOSURFACE creates. The test that held the zeros read becomes
a_command_naming_a_buffer_that_lacks_the_pages_is_dropped_and_fails_its_buffer,
and the copied-through-once test's command now names a deferred block's
buffer, which lacks no pages. Ledger row 1115.
2026-12-02 13:24:25 -08:00
Anees Iqbal d39e13c4cf 📝 Say the guest answers the info's threadgroup memory [ci skip]
The bundle now answers maxComputeThreadgroupMemory from the device info, so
the oracle table's row gives the device info's answer for each guest instead
of the Metal base's 65536. This lands in one batch with the bundle's getter.
2026-12-02 13:14:23 -08:00
Anees Iqbal baf08a4d11 🐛 Give an x86-64 guest's device info its threadgroup memory limit
The device info's max_compute_threadgroup_memory slot carried the
platform's 65536 bytes, Metal's on the M3 Max, on every host, while the
runtime refuses a kernel's threadgroup memory past
maxThreadgroupMemoryLength, which the device answers as rt's told limit
(32,752 or 32,768 bytes). Both x86 Macs answer the two alike, 65536 and
65536 (AMD Radeon Pro 5300M and Intel UHD 630, macOS 26.7.1, oracle_caps,
potluck jobs m3-max-79873 and 79874), so an x86-64 guest's framework may
size a kernel by either.

For an x86-64 guest the slot now holds the device's
maxThreadgroupMemoryLength; an arm64 guest's keeps the platform's 65536,
the M3 Max's pair. No guest reads the slot yet: the guest's
maxComputeThreadgroupMemory is still its Metal base's 65536, until the
bundle answers it from the slot.
compute_threadgroup_memory_follows_the_guest holds the new slot; no test
held the old one.
2026-12-02 13:14:23 -08:00
Anees Iqbal cffdb5cd2b 🎨 Format the texture write rounding test
rustfmt wraps the test's check of the platform's answers, which ran past the
line width.
2026-12-02 13:14:22 -08:00
Anees Iqbal 5a2b9f99f7 🐛 Answer no to the texture write rounding modes
The device answered supportsTextureWriteRoundingMode: yes for modes 1
and 2, the M3 Max's answer. No pipeline create on the wire carries a
rounding mode, so the host's pipelines round as the runtime's default,
toward zero, whatever the descriptor asks: a guest told yes for mode 2
(round to nearest even) got a pipeline that rounds toward zero, and the
bundle logged the mode as unsupported.

The guest's device now answers no for modes 1 and 2, for both guests and
on every host, as the AMD Radeon Pro 5300M and the Intel UHD 630 answer
(macOS 26.7.1, oracle_caps, potluck jobs m3-max-79873 and 79874). The
answer is the lane's, in device_info's table, until a pipeline create
carries the mode to the runtime, which takes it. No test held the old
answer; no_texture_write_rounding_mode_is_carried holds the new one.
2026-12-02 13:14:22 -08:00
Anees Iqbal e3d002fae7 🐛 Answer no to the raw primitive types 5 to 9
The device answered supportsPrimitiveType: yes for the raw types 5 to 8,
the M3 Max's answer, but the runtime draws only the public types 0 to 4
and refuses a draw of any other as a primitive type Metal has none of. A
guest framework told yes would have encoded draws that drew nothing.

The guest's device now answers yes for 0 to 4 and no for 5 to 9, as the
AMD Radeon Pro 5300M answers (macOS 26.7.1, oracle_caps, potluck job
m3-max-79873); the Intel UHD 630 answers yes for 5 to 9 (m3-max-79874).
The answer is the same on every host and for both guests.
a_roomy_device_answers_metal_s_counts held the old answer.
2026-12-02 13:14:22 -08:00
Anees Iqbal bdb649e1e9 📦 Rebuild both guest kext sets for the bundle's stop and rows
make -C guest prebuilt and prebuilt-arm64e on the M3 (job m3-max-79916) at
this stack's tree. In both sets, RgfxGate's Metal bundle now fails a queue's
buffers in flight at the device's stop, ends a commit's wait for ring room
and a queue's finish there, makes no argument encoder of a descriptor value
past 32 bits, fails commits behind a Managed write the kext did not take,
logs a refused IOSurface lock, and answers maxComputeThreadgroupMemory from
the device info. Nothing else in the sets changed: Graft and ReimsGraphics
are byte for byte as before.
2026-12-02 13:14:22 -08:00
Anees Iqbal 972ec67da6 🐛 Answer the device's threadgroup memory in the SPI's getter
maxComputeThreadgroupMemory (MTLDeviceSPI, `Q16@0:8` in macOS 27's
Metal.framework, both slices) came from Metal's base, which answers its
feature profile's 65536 whatever the host takes. Both x86 Macs answer it
the same as maxThreadgroupMemoryLength (the AMD 5300M and the Intel 630,
macOS 26.7.1, oracle_caps).

The device now answers it from the device info's
max_compute_threadgroup_memory slot. What changes for the guest: an x86-64
guest reads the device's maxThreadgroupMemoryLength there (32752 or 32768,
where it read 65536), the same as its own maxThreadgroupMemoryLength. An
arm64 guest sees no change: the host gives it the M3 Max's 65536. With no
device info it answers 32768, as maxThreadgroupMemoryLength does. The host
fills the slot in lane devanswers' commit, which lands in the same batch.
protocol_members.txt lists the getter as implemented, and the caps-blob
test reads the slot.
2026-12-02 13:14:22 -08:00
Anees Iqbal 456e995096 🐛 Fail commits behind a Managed write the kext did not take
A Managed texture's replaceRegion:, a texture's didModifyData and a Managed
buffer's didModifyRange: tell the host to copy the CPU's bytes to the GPU's
copy. The kext refuses a post once its control ring has stayed full for 5 s
(a host that stopped reading), and also once the device has stopped. On a
refusal the bundle dropped the message without a word: the region and
didModifyData always, and the range when the held messages would not fit
with it. Every command buffer committed afterwards read a stale GPU copy.

Such a write now waits in the serializer (postWaitingNotes). It goes first
at the next such write and at each commit, and is dropped when its object is
destroyed. What changes for the guest: while a write waits, a command
buffer's commit fails it unposted with MTLCommandBufferStatusError and
MTLCommandBufferErrorInternal, as a buffer behind a held create already
fails. Once the kext takes posts again, the writes go before the next buffer,
which runs as before. Past 4096 waiting writes, the next one is lost and
every later commit fails. Nothing changes where the kext takes every post.
test_commit_behind_an_untaken_managed_write_fails covers each kind.
2026-12-02 13:14:22 -08:00
Anees Iqbal 39e61b31c0 🐛 Make no argument encoder of a descriptor value past 32 bits
newArgumentEncoderWithArguments: cut each descriptor's data type, index,
array length, access, texture type and block alignment to the wire's 32
bits. So a value past 2^32 wrapped, and the guest got the layout of another
argument where the host, given the value, makes no encoder (rt_platform's
argument.rs counts it as Metal's refusal).

What changes for the guest: such a descriptor now gets nil, logged once,
and the host is asked nothing. Every descriptor within 32 bits gets the same
answer as before. test_argument_encoder_query covers an index, an array
length and a block alignment past 32 bits.
2026-12-02 13:14:22 -08:00
Anees Iqbal 9613ec4fca 🐛 Log an IOSurface lock refused, and what it leaves undone
When an IOSurface's lock was refused, three things were skipped without a
word: a copy view's upload from the pages, the write-back of a CPU write
into the copy, and a cached view's flush of the GPU's writes into the
pages. Skipping is right, as none of them can be done without the lock, but
nothing in the log said so.

lockSurface now logs the first refusal at each of these sites, with the
surface's id, the lock's options, kr and what is left undone. Nothing else
changes for the guest.
2026-12-02 13:14:22 -08:00
Anees Iqbal 0d74acbc81 🐛 Take the ring in a queue's finish where no thread drives it
The queue's finish waited on its committed buffers' group with no deadline
and never took the queue's completion ring. Every other wait for a command
buffer takes the ring itself where no completion thread drives it (none
could be made, or the thread was destroyed). With no thread, the buffers
finish waited for completed only if another thread took their records, so
finish could wait for good.

finish now takes the ring meanwhile as the buffers' waits do
(rgfxWaitFor), looking again every millisecond, and with a driving thread
it looks each second whether the thread has gone.

What changes for the guest: where no thread drives the ring, finish
returns once the host has completed the buffers committed before it. It
used to wait for good. With a driving thread nothing changes. queue_tests'
new test runs finish on an undriven queue.
2026-12-02 13:14:22 -08:00
Anees Iqbal c0dcc030cd 🐛 End a commit's wait for ring room at the device's stop
A commit that found its queue's submission ring full waited for the host to
take from it, with no deadline: on the host's room record where the device
holds SUBMIT_ROOM, else in sleeps between looks. Once the device stopped,
the host took nothing more, and the ring may already be gone from the
process with the context's window, so the committing thread looked at it for
good. The same held for a waiting thread's scheduled ask.

A queue's reader now stops the ring's room events with itself
(RgfxReplyReader::stop). A post waiting for room ends there, and a post
after it answers at once, looking at no ring word and ringing no doorbell
(RgfxRingWriter::post). Every queue now has room events, as the stop's
channel; whether the post waits for room records still follows SUBMIT_ROOM,
so the waiting is unchanged.

What changes for the guest: a commit waiting for room on its queue's ring
at the device's stop returns, and its command buffer fails with
MTLCommandBufferErrorInternal ("Discarded (victim of GPU error/recovery)"),
as a buffer committed after the stop does (previous commit). Before, the
commit never returned. serializer_tests' new test runs the writer's wait
across the stop with and without room records, and queue_tests' new test
runs a commit's.
2026-12-02 13:14:22 -08:00
Anees Iqbal ac7885c79b 🐛 Fail a queue's buffers in flight at the device's stop
When the kext closed a process's completions (the device's stop, or the
context's release), the completion thread ended and left its readers
undriven, so each wait for a command buffer took the queue's ring itself.
No record could come there any more, and the kext also takes the context's
window, the rings in it, out of the process. waitUntilCompleted,
waitUntilScheduled and commitAndWaitUntilSubmitted spun on the ring for
good, -commandBuffer polled it every millisecond for slots the buffers in
flight never gave back, and the queue's finish slept for good, where they
did not read memory the process no longer mapped.

The completion thread now stops every reader at that point, and each one
added after (RgfxReplyReader::stop). A stopped reader reads its ring no
more and fails every command buffer it still awaits, in ring order, as a
GPU recovery's victim. A buffer committed after the stop fails at its
commit, with nothing put on its ring. Such a failure touches nothing of
the buffer's surfaces or copies.

What changes for the guest: at the device's stop, each command buffer in
flight or committed afterwards completes with MTLCommandBufferStatusError
and MTLCommandBufferErrorInternal ("Discarded (victim of GPU
error/recovery)"), the bundle's answer for work a stopped device never
took. Its scheduled and completed handlers run, and every wait for it
returns. Before, the buffer never completed. A buffer committed after
the stop no longer goes on its ring, and its waiter no longer takes
records from the ring.

shell_tests' test_completion_thread_stops held the old behaviour (a buffer
committed after the stop completed from a record its waiter read off the
ring). It now holds the failure, and keeps the ring-taking waiter for a
destroyed thread. queue_tests' new test runs every wait above across the
stop, alone with `shell_tests --waits`.
2026-12-02 13:14:22 -08:00
Anees Iqbal b5eaebe8ee 🎨 Format the refused download and fill tests and their helper
rustfmt breaks the macro calls 3f446e1e70 and 91845d50fe wrote on one line:
the lint job m3-max-79939 failed its rustfmt check on them alone (clippy and
rustdoc, host and Windows, passed).
2026-12-02 13:06:15 -08:00
Anees Iqbal c9e1b356b5 🐛 Fail a buffer whose cache fill gets no command buffer
What the guest observes changes. A fill of a surface's device cache from its
pages, or of a new shape from the cache, that the platform made no transfer
queue or command buffer for was left unmade with nothing said: the command
buffer whose begin asked it ran over the cache's older bytes, or the shape's
zeros, and completed with no error. A fill whose command the platform refused
already fails that buffer with MTLCommandBufferErrorInternal (ac5b41b2ed), so
the fill no command buffer could carry now takes the same answer: the buffer
fails with the internal error, the miss is counted under surface-copy-refused,
and the cache keeps its older generation, or the shape owes its fill still,
for the next use to make. A refused buffer memory keeps OutOfMemory.

This is the fill half of the class 3f446e1e70 fixed for downloads (ledger row
1193). Two fake-platform tests: red at c1de973e24 (m3-max-79907, both failed
on the missing count), green with the fix (m3-max-79910, the surface, shape,
pages, order, command buffer, video and graphics tests, 668 passed).
2026-12-02 13:06:15 -08:00
Anees Iqbal 216197c62a 🐛 Answer a download refused where no copy into its pages is made
What the guest observes changes. A SURFACE_DOWNLOAD whose copy of a device
cache into the surface's pages got no transfer queue or command buffer from the
platform, or whose cache's buffer the platform refused its memory, was answered
RGFX_STATUS_OK at once, over the pages' older bytes: the CPU lock that asked
went on reading what the CPU had last written, without the GPU's writes. rt
answers no command buffer at a wait for room on its own handler thread, where
a download carried out in a writer's finish can ask for one, and on a quiesced
device.

Such a download is now answered failed (RGFX_STATUS_REFUSED, the kext's
existing copy-refused path) where the pages lack a write of the cache's,
counted under surface-copy-refused as a refused copy is since aaedba617b, and
the cache stays written, so the next download or release copies it. A cache
whose buffer holds no memory, so no work wrote it, and whose shapes hold no
write is answered done as before: the pages hold all it holds. A release's
copy so is logged, as a refused one's is.

Ledger row "a SURFACE_DOWNLOAD whose copy gets no command buffer, or whose
buffer memory is refused, is answered done" (audit, 12-02). Two fake-platform
tests: red at b7ff9acca9 (m3-max-79892, both failed), green with the fix
(m3-max-79896, the surface, shape, pages, order and command buffer tests,
411 passed).
2026-12-02 13:06:15 -08:00
Anees Iqbal 5c2ba166a8 🐛 Read a lent surface's run table no further than its surface
A VT_MESSAGE surface that carries its runs in a run table had the whole
table read at once: as many bytes as the table's runs named, up to the
guest's RAM, copied into one allocation. Only the entries up to the
surface's length are used. A guest whose table runs named gigabytes made
the host copy gigabytes for each message.

The table is now read a page at a time from its start, and the reads stop
once the entries hold the surface's bytes. Each read is given the table's
runs from its first byte on.

What changes for the guest: a table whose runs past the entries it needs
lie outside the guest RAM the host maps is no longer refused as malformed,
since the host no longer reads them. Unchanged: a table whose first page
does not read is refused, and so is one whose entries do not hold the
surface's bytes.

Red: read whole (RUN_TABLE_READ at u64::MAX), the new test reads 1 MiB for
a two-entry surface (m3-max-79886). Green: the lent-surface and VT tests
pass (m3-max-79886, um870).
2026-12-02 12:55:26 -08:00
Anees Iqbal c63998ae55 ✅ Fuzz each type ring 0 carries out through the decoder
The decoder's message fuzz picked its types from a list kept by hand. The
list stopped at 0x21d, so it missed QUEUE_CREATE and every type added
since: 14 that decode() carries out never reached it, among them
BUFFER_OVER_PAGES, HEAP_OVER_PAGES, HEAP_OVER_POOL, the ICB writes and
slots, MANAGED_BUFFER_CREATE, TEXTURE_DID_MODIFY_DATA, FUNCTION_TABLE_SET
and BUFFER_ESCAPED. The 15 messages that ring 0 answers through the
decoder's own calls outside decode() fared no better:
- LIBRARY_LOOKUP, HEAP_TEXTURE_SIZE_AND_ALIGN and ARGUMENT_LAYOUT were in
  the list, but went to decode(), which refuses them as unknown;
- SAMPLER_CREATE went to decode()'s own arm, not to the call that answers
  it;
- the other 11 were never picked.

The fuzz now reads its types from the source as it is written: the wire's
constants and the arms of decode()'s match. The answered types are handed
to the same decoder calls that GraphicsControl::handle_stage3 makes. A new
test fails where handle_stage3 routes a type that the fuzz never picks, and
the messages target checks that each type is reached. PIPELINE_ANSWERS is
the one routed type left out: the device's kept answers reply to it, and
no decoder does. With the new types, the 384 cases found no panic.

Red: with the old list, the new test names the 24 types ring 0 carries out
that it never picked (m3-max-79871, m3-max-79880). Green: the fuzz module's
6 tests pass (m3-max-79880, um870).
2026-12-02 12:55:26 -08:00
Anees Iqbal 22cfe51a54 📝 Delete B96; say how each arm decodes resizing VP9 [ci skip]
B96 is fixed: one NVDEC decoder, or one VA context and pool, takes a VP9
stream's frames at every size up to the largest so far. nvidia.md says what
NVDEC still refuses (an inter frame larger than every frame before it, which
libvpx never codes) and lists the new test; vaapi.md says how the context grows,
with radeonsi's wrong frames under a context for each size (potluck jobs
m3-max-79740 and m3-max-79744), and where the resizing stream decodes (a Radeon
780M, m3-max-79777; the Iris Xe, m3-max-79848); backends.md lists the stream.
2026-12-02 12:46:12 -08:00
Anees Iqbal f6955b031f 📝 Cite an arm64 guest's 4:2:2 export on the Iris Xe [ci skip]
The listing of HEVC Main 4:2:2 10 came back with its hold's lift, and its
ordinary proof is a guest's export of that format on the Iris Xe: an arm64
macOS 26 guest's hardware session coded 10 frames at 640x360 that decoded back
frame for frame at 65.1 to 68.3 dB luma and 59.0 to 60.7 dB chroma, with no
engine reset in the host's kernel log (potluck job m3-max-79800). formats.md's
row and text cite it.
2026-12-02 12:46:12 -08:00
Anees Iqbal dc08fddd25 🐛 Decode VP9 inter frames that change the stream's size
VP9 lets an inter frame change the frame size and predict from references of
another size (B96). The NVDEC arm made a decoder for each run of frames of one
size, and NVDEC names references by their surfaces, so the first frame of a new
size did not decode, nor the frames after it until an intra frame. The VA arm
made a context for each size too: there radeonsi decoded the first frame after
a change wrongly, with no error, as ffmpeg's own VA-API decode does frame for
frame, where one context as large as the largest frame decodes it right.

Each arm now keeps one decoder (NVDEC) or one context and pool (VA) for the
stream's format, as large as its largest frame so far, and decodes each frame
at its own size; NVDEC reconfigures at the map, as its AV1 decoder does. A
frame larger on a side than the decoder makes a new one, as large as both on
each side; libvpx codes a key frame there, so its streams lose no reference.

For the guest: the device's VP9 decode and an arm64 guest's paravirtual VP9
decoder give every frame of a stream that changes size between key frames, at
its own size, where NVDEC gave errors and radeonsi wrong pictures.

Tests: the resizing stream's tests of the commit before pass: the NVDEC test
on an RTX 3090 (potluck job m3-max-79818, where it failed before), the VA test
on a Radeon 780M (m3-max-79777; it failed before in m3-max-79740) and on the
Iris Xe (m3-max-79848), with the codec and accelerator unit tests. Build, unit
tests, rustfmt and clippy on Linux and the Windows target: m3-max-79773.
2026-12-02 12:46:12 -08:00
Anees Iqbal 72d823c2a5 ✅ Test a VP9 stream whose inter frames change its size
VP9 lets an inter frame change the frame size and predict from references of
another size (B96), and neither arm's VP9 decode had a stream that does. This
adds one: libvpx's, 30 frames at 352x288 in one pass whose inter frames change
the size four times (176x144, 264x216, 352x288 and 320x240), 44 KB, with
libvpx's MD5 of each frame, which ffmpeg's decode matches.

The codec test checks that the accelerator is configured at each frame's own
size, that only the first frame is a key frame, and that each resized frame's
last reference is the frame before it at its own size. The ignored NVDEC and VA
tests decode the stream to libvpx's MD5s, each frame at its own size.

Tests: the NVDEC test fails on an RTX 3090 before the fix, at the first
176x144 frame, which predicts from a 352x288 one of another decoder (potluck
job m3-max-79818); the VA test fails on a Radeon 780M from the same frame on,
which radeonsi decodes wrongly with no error, as ffmpeg's own VA-API decode
does (m3-max-79740, m3-max-79744).
2026-12-02 12:46:12 -08:00
Anees Iqbal 8341e0d047 🎨 Format the 4:2:2 listing test's closure
rustfmt lays the closure that lists the profiles on one line (build
m3-max-79811).
2026-12-02 12:46:12 -08:00
Anees Iqbal 108a8bcb8a 📝 Keep NVDEC's per-set current references off as D28 [ci skip]
An HEVC decode entry answers 8 current references on both arms, and the guest's
video driver fails the schedule of a picture whose sets name more. NVDEC holds 8
pictures in each of its three sets, so lifting the bound there was on the list as
a per-set wire field. Such a picture lies outside the profiles the host lists:
va.h bounds NumPocTotalCurr at 8, and the one stream here that names more,
kvazaar's --ref 15, does what Main does not allow (vaapi.md). So the change, a
wire field with the kexts and both prebuilt sets, buys nothing a listed profile
reaches, and it is put off with what would lift it.
2026-12-02 12:46:12 -08:00
Anees Iqbal 1bb64aaa55 🆕 List HEVC Main 4:2:2 10 for arm64 guests on the Iris Xe again
The hold on HEVC Main 4:2:2 10 (b675d53fff) waited for one encode of the arm64
guest's session that hung the Iris Xe's render engine (boot m3-max-79085:
640x360, a constant QP of 10, a Quality of 0.9, VA quality level 2), run under
the quality-level fix (201d165e47), which renders the level alone and codes at
the nearest level the driver takes. With the owner's word, that case ran once on
the Iris Xe (iHD 26.3.5, Linux 7.3.1, potluck job m3-max-79699): the driver
refused level 2 and took 1, the 10 frames, each repacked by the GPU, coded a
Main 4:2:2 10 stream that decoded back at 65.1 to 68.3 dB luma and 59.5 to 60.2
dB chroma, and the kernel logged no hang or reset. So the refused level was the
trigger, and the hold comes off.

repacked_profiles again keeps Main 4:2:2 10 where the runtime device's GPU makes
an encode session's filler, and leaves it out, said once, where it makes none.
B102 is deleted; formats.md lists the profile as offered on the Iris Xe, and the
lesson on the quality level cites the run.

For the guest: an arm64 guest's paravirtual HEVC encoder lists Main 4:2:2 10
again where the host's VA-API driver encodes it (the Iris Xe's iHD), and a
session of HEVC_Main42210_AutoLevel encodes in hardware. Other profiles and
hosts see no change.

Tests: Main 4:2:2 10 is listed where the device makes a filler and left out
where it makes none, the driver's other profiles listed either way (a unit
test). Build, unit tests and clippy on Linux and the Windows target: potluck
jobs m3-max-79811 and m3-max-79842; rustfmt passes with 68b40ffd56 on top
(m3-max-79842). An arm64 macOS 26 guest booted on the Iris Xe with the change
(m3-max-79800) listed the profile, and its VideoToolbox session of
HEVC_Main42210_AutoLevel, which requires hardware, coded 10 frames at 640x360
on the paravirtual encoder that decoded back frame for frame at 65.1 to 68.3 dB
luma and 59.0 to 60.7 dB chroma; the boot passed its 17 checks, and the host's
kernel logged no engine reset.
2026-12-02 12:46:12 -08:00
Anees Iqbal e76d7e3ab1 📝 Delete B95, fixed by early completion; B41 becomes D27 [ci skip]
B95 said a VA-API reference picture's command buffer completes only once
video processing has copied the picture into its output. 359ac7817e (11-19)
posts the CB_COMPLETE of a command buffer holding only that decode as the
decode is done and the copy issued (runs_behind_the_decode's decoded_now,
Landing::decode_done, ahead_at_decode), and readers of the output wait for
the copy and its acquire at the buffer's platform end: the fix B95 named.
Boots on a Radeon 780M then counted 893 decodes completed ahead and no
buffer or present held (walks 55149 and 55141). The 4K start's first long
gap, read by refresh, was 198.4 ms with it and 197.7 without; its share of
surface makes, first decodes and first video-processing runs is in the
ledger, unmeasured since 6bdfdcd49e and ff96c37f07. The decode wait's cost
B95 held (Iris Xe, m3-max-78524) moves to vaapi.md's zero-copy paragraph.

B41, a truncated slice decoding on VA-API with no error, is put off as D27,
as decided on 2026-12-02: a Mac's hardware H.264 decoder does the same
(measured, D25); a Mac's answer for HEVC is not measured. Its citations in
nvidia.md, vaapi.md and T3 now name D27.
2026-12-02 12:46:12 -08:00
Anees Iqbal 4cd2b6a9b7 ✅ Pass VA tests where the driver lists no H.264 encoder
The VA crate's wait tests (wait::gpu, wait::held), its teardown, H.264,
zero-copy and Direct3D 11 tests make their streams with the driver's own
H.264 encoder (teardown's Stream, unless RVG_VA_H264 names a file), and
panicked on a driver that decodes alone, as NVIDIA's VA driver does, at
"an H.264 encoder". reims-vgpu's rt caps test asserted that the host's VA
driver encodes. A test that cannot hold on a driver must not fail there.

Each stream maker now asks the driver's encoders first (encoder_support,
from vaQueryConfigEntrypoints, never the vendor's name) and, where none is
listed for the H.264 profiles it codes, says so on stderr and the test
passes. The caps test holds on such a driver: it checks that the arm then
answers no encoder and no encode caps, and still checks its decode caps. On
a driver that lists an H.264 encoder every test runs as before.

Tests: on an RTX 3090, whose VA driver (NVIDIA's) decodes alone, 11 of the
VA crate's ignored tests panicked at "an H.264 encoder" before the change and
pass after it, each saying why it did not run (potluck job m3-max-79818). On a
Radeon 780M, whose driver encodes, every test runs and passes as before
(m3-max-79606). Build, unit tests, rustfmt and clippy on Linux and the Windows
target: m3-max-79599.
2026-12-02 12:46:12 -08:00
Anees Iqbal 285014eb0c ✅ Expect the replaced-binary path in host separators
The Windows leg at 9c3ccc18f3 (m3-max-79803, the mini) failed
update::tests::a_binary_installed_over_the_one_noted_is_seen: the note
names the binary through paths::tilde, which shows a path in the host's own
separators, so on Windows /opt/bin/reims-ctl reads \opt\bin\reims-ctl,
and the test expected the Unix form on every host. The test now expects
each host's form. What the user sees is unchanged.
2026-12-02 12:46:12 -08:00
Anees Iqbal 29de5f36e0 🐛 End the commit order's waits at a device reset
A buffer answered CB_SUBMITTED on its doorbell's thread keeps its ticket in
the commit order on its queue until its begin. Where the device's reset ends
the queue before the queue's thread takes the buffer, it is never begun, and
its ticket is given back only as the control thread's reset drops the
queue's tables, holding the reset gate. A walk of the same process on
another queue, begun after that answer, waits at its commit for the ticket
(Sequencer::wait_for, or wait_for_ranges for a range message behind it)
while it holds the gate. The control thread's reset then waited for the walk
and the walk for that reset: on development a deadlock of the reset, and
with the host's settle waiting for the walks begun before the reset, a
death at its 30 s bound. A reboot between a doorbell's answer and its
queue's take meets it, as when the queue's thread is still walking the
buffer before it in place.

The sequencer's two waits now take the decoder's count of resets
(commit_order::Cancel) and end while a reset is under way, or once one came
since they began, as the waits for COMMIT_ORDER, SURFACE_ORDER and the video
caches already did. Decoders::resetting, which both the settle and the
control thread's reset call before they wait, wakes them (Sequencer::wake,
under the order's lock, so no waiter misses it). Its doc already said every
wait for another queue's buffers ends; these two did not.

What the host observes: a reset that comes between a doorbell's answer and
its queue's take no longer deadlocks the control thread's reset, nor ends
the process at the settle's bound ("the device's reset: after 30s, ... queue
walks begun before the reset"). Nothing changes outside a reset.

Tests:
- sequencer::a_reset_ends_a_commit_s_wait_for_tickets_and_range_messages: a
  wait under way as a reset begins ends, one begun during it does not wait,
  and waits wait again once it has ended, for tickets and range messages.
- reset_walks::a_reset_ends_a_walk_s_wait_for_a_buffer_answered_at_its_
  doorbell: queue 1's short buffer walked in place and held, the asking
  buffer behind it answered at its doorbell, queue 2's buffer waiting for
  its ticket, the control thread's reset held; the reset returns inside its
  bound.
Job m3-max-79774 (homelab-um870-1, fake platform): green, 178 passed (the
sequencer's, reset_walks', reset_chain's, commit_order's and the answer,
doorbell and range tests); red, with the waits not ended, both new tests
fail, the reset dying at the bound. fmt, the header's check and clippy on
the host and the Windows target are clean (79783, after the fmt fix); the
workspace's 3169 tests pass on homelab-um870-1's Radeon 780M (79801).
2026-12-02 12:46:12 -08:00
Anees Iqbal 1e8853cd04 🆕 Keep the AIR of states rt refuses for unsupplied draw input
REIMS_VGPU_REFUSED_AIR_DIR kept the AIR and record of a pipeline state only
where the translator refused it. A state rt refuses as reading what a draw or
a dispatch does not supply yet (Gap::RenderPipeline, Gap::KernelInput, such
as DrawInput) names no cause: it is one of a function table, a translation
table, a long parameter block, an unfilled push field or an unnormalized
constexpr sampler, which only the functions' AIR tells apart. A usdz preview
in Quick Look on an x86-64 guest met one (DrawInput) that no log could
explain.

The switch now keeps those states' AIR and records too. It is a diagnostic,
off by default: nothing the guest or host observes changes.
2026-12-02 12:28:20 -08:00
Anees Iqbal ea27c4943e 🐛 Make a heap's texture buffer over the heap's bytes
A guest's texture buffer (MTLTextureTypeTextureBuffer) placed in a heap was
refused: rt makes a texture buffer only over a buffer its consumer places, and
the platform passed the heap's to rt's heap-texture calls, which refuse it
(Refusal::TextureBufferNotOverBuffer). A usdz preview in Quick Look on an
x86-64 macOS 26.7.2 guest showed it six times: the size query was refused,
the bundle laid the texture out by its own bound, and the posted
TEXTURE_CREATE stood refused, so the guest's texture named nothing on the
host and what bound it bound nothing.

What the guest gets now:
- heapTextureSizeAndAlignWithDescriptor: of a texture buffer answers the
  bytes of its row of texels rounded up to the format's texture-buffer
  alignment (minimumTextureBufferAlignmentForPixelFormat:), at a heap
  buffer's alignment of 256 or that alignment, the larger; one of no texels
  stays Metal's refusal.
- MTLHeap newTextureWithDescriptor:offset: of a texture buffer makes it as
  the device's is composed: rt's texture over a buffer of the heap's bytes at
  the offset (rt's new_heap_buffer), answering the heap's modes and tracked
  as the heap. Its texels are the heap's bytes there, in a Private or a
  Shared heap, as a texture buffer's are its buffer's. Bytes past the heap's
  end stay Metal's refusal.
2026-12-02 12:28:20 -08:00
Anees Iqbal 9c3ccc18f3 🎨 Let the presenting queue test time its GPU work by the wall clock
clippy denies Instant::now outside the Clock, and the batch's lint legs
failed on the three calls in row 27's test, which sizes its fills from a
timed run and measures the lock it probes. Like command.rs's GPU timing
tests, it now allows disallowed_methods with the reason. Test-only.
2026-12-02 12:14:10 -08:00
Anees Iqbal f07e99e0d2 🐛 Refuse an x86-64 guest's Shared heap as its Mac makes none
The x86 Macs' Metal makes no Shared heap: newHeapWithDescriptor: of one ends
the process at the descriptor ("Heap Descriptor Validation / Shared storage
mode disallowed") on the AMD 5300M and the Intel 630 under macOS 26.7.1, for
both heap types, with and without the validation layer (m3-max-79571/79572).
The guest's bundle already ends an x86-64 guest's process there, sending
nothing, but the host made a raw HEAP_CREATE of a Shared heap over rt's
Shared memory for any guest, so once rt places textures in Shared heaps an
x86-64 guest could have had textures its Mac cannot make.

What changes for an x86-64 guest: a HEAP_CREATE of a Shared heap now stands
refused, unmade, and the platform is never asked for it, where it was made.
No bundle sends one: the x86 bundle ends the process first, and the arm64
bundle lays its Shared heaps over the pool or the region. An arm64 guest's
device still makes it, as the M3 Max's Metal does. The heaps the bundle lays
over its own Shared memory (HEAP_OVER_POOL, HEAP_OVER_HOST_MEMORY,
HEAP_OVER_PAGES), which hold its Shared buffers and the textures over them,
are made for either guest as before.

The answer lives in device_info beside the other answers about the Mac the
device imitates (makes_shared_heaps), and the device tells the decoder at its
make. a_create_the_platform_refuses_makes_nothing placed its texture in a
Shared heap of an x86-64 guest's device, now refused; it uses a Private heap.
2026-12-02 12:07:50 -08:00
Anees Iqbal 67c065b6f7 🎨 Format the presenting queue test's fills
rustfmt's one-line layout fix to row 27's test. No code changes.
2026-12-02 12:07:50 -08:00
Anees Iqbal ec6d0fcd64 🐛 Wait in an encode for no early copy behind a later writer
A video op waits on the CPU, before the host's video reads or writes a
surface's device cache, for an early copy of the cache into its pages still
in flight. It took the last copy made, even one behind a writer of another
queue begun after the op's own command buffer. Such a writer may wait on the
GPU for that buffer (a shared event the encode's buffer signals once the frame
is encoded, before the writer draws the next frame into the surface), and its
copy lands only after it: the op then waited for itself, and the guest's
encode froze until a reset of the device cut the wait.

A cache now keeps its early copies still landing with the number each
writer's use was counted under, and the op waits only for the last one behind
a writer counted before its own buffer's begin ended, as for its fill and its
users. Each copy waits on the GPU for the one before it, so that wait holds
the earlier copies too. Nothing changes for an op with no such copy.

Row 287's class, third of three. The test, in the commit before, commits that
writer with its early copy in flight before the encode's walk.
2026-12-02 12:07:50 -08:00
Anees Iqbal 55495d3d61 ✅ Test an encode's wait for an early copy behind a later writer 2026-12-02 12:07:50 -08:00
Anees Iqbal 766255feca 🐛 Wait in a decode for no use begun after its buffer's begin
Before its picture lands, a decode op waits on the CPU for the command
buffers committed before it that used its output's device cache with no
video op to end, by their queues' end events. A cache kept one mark a
queue, its latest buffer's, so the decode waited for a buffer of another
queue begun after the decode's own buffer. Such a buffer may wait on the
GPU for a copy of the cache that follows the decode's buffer, made only at
that buffer's finish, after the walk the decode waits in: the decode then
waited for itself, and the guest's decode froze until a reset of the device
cut the wait (a reader of the surface at a newer generation, begun on
another queue between the decode buffer's begin and its walk and committed
before the walk, is enough).

A cache now keeps each queue's unreached marks with the number its use was
counted under, and the decode waits only for those counted before its
buffer's begin ended, as for its fill. A queue's marks are let go of as its
end event reaches them, as before. Nothing changes for a decode with no
such buffer.

Row 287's class, second of three. The test commits that reader before the
decode's walk, its end left unreached as the GPU would leave it.
2026-12-02 12:07:50 -08:00
Anees Iqbal 70df1439e3 📦 Rebuild both guest kext sets for the library stream's stop
make -C guest prebuilt and prebuilt-arm64e on the M3 (job m3-max-79598, at
the stream's fix): RgfxGate's Metal bundle, in both sets, now ends a library
stream's wait for an ack at the device's stop. Nothing else in the sets
changed.
2026-12-02 12:07:50 -08:00
Anees Iqbal 6abc65d06f 🐛 Wait in a decode for no fill asked after its buffer's begin
A decode op waits on the CPU, before its picture lands, for the last fill of
its output's device cache. It took the last fill asked, even one another
buffer asked after the decode's own buffer began: that fill follows every
use counted before it, the decode's buffer among them, so it is made only
at the buffer's finish, after the walk the decode waits in. The decode then
waited for itself, and the guest's decode froze until a reset of the device
cut the wait (a reader of the surface at a newer generation begun on
another queue between the decode buffer's begin and its walk is enough).

A buffer's begin now notes how many uses of caches were counted as it
ended, and the decode's wait takes only a deferred fill asked below that,
as the caches' own rule has a buffer follow only copies asked before it. A
fill asked later is made at the buffer's finish, after the decode, as it
would be ordered behind the decode's buffer on a Mac. Nothing changes for
a decode with no such fill.

Row 287 of the hangs list. The test begins a reader of the output on a
second queue between the decode's begin and its walk.
2026-12-02 12:07:50 -08:00
Anees Iqbal bda4decb62 🐛 End a library stream's wait for an ack at the device's stop
A guest process streaming a library through its staging window waited for
each chunk's ack with no deadline and no other way out: once the device
stopped (or the process's context was released), the kext closed the
process's completions and no ack could come, so the thread making the
library slept-polled for good, holding the stream lock every later library
waits on.

The completion thread now marks the streams stopped when its wait ends
(rgfxKextWaitCompletions's error path, beside RgfxResourceWaitsStop), and
the stream's idle answers whether to look again: the default idle answers
no once the streams are stopped. A stream whose wait ended that way fails
(the library is not made, as with a refused chunk) and keeps its window,
which the host may still read, logging that once. A stream with every ack
in time is unchanged.

Closes row 321 of the hangs list. The stream test runs a device that stops
while the first chunk's and while the last chunk's ack is outstanding.
2026-12-02 12:07:50 -08:00
Anees Iqbal 74d3e23de6 📝 Say why a CPU lock's waits inside IOSurface's sync have no bound [ci skip]
Row 322 of the bug ledger noted that op 2's waits run unbounded under
IOSurface's lock. Read at 25488bee35, every such wait (the writes' buffers, a
download's answer, another lock's download, a deferred block's naming, the
block's release) already ends at the device's stop and at the locking
thread's abort, and the bundle's retire after the device's completion keeps
its 2 s bound. The rest is the host's own time, which f1da7c780d left
unbounded on purpose: at a bound the lock read whatever bytes the pages held.
So no code changes; design.md's section on how a waiter waits now says this,
which closes the row.
2026-12-02 12:07:50 -08:00
Anees Iqbal 82d7064f04 🐛 Release reims-graphics at a quit of a VM that was not running
vendor/qemu moves to f8a1f0c5 on the fork's steelbrain/reims-vgpu-rebase-2
(a60aa2b3 before it).

A quit of a VM that QEMU was not running (paused by QMP's stop or by a full
disk, never started past -S, or paused by a shutdown whose action pauses)
stopped no running VM, so the device's VM state handler never tore it down.
The device stayed to the exit, the library's quiesce at the end of QEMU's
cleanup answered that it still held a GPU device, and QEMU ended with _exit.
reims-ctl's stop of a VM paused for a full disk quits such a VM.

QEMU's cleanup notifier now first tears down each device no teardown ran for,
BAR 2 out of the guest's address space first, as at a stop. The release lets
go of the GPU device, the quiesce answers true, and QEMU ends with exit().
Only a device a display's read kept (a GPU that stopped answering) still
ends QEMU with _exit. docs/qemu.md and docs/api.md say so.

What changes for the host: such a quit ends by exit(), with its exit handlers
run. The guest sees nothing: it no longer runs.
2026-12-02 12:07:44 -08:00
Anees Iqbal f872c9ce21 🐎 Wait for the presenting queue's idle outside rt's lock
A window's swapchain without present fences (no swapchainMaintenance1) waits
for the presenting queue to idle at the window's end, and once more than four
retired swapchains are kept. It ran vkQueueWaitIdle inside rt's
with_present_queue. Where the device's queue family has one queue, that queue
is rt's and so is the lock: every submission of rt's waited for the whole
drain of the work already on the queue, a stall of rt's submit thread at a
resize or a window's close.

The wait now submits no batch with a fence of the swapchain's own inside the
lock, and waits for the fence with the lock let go of. Vulkan signals such a
fence once all work submitted to the queue before it has completed, which is
how vkQueueWaitIdle's wait is defined (a fence on every submission before
it), so the swapchain waits for the same work and destroys its retired
swapchains at the same point. Where the fence cannot be made or the
submission is refused, it waits as before, inside the lock. The wait is
counted as window-idle among the long waits.

What changes for the host: rt's submissions go on while a window's swapchain
waits for the presenting queue at a resize or a close, on a one-queue family
without present fences. Nothing changes for the guest.
2026-12-02 12:07:24 -08:00
Anees Iqbal ae914185b5 ✅ Test a wait for the presenting queue's idle beside rt's work
A window's swapchain without present fences waits for the presenting queue
to idle at the window's end and past four retired swapchains. It runs
vkQueueWaitIdle inside rt's with_present_queue, and where the device's queue
family has one queue, that lock is the one every submission of rt's takes. So
rt's submit thread stalls for the whole drain of the work already on the
queue: a hitch at a resize or a window's close.

The test schedules a Private buffer's fills on rt's queue, starts the wait,
and 10 ms in has another thread take the presenting queue's lock for an empty
call. It asks that the lock come free within a quarter of the wait. A device
whose presenting queue holds none of rt's work idles at once, and the test
says so and shows nothing. It fails on the code as it is on a one-queue
family.
2026-12-02 12:07:24 -08:00
Anees Iqbal 60ab134af2 🐛 End a stop with no timeout of a VM paused on a full disk
A stop with no timeout (a stop timeout of 0) waits until the guest shuts
down and never powers the VM off. QEMU pauses a VM when a write to its disk
finds the host's disk full, and a paused guest never shuts down, so that stop
waited for good. It also sent the shutdown keys, which the guest would read
once resumed.

Such a stop now asks QMP first whether QEMU paused the VM for a full disk,
and again every 2 s while it waits for the guest. Where QEMU did, the stop
ends with an error that names the file QEMU could not write and the two ways
out: free space, resume, and stop again; or a forced stop, which loses the
writes QEMU holds. It sends no keys to a VM paused before the stop, and
powers nothing off. A stop with a timeout is left as it was.

What users see: reims-ctl stop --timeout 0 (or x in the interface with a
shutdown timeout of 0) on a VM paused for a full disk returns with that error
instead of hanging.

The test of the no-limit stop now expects QMP's query-status before the keys.
2026-12-02 12:07:24 -08:00
Anees Iqbal e39a8460fe ✅ Test a stop with no timeout of a VM paused on a full disk
A stop with no timeout waits until the guest shuts down and powers nothing
off. A VM that QEMU paused because the host's disk is full cannot shut down,
so such a stop waits for good today. It also sends the shutdown keys, which
the guest reads once resumed.

The test asks that the stop end within 10 s with an error that names the full
disk and the two ways out (free space and resume, or a forced stop), and that
it sends no keys and powers nothing off. It asks the same of a VM QEMU pauses
while the stop waits for its guest. The stop runs on a thread of its own, so a
stop that waits for good fails the test at 10 s instead of holding it: the
test's QEMU, a child the test does not reap, stays in the process table. It
fails on the code as it is.
2026-12-02 12:07:24 -08:00
Anees Iqbal 7baeccd277 ✅ Keep the VM-window desktop test to Linux
doctor_wants_a_desktop_only_for_a_vms_window assumed a VM's DISPLAY can
name a screen on a Mac, the behaviour the session-based screen check
changed; make check-ctl on the Mac caught it. The test and its helper
screenless_vm now build only on Linux and other non-Mac unixes, where
DISPLAY names one. Test-only.
2026-12-02 12:07:15 -08:00
Anees Iqbal a760c49675 🎨 Format the tests' stand-in program writer
rustfmt's layout of testenv::program, which the ETXTBSY fix rewrote. No
code changes.
2026-12-02 12:07:15 -08:00
Anees Iqbal febcdc14c5 🎨 Format the counts-report tests
rustfmt's layout of two test lines (logs.rs and runtime.rs) that the
stopped-report commit added. No code changes.
2026-12-02 12:07:15 -08:00
Anees Iqbal d81a537c34 🐛 Write the tests' stand-in programs from a child process
A test that wrote a stand-in program and then ran it could fail with ETXTBSY
on Linux. Another test's child, forked while the write's descriptor was open,
holds a copy of that descriptor until it execs, and Linux refuses to exec a
file open for writing anywhere. install::tests::a_qemu_that_takes_the_probe_
takes_the_memory_type failed so once (m3-max-79479) and passed on its reruns.

testenv::program, which every reims-ctl test that runs a stand-in script goes
through, now has sh write the file. This process never holds a descriptor of
it, so a fork has none to copy. The new test runs 100 programs while eight
threads fork, and failed with ETXTBSY before the change.

Users see no change: only the tests' helper changes.
2026-12-02 12:07:15 -08:00
Anees Iqbal 2a0064a9bb 🆕 Write the degradation counts again each minute they changed
The library writes its degradation counts line at a device's reset, at the
process's exit and when the host asks (reims-ctl report). A QEMU killed or
crashed writes nothing at its end, so its log held counts only as of the
last reset or ask, often the boot's start: a report of such a run had
nothing to read its degradations from.

The first device made on the process's platform (GraphicsDevice::new, as
the C API makes QEMU's) now starts a thread, reims-vgpu.counts, that every
COUNTS_REWRITE, a minute, folds rt's metrics in and writes the counts line
where it changed since the library last wrote it, and nothing else: the
repeats' line and rt's diagnostic lines stay the reset's, exit's and ask's.
Each write is an entry, so the thread parks for good once the process's
exit began. A killed or crashed QEMU's log now holds counts at most a
minute old. A diagnostic: free under the contract. A test's platform runs
no such thread.
2026-12-02 12:07:15 -08:00
Anees Iqbal a1ebd6f3d4 🆕 Say in a stopped VM's report whether its counts are as of its end
reims-ctl report asks a running VM's library for its degradation counts; for
a stopped VM it wrote "stopped" in state.txt and nothing else. The library
writes its counts into QEMU's log at a device reset, at an ask, and at the
process's exit, so a VM whose QEMU was killed or crashed has none as of
that moment, and nothing in the report said so: whoever read it took the
log's last counts for the run's.

state.txt for a stopped VM now says why it stopped, as its state does, and
whether the counts in logs/qemu.log are as of the run's end: "as of the
run's end" where QEMU exited (an ask to shut the VM down, a signal), "not
as of the run's end, which wrote none: logs/qemu.log's last are from
earlier in the run" where it was killed, crashed or a fatal error ended it,
or that the run has none. A run an earlier reims-ctl started, whose end
its log does not tell, says "stopped" as before.
2026-12-02 12:07:15 -08:00
Anees Iqbal 770aedd67c 🆕 Say why a VM stopped: its guest, its window, a quit or a signal
A VM that stopped by itself showed only "stopped" (or reims-vgpu's fatal
line): a guest that shut down and a window closed at the host looked the
same, and so did a VM whose QEMU was killed or crashed. QEMU logged nothing
of a shutdown's cause; it tells it only to a QMP client connected at the
time.

QEMU's command now carries `-trace qemu_system_shutdown_request`, which has
QEMU write `qemu_system_shutdown_request reason=N` to its log, the VM's
qemu.log, as anything asks it to shut the VM down, N its ShutdownCause.
Every QEMU scripts/install-ctl.sh builds, on Linux, macOS and Windows, has
meson's default `log` trace backend, which writes it to stderr. This
changes the QEMU command line: it needs an install and a VM boot on each
host.

From the last run in the log, a stopped VM's state now says why it
stopped: "its guest shut down" (a stop's keys or power button ask for
that), "its window was closed", "QEMU was told to quit (reims-ctl stop's
power off, or another QMP client)", "QEMU ended on a signal (terminating
on signal 15 from pid ...)", "its guest panicked", reims-vgpu's fatal line,
or, where the run asked for the trace and QEMU traced no ask, "QEMU ended
without shutting it down, as it does when killed or when it crashes". A
run an earlier reims-ctl started says "stopped" as before. Users see it in
the interface's status line as a VM stops ("t: stopped: its window was
closed"), its VM pane's and reims-ctl show's state line, and reims-ctl
list --json's "why" for a stopped VM.
2026-12-02 12:07:15 -08:00
Anees Iqbal 467a108fe0 🐛 Refuse a start from a reims-ctl whose binary was updated since
A reims-ctl process carries the guest's kexts and the device's option ROM of
its own build, which a start gives the VM (its OpenCore image, made again
where it holds other builds, or an arm64 VM's config bundle), but the QEMU a
start runs, with the library in it, is the install's. An interface left
open while reims-ctl was updated from another terminal so started VMs with
its older drivers and ROM under the newer library, which can keep the
guest from using its GPU, and said nothing.

reims-ctl now notes its binary's file as it starts (its length, time of last
write and identity: device and inode on macOS and Linux, volume and file index on
Windows), and a start from a process whose binary was replaced since is
refused, in the interface's status line as on the command line:
"reims-ctl was updated since this one started (PATH holds another build
now): quit it and run reims-ctl again. This one carries older macOS drivers
and option ROM than the QEMU it would start, which can keep the guest from
using its GPU". A path that holds nothing now is not taken for another
build. The test installs a build over a noted one both ways an install
can, renamed over it and written in its place, keeping its length and time
of last write.
2026-12-02 12:06:26 -08:00
Anees Iqbal 1719ebb0bb 🐛 Let the viewer hold a VM's QMP socket only for each exchange
QEMU serves a VM's QMP socket one client at a time. The terminal viewer let its
connection go after each frame, but kept the one it sent input on until its
next frame, and it takes no frame while the last one is still being drawn.
So while someone moved the mouse or typed into a viewer whose terminal was
slow to draw, every other client of the socket waited, and one whose wait
ran out failed (read from the code): a report waited 3 s and wrote
"degradation counts: not written for this report", and reims-ctl stop's
keys and power button (10 s each) could fail to reach the guest, so the
stop powered it off; a resume, a USB attach or the interface's pause probe
failed the same way.

The viewer now connects for each exchange, a frame's screendump or a batch
of input, and closes the connection as QEMU answers. Other clients get in
between its exchanges, queued in the socket's backlog ahead of its next one.
The test drives the viewer's QMP thread against a socket served as QEMU
serves it, moving the mouse while a frame is being drawn, and has another
client's command answered.
2026-12-02 12:06:18 -08:00
Anees Iqbal be5814d705 🆕 Name the Mac a VM's image presents with the macOS it runs
An OpenCore image reims-ctl makes for a new VM picks its Mac by the macOS it
installs: the iMacPro1,1 below 10.15, else reims-util's default iMac20,1. An
image that keeps a Mac does not: the image beside an existing disk, which a
create presents again so the disk's macOS sees no new Mac, an image given
with --opencore, and a renewal (U, update-opencore). Those keep the Mac they
were made with, and reims-ctl said nothing when that Mac can't run the
disk's macOS: the user met it only as a guest that would not boot.

Now each of them names the Mac with the macOS releases it runs, the range
model_for's choice rests on (iMac20,1: macOS 10.15.6 to 26; iMacPro1,1:
10.13 to 15), and a Mac reims-ctl knows no range of as such:
- create, on an existing disk: "presenting the Mac <image> presents, the
  one macOS on this disk ran on: an iMac20,1, which runs macOS 10.15.6 to
  26";
- create, given an image: "the OpenCore image given presents an iMac20,1,
  which runs ...", or why its Mac could not be read;
- a new image reims-util makes: "OpenCore presents the VM as an iMac20,1,
  which runs ...; its serial is ...";
- the renewal's line, and the interface's U confirmation (a TUI text
  change), name the range too.
It is a line, not a refusal: no start or create is refused for it.
2026-12-02 12:06:18 -08:00
Anees Iqbal 3e12823dbe 🐛 Stamp a VM's OpenCore image with its change time on Windows too
The interface's VM pane keeps what a read of a VM's OpenCore image found while
the image's file keeps its stamp: its length, its time of last write and,
on macOS and Linux, its ctime. On Windows the stamp had no change time, as
std's metadata gives none, so an image another program rewrote in place to
its old length and time of last write (cp -p, rsync -t) kept the old answer
until reims-ctl restarted: the pane could say the image held reims-vgpu's
drivers after they were gone, or the other way round.

os::changed now reads NTFS's change time on Windows, FILE_BASIC_INFO's
ChangeTime through GetFileInformationByHandleEx, opening the file to read its
attributes alone, so a running QEMU's open handle does not keep it from being
read. A file system that keeps none (FAT, exFAT) answers 0, read as none, as
before. The test rewrites a file keeping both and checks the stamp moves; it
held already on macOS and Linux, and fails on Windows without this.
2026-12-02 12:06:18 -08:00
Anees Iqbal e7b0cabd1e 🐛 Tell a Mac's screen by its session, not X's or Wayland's variables
host::has_screen read only WAYLAND_DISPLAY and DISPLAY on every unix host, so
on a Mac, whose windows are AppKit's, it said "no screen" in a signed-in
user's session. Nothing a user sees changed with it: a start on a Mac opens
the library's window whatever it says (qemu::opens_window), and doctor checks
a desktop only on Linux and Windows. A caller that trusts it on a Mac would
have taken every Mac for headless.

On macOS it now answers whether this process's security session reaches the
window server, Security's SessionGetInfo with sessionHasGraphicAccess: yes in
a signed-in user's session, no in an SSH login's. A VM's X and Wayland
variables decide nothing there, which the new test pins.
2026-12-02 12:06:18 -08:00
Anees Iqbal 68701c61bf 🐛 Wait at a reset for the queue walks begun before it
The device's reset waits, in the host's settle, for the GPU work the guest
committed before it, so none of that work writes the guest's memory after the
reset returns. A queue walk begun before the reset could still commit work
after the settle looked: the control thread's reset waits for it (the reset
gate), but the settle cannot take that gate, as ring 0's queue creates and
destroys hold it and may wait for the BQL that QEMU holds around the reset. The
walk's GPU work then ran, and wrote the guest's pages, after the reset returned.

The settle now waits, within 30 s of its start, as for the decoder's locks, for
the queue walks begun before the reset (walks.rs: a ticket taken in
begin_command_buffer before the walk asks whether its poster is stale, so a
walk that begins after the reset ends at once and is not waited for). First it
cuts short every wait the control thread's reset cuts short, so no walk waits
for that thread: for other queues' buffers and their events
(Decoders::resetting; commit_order::Cancel now nests, as the two resets may
overlap), for compiles outside the process (GpuDevice::reset_begins, whose
stage-fill suspends nest) and for pipelines still compiling
(Pending::resetting, which nests too). After the walks it releases the events
and surface timelines again, for what the walks made or waited for meanwhile,
then waits for the GPU as before, on progress: the command buffers it waits
for are those committed by then, the walks' among them. Ring 0's block-lane
downloads and cache copies stay out of it. A walk past 30 s ends the process
at "the device's reset", naming the oldest. The settle's line now reads "the
device's reset waited X ms for the W queue walks begun before it (Y ms) and
the N command buffers committed to the GPU before it, Z ms at most with none
of them completing".

What the host observes: rvg_graphics_device_reset and a STATUS write of 0
return only once the queue walks begun before them have ended, which the
header's reset doc and docs/api.md now say. Two tests held the old behaviour
and change with it. a_reset_during_a_walk_comes_after_it had the reset return
with the walk in flight; it now resets on a thread of its own and checks that
the reset waits. reset_chain's stage-fill test had the fill go on through the
settle, cancelled only by the control thread's reset, with the settle setting
the writer's timeline on the CPU; now the settle cancels the fill, the walk
ends with its dispatch refused and commits the writer's buffer, and the settle
waits for it and the reader's on the GPU. Its compile test now moves the clock
past the bound where the reset has not returned, so a red run dies there
rather than hanging.

Tests (tests/reset_walks.rs), each with the control thread's reset held behind
a ring-0 message whose platform call is held, standing for the BQL:
- a_reset_waits_for_a_walk_begun_before_it and
  a_reset_whose_walk_runs_past_the_bound_ends_the_process;
- one per wait class a walk can sit in, each ending inside the bound: a
  COMMIT_ORDER wait, a begin's SURFACE_ORDER wait (whose buffer then waits on
  the GPU for a timeline the settle sets after the walks), a stage's fill and a
  pipeline still compiling.
Job m3-max-79627 (homelab-um870-1) ran them on the fake platform three ways.
Green: all pass, with the progress rule's and the chain's tests (88). Without
the walks wait: the two walk tests, a_reset_during_a_walk_comes_after_it and
the SURFACE_ORDER test, whose timeline is set only after the walks, fail.
Without the settle's cut-shorts: each wait class's test and both chain tests
die at the bound. fmt, the header's check and clippy on the host and the
Windows target are clean (79627); the workspace's 3167 tests pass on
homelab-um870-1's Radeon 780M (79647).
2026-12-02 12:06:18 -08:00
Anees Iqbal 537a9b1f14 🐛 Write no GPU work back into guest pages after a device reset
The rt platform runs the GPU's writes to guest pages it does not import on a
copy, and a command buffer's completion merges the bytes the GPU changed back
into the pages (copied.rs). The device's reset waits, in the host's settle, for
the guest's work committed before it, but not for every command buffer made
before it: ring 0's block-lane downloads and cache copies stay out of the
settle, and one of them can complete after the reset has returned. Its merge
then wrote into pages that are the rebooted guest's, where a GPU's reset stops
its DMA first.

A command buffer now notes its device's count of reset begins and ends as it
is made (Flights::resets, which RtDevice::reset_begins and reset_ends raise; a
part takes the count of the buffer it was cut from). Where the count has moved
by its completion, the completion writes nothing back into the pages of a copy
that merges. Each copy left is counted (rt-copied-merges-skipped-at-reset), and
the process's first is logged at info. The GPU's bytes stay in the copy, where
nothing of the rebooted guest's reaches them: the reset drops every object over
the guest's pages, and a block made after it gets a copy of its own. A copy of
unchanging pages is still written again from them, which writes rt's memory,
not the guest's.

What the guest observes: after a reset, its pages no longer take GPU writes of
work made before it through a copy. GPU writes such work makes into pages rt
imports in place are not covered, and stay open.

Tests: copied's a_completion_after_a_reset_writes_nothing_back, and on the GPU
the test holds, a_completion_after_a_reset_merges_nothing_back_on_vulkan. Red,
jobs m3-max-79646 and 79647 (homelab-um870-1): with merge_back writing back
after a reset too, both fail (the GPU's bytes reached the pages; on the Radeon
780M, merged back after the reset began). Green, with the next commit's (C) on
top: both pass among the workspace's 3167 tests on the 780M (79647), and fmt,
the header's check and clippy on the host and the Windows target are clean
(79627).
2026-12-02 12:06:18 -08:00
Anees Iqbal 161cf78cf4 🐛 Let a reset wait while the GPU work before it completes
The device's reset waits for the GPU work the guest committed before it, so
none of that work writes the guest's memory after the reset returns. It waited
a flat 30 s, and ended the process past that. A guest that is busy, with
nothing stuck, could reach it: the settle waits for every command buffer
committed before the reset, and a backlog of long ones, each well within the
drivers' watchdogs, can sum past 30 s. Nothing of ours bounds that backlog.

The wait now runs on progress. The set of command buffers it waits for is
fixed as it begins. It waits while they complete, each within 30 s of the one
before (or of its start), and 10 min at most in all: the time cap of the helper
process that runs pipeline compiles and stage fills, read from its definition
(os::compile_helper's TIME_MOST, exported as COMPILE_HELPER_TIME_MOST), not a
new constant. The decoder's locks the settle takes keep their flat 30 s. Each
settle logs the longest it waited with none of its command buffers completing.

What the host observes: rvg_graphics_device_reset and a STATUS write of 0 wait
while that work completes, past 30 s, and end the process only once 30 s pass
with none of it completing, or at 10 min. A reset still waiting 2 s on writes
one line on stderr, whatever REIMS_VGPU_LOG says ("reims-vgpu: reset waiting:
for the GPU work committed before it, N command buffers, 2 s on"), and one
once it is done ("reims-vgpu: reset waited: S s for the GPU work committed
before it"). The death's line says which bound it passed. reims-ctl's
interface reads the first line from QEMU's log, and shows the VM's state as
"reset: waits for GPU", with the line in its pane, until the second comes. The
header's reset docs, docs/api.md ("Waiting", "Deaths", the threads table and a
new "The reset's lines") and docs/known-issues.md ("A stuck GPU closes the VM
when it restarts": one command buffer running past 30 s on a driver that never
ends it is a stuck GPU to the reset) say so.

GpuDevice::settle takes SettleBounds and a waiting callback and answers
Settled; rt's Flights::settle restarts its bound on each command buffer that
completes, on the platform's clock, as the testkit's World::settle does on
virtual time.

Tests: a_reset_waits_on_while_its_gpu_work_completes (three buffers, one
completing every 20 s: the reset returns, having said both lines) and
a_reset_whose_gpu_work_completes_past_the_most_ends_the_process (one buffer
every 29 s, 22 of them: alive after 20, dead at the ceiling); rt's
a_settle_waits_while_its_command_buffers_settle_within_the_quiet_bound on a
virtual clock; reims-ctl's a_vm_whose_reset_waits_for_its_gpu_shows_it.

Red, job m3-max-79515 (homelab-um870-1, fake platform): with the settle's
ceiling set back to the flat 30 s, both reims-vgpu tests fail (the reset ended
40 s on, with its GPU work completing; it ended before the most it waits).
Green: the same tests pass (79515); fmt, the header's check and clippy on the
host and the Windows target (79539); the workspace's 3156 tests on
homelab-um870-1's Radeon 780M (79546); make check-ctl on the Mac (79521).
2026-12-02 12:06:18 -08:00
Anees Iqbal f9a14c1d3a ✅ Give the C harness's device configs the headless mode fields
The headless resolution added headless_mode_width and _height to
RvgGraphicsDeviceConfig, and the C harness's three config initializers,
built with -Werror=missing-field-initializers, stopped compiling, so
every c_harness test failed (batch by's Mac and 3090 runs). They now
give 0 and 0, the 1920 x 1080 default. Test-only.
2026-12-02 12:06:18 -08:00
Anees Iqbal 7acdc2116c 🐛 Escape the shared image path in the processor-type wait test
The test wrote a Windows path into a VM's settings with raw backslashes,
which TOML reads as escapes, so it failed on Windows before reaching
the wait it checks (development's Windows leg, m3-max-79523). It now
writes the path through testenv::toml_path, as 25488bee35 did for the
same class. Test-only; no change for users.
2026-12-02 12:06:18 -08:00
Anees Iqbal a18876aa0e 🎨 Format the one-wait display read and its tests
rustfmt wraps the display read's alignment chain and the asserts its
tests added, which batch by's lint leg found unformatted. No code
changes.
2026-12-02 12:06:18 -08:00
Anees Iqbal 653f597eee ✅ Give the start on a running VM's disk its headless argument
The test of a start refused on a running VM's disk called start with the
arguments it took before --headless.
2026-12-02 12:06:17 -08:00
Anees Iqbal 6716d98745 🆕 Add reims-ctl start --headless, a start with no window
The owner asked for a headless start for viewer-only use: a VM used through
reims-ctl view alone, on a host or over SSH. Until now that took the VM's
variable REIMS_VGPU_WINDOW=0, saved in its settings and named nowhere but the
README.

reims-ctl start NAME --headless opens no window for that start and saves
nothing: on reims-vgpu's own device QEMU gets REIMS_VGPU_WINDOW=0 over any
value the VM's variables give, and VMware SVGA's QEMU -display none. Each
display offers macOS the VM's resolution at 60 Hz: no screen of the host
shows the guest, so there is no screen's rate to follow.

What the user sees: the start prints "NAME: headless, with no window:
`reims-ctl view NAME` shows its screen in the terminal" after its pid;
reims-ctl show and the VM's pane say "running headless (pid N), with no
window: reims-ctl view NAME shows its screen", read from the line the start
writes at the head of its QEMU log; reims-ctl list adds that note below its
table, and its JSON "headless": true. A VM kept headless by its variables is
told the same way. start --help, the interface's help, view --help, doctor's
hint, the resolution settings' help, the README row and docs/qemu.md name the
flag.
2026-12-02 12:06:17 -08:00
Anees Iqbal 120627773e 🐎 Read the display in one wait, from a texture over a buffer
A read of what a display shows (rvg_graphics_read_display, which QEMU's
screendump and so reims-ctl view call, up to 15 times a second) drew the
display into a texture of its own, waited for that draw, then read the texture
back with getBytes. On the Vulkan platform that read-back of an image is an
upload of its own on the process's queue, so a read waited a second time,
behind every submission queued by then, the guest's GPU work among them.

The read's target is now a texture over a Shared buffer of the read's own, its
rows at the device's linear alignment for BGRA8, as Metal documents
newTextureWithDescriptor:offset:bytesPerRow:. Once its draw has finished the
texture's pixels are the buffer's bytes, which the read copies out on the CPU:
one wait, for its own draw, and nothing asked of the platform after it. What
the read returns is unchanged.

The fake platform now logs getBytes, and the read's tests ask for one wait,
no getBytes and the target's buffer made once.
2026-12-02 12:06:17 -08:00
Anees Iqbal cbd87bd547 🆕 Offer a headless display the VM's resolution as its mode
A device with no window (REIMS_VGPU_WINDOW=0, or another display of
QEMU's) offered every display 1920x1080, whatever QEMU's resolution
property said: the property reached the library only inside a window
config. A VM started for its viewer alone therefore ran at 1920x1080
whatever its settings named.

The C API's RvgGraphicsDeviceConfig grows headless_mode_width and
headless_mode_height (its seventh version), read only where window is
NULL, and the Rust API's GraphicsConfig grows headless_mode. A display
without a window offers that mode first, its width rounded down to a
multiple of 16 and its height to even as a window's size is, at 60 Hz;
0 in either, or a host built before the fields, keeps 1920x1080. QEMU's
reims-graphics-pci passes its resolution there (vendor/qemu 0f7f65ae).

What the host's user gets: a VM started without a window now offers its
guest the resolution its settings name.
2026-12-02 12:06:17 -08:00
Anees Iqbal b15371a007 📝 Say ANV imports a view's dma-buf from metal2vulkan d122da6ae3 [ci skip]
metal2vulkan-runtime's dma-buf rule now takes, where the first type a dma-buf's
query offers is device-local, the first offered type that is listed,
device-local, host-visible and host-coherent (edad2e31fb): type 1 on the Iris
Xe of RPL-P, where it refused before. So ANV imports a view's pages as a
dma-buf from this pin on, and only NVIDIA's driver still maps views from their
files. The surface pages' module doc, the device's design and the QEMU notes
said ANV was refused.
2026-12-02 11:48:57 -08:00
Anees Iqbal 290f284335 🆕 Answer programmable sample positions as rt's device does
What the guest observes changes: its device's
programmableSamplePositionsSupported was yes on every host GPU, Metal's answer
on the M3 Max; it is now metal2vulkan-runtime's answer for the device
(Device::programmable_sample_positions_supported, 1c307b4608): yes where the
device lists VK_EXT_sample_locations with Metal's grid of positions at every
sample count it renders, and no elsewhere, as a Mac whose GPU takes no
positions answers. The rt platform's passes still render at the default
positions and count other positions as unbuilt (set_sample_positions); on a
device that answers no, a guest that asks first sets none.

The device's facts carry rt's answer, and the caps take it. A device-free test
holds both answers; the GPU test checks the answer against rt's on the GPU it
holds and prints it with the device's name.
2026-12-02 11:48:57 -08:00
Anees Iqbal 225014b76a 🆕 Carry rt's plane stand-ins and their copies on the counts line
metal2vulkan-runtime no longer refuses a pass that mixes a marked linear
surface plane with another attachment (23847fe2ae): it renders or resolves
into a stand-in in the plane's place, an optimal image, and copies the pass's
render area in as the pass begins and back as it ends, copies Metal does not
make. rt counts them in Metrics::plane_copies_in, plane_copies_out and their
bytes, and gauges the stand-ins in Gauges::plane_stand_ins and their bytes.

For the host, the counts line now carries the four copies as amounts,
rt-plane-copies-in, rt-plane-copy-in-bytes, rt-plane-copies-out and
rt-plane-copy-out-bytes, and the two gauges at their highest,
rt-plane-stand-ins-most and rt-plane-stand-in-bytes-most, so a boot's line
says whether its passes over planes ran through stand-ins: where the pin
before refused them, counted under rt-refused-gap. On a device whose LINEAR
tiling renders the plane's format all six stay 0.
2026-12-02 11:48:57 -08:00
Anees Iqbal c5e7501795 🐛 Wait for an exported block's making before handing out its memory
metal2vulkan-runtime makes an exported block the runtime's until its making,
the release of its buffer to the other API's queue family, which rt records
for its first submission after the make and does not wait for (d0a424060a).
Its hand-over contract: the other API's first access of the block comes after
Block::wait_until_ready has returned. Each export of an exportable buffer
(export_memory, export_dma_buf) now waits for it before it hands out the fd,
as an exported surface's export already waits for Surface::wait_until_ready.
For the host, NVDEC's and VA-API's first decode into an IOSurface device cache
can no longer start before the block is theirs; the wait is one per import.

The test counts rt's ready waits (Metrics::surface_waits) across two exports
and an export of another kind.
2026-12-02 11:48:57 -08:00
Anees Iqbal 255745b8e9 🔥 Drop the release call that rt now makes at each submission
metal2vulkan-runtime removed BlitCommandEncoder::release_to_external
(d0a424060a): each submission that uses memory another API shares now
acquires it at its head and releases it at its end, whatever order the
consumer calls in. Our wrapper went with it: BlitEncoder::release_to_external
(only the rt platform implemented it; the default and the testkit did
nothing), its rt impl, and its two callers, the NVENC input copy and the
VA-API encoder input fill. The VA-API fill opened a blit encoder only to carry
that release, so it opens none now. Nothing changes for the guest: each
encoder still reads its input only after the fill or copy completed, and the
submission that wrote it now hands it over as it ends.

Red: the build at the pin move failed on rt_platform/blit.rs:1005, no method
release_to_external (job m3-max-79295, gem10).
2026-12-02 11:48:57 -08:00
Anees Iqbal cc0142cf8d 🔥 Drop the refusal kind of a linear plane pass rt no longer refuses
metal2vulkan-runtime removed Gap::LinearPlanePass and LinearPlanePassKind
(23847fe2ae): a mixed pass over a marked linear plane now renders through a
stand-in with counted copies instead of being refused. The refusal counter
named that gap LinearPlanePass-<kind>; the arm and the test that built the gap
go, as nothing can produce it now. For the host, the counts line no longer
lists a LinearPlanePass kind; the video lane read 1091 rt-refused-gap at pin
d8735b75f0 from it on the 3090.
2026-12-02 11:48:57 -08:00
Anees Iqbal 55ded22040 ⬆️ Build on metal2vulkan development d122da6ae3
The next pin move: metal2vulkan-runtime at its development commit d122da6ae3.
The adaptation commits that follow make the tree build and pass on it.
2026-12-02 11:48:57 -08:00
Anees Iqbal 53e7385993 📝 List the core counts About This Mac names a CPU at [ci skip]
About This Mac says "Unknown" where Apple's table of Intel names has none
for the host's family at the core count macOS reads, the VM's vCPUs
rounded up to a power of two, as a VM of 4 vCPUs on a Core i9 host. The
known issues list the vCPU counts each family is named at, how to pick
one, and that an AMD host reads as the Intel family of the same rank,
macOS having names for Intel processors only.
2026-12-02 11:00:02 -08:00
Anees Iqbal 24d78a3619 📝 Say how an x86-64 guest's About This Mac names its CPU [ci skip]
docs/qemu.md said the name came from OpenCore's own pick, which macOS
named "Unknown", and that model-id changed nothing in About This Mac. It
now says how macOS makes the name, from type 131's family and the core
count machdep.cpu.core_count reads, the vCPUs rounded up to a power of
two, where Apple's table has the pair, what reims-ctl writes for the
host's CPU and the model-id it gives, and the values measured on macOS
26.7.2: by hand (m3-max-79231), and before and with the change on a
Core i9 and a Ryzen 7 host (m3-max-79299, 79300, 79321 and 79342).
2026-12-02 11:00:02 -08:00
Anees Iqbal adfb3482e0 🐛 Name a Xeon host's VM of 5 or 6 CPUs as a Xeon W
macOS names the processor at the core count machdep.cpu.core_count reads,
which with QEMU's CPU is the VM's vCPUs rounded up to a power of two
(measured on macOS 26.7.2: 3 vCPUs read 4, 5 to 7 read 8, 9 reads 16), not
at SMBIOS type 4's count. A Xeon VM of 5 or 6 vCPUs got "Intel Xeon",
which reads as "8-Core Intel Xeon", a name Apple's table lacks, so About
This Mac said "Unknown"; it now gets "Intel Xeon W" from 5 vCPUs, which
shows "8-Core Intel Xeon W" (m3-max-79342). The start's and the TUI's help
said odd counts show "Unknown"; they now say the count rounds up and at
which counts each family is named.
2026-12-02 11:00:02 -08:00
Anees Iqbal d8491185bd 🆕 Name the host's CPU family in an x86-64 guest's About This Mac
About This Mac showed an x86-64 guest's processor as OpenCore's own pick,
Apple's type 0x0905, Core i3, on every host: "Quad-Core Intel Core i3" at
4 vCPUs, "Unknown" at 8. A start now writes PlatformInfo > Generic >
ProcessorType into the VM's OpenCore image for this host's CPU, where the
image holds another value, after any new image the start makes: the
family the CPU's brand string states (processor.rs), as Apple's type for
it, 0x0909, 0x0609, 0x0709 or 0x1009 for Core i3 to i9, and for a Xeon
0x0501 up to 6 vCPUs and 0x0F01, Xeon W, from 8; 0 again, OpenCore's own
pick, for a CPU that states none. AMD's Ryzen 3 to 9 take the Intel
family of the same rank, Threadripper and EPYC Xeon's: macOS names Intel
processors only. Each value but 0x0501 was measured to name its family on
macOS 26.7.2 (m3-max-79231). The core count About This Mac puts before the
family is the VM's vCPUs, as before; where Apple's table has no name for
the family at that count, it still says "Unknown".

The value goes into a copy of the image, read back and renamed over it,
with config.plist's length kept so only its own clusters change: a write
stopped part way leaves the image as it was. It is refused while the VM
or another VM on the same image runs, as a renewal is. Start's --help and
the interface's help say what the guest shows.
2026-12-02 11:00:02 -08:00
Anees Iqbal 167c4913f7 🆕 Give an x86-64 guest's CPU the host CPU's brand string
The guest's sysctl machdep.cpu.brand_string read QEMU's name for the CPU
model, "Intel Core Processor (Skylake, IBRS, no TSX)", whatever the host.
It now reads the host's own, "13th Gen Intel(R) Core(TM) i9-13900H" or
"AMD Ryzen 7 7840HS w/ Radeon 780M Graphics": reims-ctl passes it as
-cpu's model-id, a comma doubled as QEMU's option syntax escapes one,
after its own flags and before the VM's cpu_flags, so a model-id there
replaces it. The CPU's model and its features stay as they were; in the
guest the brand string is read only by that sysctl, a boot log line, the
MCA panic log and OpenCore's own pick of the processor type. A host that
gives no brand string, as one other than x86-64, gets the line as before.
2026-12-02 11:00:02 -08:00
Anees Iqbal 1d06c1a6cf ✅ Expect an x86-64 guest to name the host's CPU
A user's x86-64 guest on an Intel Core i7 host shows its processor as an
Intel Core i3: OpenCore picks Apple's processor type itself, 0x0905, from
QEMU's own CPU name ("Intel Core Processor (Skylake, IBRS, no TSX)") on
every host, which About This Mac shows as "Quad-Core Intel Core i3" at 4
vCPUs and "Unknown" at 8 (measured on macOS 26.7.2, m3-max-79231).

These tests hold what the guest is to get instead: the family the host
CPU's brand string states, Intel's i3 to i9, Core (Ultra) 3 to 9 and
Xeon, and AMD's Ryzen 3 to 9, Threadripper and EPYC by the same rank, as
Apple's processor type for that family; and the brand string itself as the
guest CPU's model-id. The host's brand string is read from CPUID
(host::cpu_brand) and carried in QEMU's context; the family's reading and
the model-id argument are stubs here, so the family, processor type and
model-id tests fail.
2026-12-02 11:00:02 -08:00
Anees Iqbal 0209935005 📝 Document HEVC 4:2:0 range extensions decode on iHD [ci skip]
The formats table lists 4:2:0 range extensions at 8 and 10 bits as offered on
the Iris Xe, with its conformance runs, and drops N3, which those were. The
devices and VA-API docs say what iHD lists for HEVCMain12 and which of its
surfaces such a stream decodes into, P012 with the samples at the top, and how
a frame lands: an 8-bit one narrowed by the CPU, each sample's top byte, and a
10-bit one copied as P010.
2026-12-02 11:00:02 -08:00
Anees Iqbal 6d1cdb90ff 🆕 Decode HEVC 4:2:0 range extensions at 8 and 10 bits on iHD
iHD's HEVCMain12 decoder lists YUV420, YUV420_10 and YUV420_12 render targets
but P012 and P016 surfaces alone, and fails a picture's decode into NV12
(vaEndPicture's invalid parameter on the Iris Xe, potluck job m3-max-78771). So
an arm64 guest's 4:2:0 range extensions stream of 8 or 10 bits, such as Main
Intra or Main 10 Intra, was refused there and decoded in software.

- The VA crate's HEVC decoder now tries Main 12's P012 after NV12 or P010 for
  those streams, taking the first whose surfaces the driver lists
  (range_extensions_decoders). The pool records the stream's depth
  (SurfacePool::new_of_depth; a Windows context's shape keeps it), so a frame
  answers the stream's bit_depth, its samples at the top of P012's 16 bits.
- ReadBack::copy_into narrows an 8-bit stream's P012 frame into NV12 planes,
  each sample's top byte (Frame::copy_converts), and copies a 10-bit one's into
  P010 planes as it lies.
- The VA-API arm takes such a stream where any of those decoders passes its
  check, and counts each narrowed picture as converted by the CPU.
- The conformance suite decodes x265's Main Intra and Main 10 Intra streams at
  4:2:0 against ffmpeg's NV12 and P010 references.

For the guest: on a host whose VA-API driver decodes HEVC Main 12 into P012
alone (the Iris Xe's iHD), an arm64 guest's 4:2:0 range extensions streams of
8 and 10 bits now decode in hardware, landing in 420v and x420.
2026-12-02 11:00:02 -08:00
Anees Iqbal d597bf1608 ✅ Pass VA encode tests with a note where none is listed
On the RTX 3090's VA path, whose driver decodes alone, the VA crate's three
encoder tests panicked ("the driver encodes nothing", "an NV12 profile") and
reims-vgpu's six encode tests panicked, three at "the driver encodes neither
H.264 nor HEVC" and three at the arm's vendor check before any query
(m3-max-79247). A test that cannot hold on a device must not fail there.

Each test now asks the driver's encoders first (encoder_support, from
vaQueryConfigEntrypoints, never the vendor's name), and where the driver lists
none for the profiles it codes, it says so on stderr and passes. reims-vgpu's
tests on the rt device ask before tested_gpu::check_rt. On a driver that lists
encoders every test runs as before.

Tests: red m3-max-79247 (the nine panics); green on the 3090's VA path
m3-max-79320 (the nine pass with their note) and on the Radeon 780M m3-max-79318
(each runs and passes).
2026-12-02 11:00:02 -08:00
Anees Iqbal 3975719e28 🎨 Name the video call an exit waits for, not the runtime's wrapper
The exit gate names where each step it waits for began, its caller's site.
Every step of the video crates' threads was taken inside reims-vgpu's video
runtime, so a close that waited for one named video/runtime.rs:61 whatever the
call, as boot m3-max-79085's close did.

Runtime::exit_step_at now takes the site, and exit_step, on dyn Runtime, passes
its caller's. The VA calls (Calls' call, try_call, wait_call and release, and
Display's wrappers of them) are #[track_caller], and an order carries its
caller's site to the call thread, so a step names the driver call that took it.
The device waits' sweep, the import reaper's drops, the display's open and the
NVIDIA arm's call threads name their own lines. The gate's step_at takes a site
its caller names.

A diagnostic only: what the guest and the host observe is unchanged.

Tests: a fake runtime records each step's site; a call, a try_call and a
release made at once, and a wait_call and a release ordered on the call thread,
each begin at their caller's line (red with the sites not carried,
m3-max-79280, where they named calls.rs's own lines; green m3-max-79283, with
the VA calls', the gate's and the video runtime's tests, rustfmt, and clippy for
Linux and Windows). The gate's step_at names the site it is given.
2026-12-02 11:00:02 -08:00
Anees Iqbal 201d165e47 🐛 Send VA's quality level alone, and the nearest the driver takes
iHD 26.3.5's HEVC encoder takes quality levels 1, 4 and 7 of the 7 its config
lists, and answers success for a render that carries another level with a packed
header after it, then codes at the refused level (read in its source:
media_ddi_encode_hevc.cpp's ParseMiscParams, RenderPicture and
EncodeInCodecHal). An arm64 guest's session at a Quality of 0.9, level 2, hung
the Iris Xe's render engine (boot m3-max-79085, bugs.md B102). The refused level
is the likely trigger, unconfirmed.

The VA crate now renders the quality level alone, first, where a picture sends
its misc buffers (IDR pictures and a rate control change), so the driver's
answer to it is its own. A refused level gives way to the nearest level the
driver takes, the better quality first at a tie, before the picture's other
buffers, and the session keeps the level taken. VA-API's text allows the form:
a picture's buffers go in as many renders as the caller makes, and va.h's own
misc parameter example renders one alone. The choice is the driver's answer
alone, with no driver name, version or card in it, and a driver that takes
every level sees the same buffers, the level in a render of its own.

For the guest: a session asks the same quality as before. Where the driver
refuses that level, the stream codes at the nearest level the driver takes
rather than at the refused one: on the Iris Xe's HEVC, 1 for 2, 4 for 3 and 5,
and 7 for 6. reims-vgpu counts such a session as
video-encode-quality-level-adjusted and logs it once a session. x86-64 guests'
encoder asks level 4, which iHD takes, so they see no change, nor does a session
on radeonsi, which takes every level. iHD's H.264 encoder copies the level into
the sequence as it parses the sequence buffer (read), so its first sequence now
takes the asked level too, where it took the context's earlier one. HEVC Main
4:2:2 10 stays held back (B102).

Ledger (bugs.md B102 and U37). Read from code: iHD's masked refusal, above, a
lead until the guest's 4:2:2 case encodes under the fix, which waits for the
owner's word. Run: a fake driver modelled on that read gives the refused level's
render a failure and the next choice is taken (red m3-max-79207 at the masked
path, green m3-max-79223 with rustfmt and clippy). No report on file names an
Intel host's HEVC encode at a level iHD refuses but boot m3-max-79085's: the
Intel rows on file (B98 to B101) are x86-64 guests', at level 4.

Run on hardware: on the Radeon 780M (radeonsi) the VA encode tests and the new
one, asked level 2 and taken 2, 52.0 to 54.9 dB luma (m3-max-79243,
m3-max-79256; m3-max-79318 with the commits after it). The RTX 3090's VA driver
lists no encoder, so no level reaches it (m3-max-79247), and NVENC takes no VA
buffer: its encode tests pass (m3-max-79251). On the Iris Xe (iHD 26.3.5), one
encode of the 4:2:0 HEVC Main test asked at level 2: taken 1, 52.5 to 53.2 dB
luma, and no GPU hang or reset in the kernel's log (m3-max-79388).
2026-12-02 11:00:01 -08:00
Anees Iqbal d6511054f5 ✅ Test a reset past a walk held in a fill or a compile
The settle at the device's reset sets on the CPU the surface timeline of each
queue the reset ended where a committed buffer waits past what the queue
signalled (170b7e9905). Its test covered a named buffer the host never took.
The same GPU wait forms where the named buffer was taken and its walk is held
as the reset comes: its dispatch waiting for its stage's fill outside the
process, or for a pipeline still compiling. Either can run far past the
settle's 30 s bound (docs/qemu.md: 14 to 24 s for each of NVIDIA's big glass
pipelines past its import budget), and only the control thread's reset cuts
them short, which waits behind a ring-0 message that may wait for the BQL
QEMU holds around the reset.

The tests hold the control thread behind a ring-0 sampler create held in its
platform call, commit a second process's buffer that waits on the GPU for the
writer's seqno 1, hold the writer's walk, and reset on a thread of their own:
the settle sets the writer's timeline, the waiting buffer runs, and the reset
returns with no time passed on the platform's clock. Once the control thread
goes on, its reset cancels the fill.

Job m3-max-79417 ran them on the fake platform. Green: both pass, with fmt and
the workspace's clippy clean. With the settle's timeline set removed: both die
at the bound, as does the never-taken test.
2026-12-02 10:57:52 -08:00
YXC0915 2df30ffea9 🆕 Pin the organization runtime dependencies [skip ci]
Resolve metal2vulkan and reims-util from the maintained Reims-Go repositories. The new Vulkan pin establishes a suspend baseline for these build inputs.
2026-12-03 02:53:58 +08:00
Anees Iqbal ef9fed73df 📝 Document HEVC Main 4:2:2 10 encode and its hold [ci skip]
The formats table lists HEVC Main 4:2:2 10 encode on the Iris Xe as built and
held back (B102), with the GPU repack a frame costs, and drops N4 from what is
not built. bugs.md's B102 records the arm64 guest's session that hung the Iris
Xe's render engine (boot m3-max-79085), what the source read says of its likely
trigger, and that its confirming run waits for the owner. vaapi.md describes the
VA crate's Main 4:2:2 10 encode: EncSlice alone, a Y210 input imported at the
layout's bytes. lessons.md records the declared-size trap.
2026-12-02 10:44:57 -08:00
Anees Iqbal 7bb1e2d62b 🐛 Ask again for source buffers when a set changes their format
The host asked an arm64 guest for its source buffers' attributes (Epba) only
when the encoder opened, at esta, before the guest's session sets its profile.
A session that then set a profile of another depth kept the first answer:
an HEVC session that set HEVC_Main10_AutoLevel after esta got 420v buffers
from its pool for a Main 10 stream, whose encoder takes x420 frames. An arm64
macOS 26 guest showed it with Main 4:2:2 10: 420v buffers where an M3 Max's
encoder gives x422 ones (boot m3-max-79012), and x422 ones once Epba was sent
again (boot m3-max-79085).

A set the open encoder takes before its first frame that changes the format
it takes its frames in now sends Epba again with that format, and the set's
reply is the guest's answer to it. From the first frame on the stream keeps
its format, and a set asks for nothing.

For the guest: a VideoToolbox session that sets HEVC_Main10_AutoLevel after it
is created now gets x420 source buffers from its pool, and its set's reply
waits for the guest's own answer to the request. Main 4:2:2 10 stays held
back from the list, so no set reaches x422. Sessions that set no such profile,
or set it past their first frame, see no change.

Tests: a Main 10 set before the first frame asks again for x420 and answers
with the guest's status; the same format and a set past the first frame ask
for nothing.
2026-12-02 10:44:57 -08:00
Anees Iqbal b675d53fff 🐛 Hold HEVC Main 4:2:2 10 back from arm64 guests' encoders
An arm64 guest's session of HEVC Main 4:2:2 10 on an Iris Xe (iHD 26.3.5,
the EncSlice entrypoint, whose encode runs on the render engine) hung the
GPU's render engine on its first frame: i915 reset the encoder's context, the
host's 5 s wait failed the session, and no frame came out (boot m3-max-79085:
640x360, a constant QP of 10, VA quality level 2). Its trigger is not yet
established, and a run that could hang the GPU waits for the owner, so the
planner's interim holds the profile's listing back until it is.

repacked_profiles now leaves Main 4:2:2 10 out where the device makes an
encode session's filler too, saying so once. The rest of its encode (the
codec's 4:2:2 SPS, Y210 inputs, the repack) stays built and tested, and this
commit is reverted with the trigger's fix.

For the guest: an arm64 guest's paravirtual HEVC encoder lists no Main 4:2:2
10, and a session's set of HEVC_Main42210_AutoLevel is refused, as it was
before the profile's encode was built. Other profiles see no change.

Tests: Main 4:2:2 10 is left out of the list where the device makes a filler,
the driver's other profiles kept.
2026-12-02 10:44:56 -08:00
Anees Iqbal 741a6bfc4c 🆕 Encode HEVC Main 4:2:2 10 for arm64 guests on VA-API
An arm64 guest's VideoToolbox can ask its paravirtual HEVC encoder for
kVTProfileLevel_HEVC_Main42210_AutoLevel, and the Iris Xe's iHD lists a
VAProfileHEVCMain422_10 encoder. The device now lists that profile where the
driver encodes it and the runtime device's GPU can repack a frame, so the guest
gets a hardware Main 4:2:2 10 export.

- The codec writes Main 4:2:2 10's profile_tier_level (general_profile_idc 4
  and its constraint flags), chroma_format_idc 2, the conformance window in
  4:2:2's units, and its levels with Table A.8's CpbVclFactor of 1667.
- iHD's encoder takes packed YUY2 or Y210 surfaces alone, so the VA crate's
  encoder takes one Y210 plane as that profile's input (TargetFormat::Y210,
  imported linear or in Y tiles, exported as one layer), and uploads no 4:2:2
  frame.
- The guest's x422 and xf22 frames (the paravirtual encoder asks for x422, as
  the M3 Max's encoder does for the profile) are repacked by the new
  videoEncodeFillY210 kernel into that input: one GPU copy a frame, as a 4:2:0
  frame's fill is, and a frame the repack declines fails. The metallibs are
  rebuilt with it.
- An encoder input's dma-buf is imported at the layout's bytes, not at the
  block's whole allocation: iHD read a Y210 input declared at its 393216-byte
  allocation (a 360448-byte layout) at 8 bytes a pixel, coding at 9.4 dB, and
  the same input declared at 360448 at 59.3 dB. NV12 and P010 inputs, declared
  the same way now, code as their upload does, byte for byte, as before.
- The profile is listed only where the arm's filler is made
  (repacked_profiles), and never on the x86-64 wire or to NVENC, whose
  params_of now refuses a profile it is not asked to encode.

For the guest: on a host whose VA-API driver encodes HEVC Main 4:2:2 10, an
arm64 guest's paravirtual HEVC encoder now lists Main 4:2:2 10 and encodes it
in hardware. Other profiles, x86-64 guests and NVENC hosts see no change.

Tests: the codec's 4:2:2 SPS and levels; Y210 imports and one-layer exports;
the repack's arguments, refusals, a fake-platform pass and an rt GPU pass
against the CPU's packing; on a VA-API host, a Y210 input's stream and a guest
4:2:2 frame repacked by the GPU, each coding a Main 4:2:2 10 stream that the
driver decodes back above 40 dB.
2026-12-02 10:44:56 -08:00
Anees Iqbal f8ba3568b2 🐛 Release surface waits for buffers a reset never lets be taken
A buffer of one queue can wait on the GPU, on another queue's surface
timeline, for that queue's buffer the host has not taken yet (surface_order,
"A buffer named before the host takes it"). The device's reset ends the named
queue's ring, so that buffer is never taken, and only the control thread's
reset signalled the timeline, through queue_ended as it drops the contexts.
The host's settle at the reset waits for the waiting buffer, and does not wait
for the control thread, which may itself wait for the host's lock around the
reset. Read from code, not shown by a run: QEMU calls the reset under the BQL,
and a ring-0 message whose callback waits for the BQL (a queue create's
route_doorbell) holds the control thread's reset behind it, so the settle
waited out its 30 s bound and the process ended at "the device's reset".

The settle now sets each such timeline on the CPU, at once, to the highest
value waited for, where the reset ended the timeline's queue (its poster is
stale), and counts it among the signals for buffers that did not run. No live
waiter sees a value set so: the control thread's reset drops every queue's
timeline (SurfaceOrder::reset) before it carries out any ring-0 message the
guest published after the reset, so a queue the rebooted guest makes has a
timeline of its own, made at its create, and its poster is not stale, so the
settle sets none of it. rt's shared event keeps the higher of what the GPU
signalled and what the host set, so the old queue's own later signals of
lower values change nothing.

Tests:
- a_reset_with_its_control_thread_held_releases_a_wait_for_a_buffer_never_taken
  holds the control thread behind a ring-0 message whose platform call is held,
  standing for the BQL. Red at m3-max-79296 without the settle's set: the reset
  died at its bound. Green at m3-max-79298.
- the_reset_sets_only_the_timelines_of_the_queues_it_ended (decoder) holds the
  guard: a queue the reset did not end keeps its timeline, and a timeline is
  set once.
2026-12-02 10:44:56 -08:00
Anees Iqbal 6fd2540186 🐎 Keep function names, not libraries, in pipeline states
The host kept every library the guest released for as long as any pipeline
state made from one of its functions lived. A compute state kept its kernel's
Function, a render state its vertex and fragment Functions, and a compute
encoder the kernel of the state set last, only to name them on the first line
of each kind of rt's refusals of their dispatches and draws. A Function holds
its whole Library, every function's bytes. metal2vulkan's L52 measured up to
79.3 MB of released libraries held in a states-only play, and its fix stops
rt's own states keeping a released library whole; ours kept them whole
regardless.

They now keep a FunctionName: the first 8 bytes of the library's SHA-256, the
function's index and its name, the values the names are made of. The first
lines, the refusal keys and the kept AIR's records name a function byte for
byte as before: a_function_s_name_names_it_as_the_function_did pins the form,
and the expectations of a_site_s_functions_are_named_on_its_first_lines and
the refusal-keys tests are unchanged.

rt's Library has no weak or count API, and at the pin rt's state shares the
library with ours, so the tests read what our states keep (KeptLibrary, test
builds only). Before, a compute state of compute_add kept 3597 bytes and a
render state of two numbered_samplers functions 36698 once the guest released
them (m3-max-79336, RTX 3090); now both keep none, and name their functions as
the released functions were named
(a_compute_state_keeps_no_released_library_on_vulkan,
a_render_state_keeps_no_released_library_on_vulkan).
2026-12-02 10:44:56 -08:00
Anees Iqbal 25488bee35 ✅ Write the shared image's path as TOML in the renewal test
a_renewal_waits_for_another_vm_on_its_image wrote the second VM's vm.toml
with the shared OpenCore image's path straight into a TOML basic string.
On Windows the path's backslashes then read as escapes, so the file failed
to parse and the test panicked before it reached the renewal (Windows leg
dev8a47-win, m3-max-79253). The path now goes through testenv::toml_path,
as the crate's other tests write theirs. Tests only; nothing changes for
users.
2026-12-02 10:40:01 -08:00
Anees Iqbal 2290bad097 🎨 Format the window test and drop the motion test's unused positions
Batch bu's lint legs failed on two lines from the hidden-cursor commits.
rustfmt wants the tablet assertion in displays.rs split across lines. In
motion.rs, a_hide_whose_cursor_stays_put_under_the_tablet_is_no_games
looped over three positions that tablet_moved stopped taking when it
became per window, so the variable was unused (-D warnings). The loop now
counts its three moves. Tests only; nothing changes for the guest or the
host.
2026-12-02 10:29:49 -08:00
Anees Iqbal 506869c8a3 📦 Rebuild both sets and the ROM's record for hidden places
The wire header gains HIDDEN_PLACES and POINTER_LOOK, and the x86-64 kext
reports its hidden cursor's places, so the x86-64 set is rebuilt with its
record, on top of GUEST_BUNDLE's sets. The arm64e kext's binary is
unchanged, since the arm64e build sends no HIDDEN_PLACES; its record and the
ROM's name the new header. The ROM's bytes are unchanged.

Built by make -C firmware prebuilt, make -C guest prebuilt and make -C guest
prebuilt-arm64e on the Mac (job m3-max-79214), whose make -C guest test,
set check and ROM check passed.
2026-12-02 10:19:17 -08:00
Anees Iqbal 14eb1b4b2b 📝 Say which recordings and shares keep the normal pointer [ci skip]
An x86-64 guest's kext now reports where its hidden cursor goes, so the
window keeps the normal pointer through macOS's own screen recording, and a
game played in one gets it too. Screen Sharing hid no cursor in the proof
boot. Other apps' shares are not measured, and an arm64 guest's kext reports
no hidden places, so the release chord stays the way out there.
2026-12-02 10:19:17 -08:00
Anees Iqbal 3ff544f056 📝 Register that a game's hide counts once its cursor follows
The window's game entry changes with the hidden places: with a guest whose
kext reports where its hidden cursor goes (an x86-64 guest's), a hide counts
as a game's only once that cursor has followed the absolute pointer, so a
system recording, and a game played in one, keep the absolute pointer.

Measured on gem10's 3090 with an x86-64 macOS 26.7.2 guest (potluck jobs
m3-max-79157 and m3-max-79158), moves of 25 reports 8 ms apart: the
pointer drove the guest's mouse on the hide's second move in 8 games of 8,
17 to 381 ms after that move's first report, and never on its first. A game
that shows its cursor and hides it again needs two moves again after each
hide, where it needed one: in the rounds whose game showed its cursor for
200 ms every 2 s, the move after the hide that followed a show never drove
the guest's mouse. Through a system recording no move drove it, and macOS's
Screen Sharing hid no cursor in either session, so its moves stayed the
tablet's.

The entry gains the hidden-place tests as guards, and its manual check the
recording and Screen Sharing.
2026-12-02 10:19:17 -08:00
Anees Iqbal 4145fe7989 🐛 Ask where the hidden cursor goes from every window's pointer
The device sent POINTER_LOOK from PointerLink::pointer_at, which a window's
pointer calls only through tell_pointer, and reims-vgpu gives a window that
only on a device of several displays. So in a VM of one display no look
went, the guest never reported its hidden cursor following the tablet, and
no hide of a guest that reports hidden places counted as a game's: in the
proof boot on gem10's 3090 (potluck job m3-max-79110, x86-64 macOS 26.7.2),
the disassociated game's moves stayed the tablet's in every round.

The look is now PointerLink::tablet_moved, and every window's pointer
callback calls it (tell_tablet), before tell_pointer's hold where a device
has several displays, so an event held back from the tablet asks nothing.
A one-display window's test drives it through the window the device opens.
2026-12-02 10:19:17 -08:00
Anees Iqbal aa5f0596f4 🐛 Report where the x86-64 guest's hidden cursor goes when asked
The device counts a hide as a game's once the guest reports its hidden
cursor following the tablet (the commit before). WindowServer moves a hidden
cursor with no setCursorState, so the kext must read its place itself: the
framebuffer's shared cursor state, which the tablet moves while a game hides
the cursor and which a system recording leaves where it hid it (lane
sharecur, potluck jobs m3-max-78716 and m3-max-78811, x86-64 26.7.2).

Once its mouse is up after each start, the x86-64 kext sends HIDDEN_PLACES.
On each POINTER_LOOK it looks every 10 ms, for 150 ms past the last one, at
each display whose cursor the last MOVE_CURSOR hid, and reports each new
place as a MOVE_CURSOR with visible 0, in MOVE_CURSOR's terms (the shared
place plus the hide's difference from it). Reports and setCursorState's
posts share a lock, so none lands after a show. Nothing is read while the
cursor shows or outside those looks.

For the guest: none of this shows. A recording keeps the host's absolute
pointer, and a game's mouse is driven a move later.
Mixed, new kext with an old host: the host answers HIDDEN_PLACES
UNKNOWN_COMMAND, which no thread waits for, and sends no POINTER_LOOK, so
the kext never looks (hidden_cursor_test, "no POINTER_LOOK: no look").
Mixed, old kext with a new host: it sends no HIDDEN_PLACES, and every hide
counts as before (the host's
a_guest_that_reports_no_hidden_places_hides_as_before).
The arm64e kext is unchanged.
2026-12-02 10:19:17 -08:00
Anees Iqbal ea84b97e0f 🐛 Count a hide as a game's once its hidden cursor follows the tablet
macOS hides the hardware cursor for as long as the guest's screen is
recorded, and the window read that hide as a game's: 50 ms after it, the
captured pointer drove the guest's own mouse, so a person recording the
screen lost the absolute pointer, could not cross to another display, and
got the guest's acceleration on top of the host's (ledger row 244).

The hidden cursor tells the two apart (lane sharecur, x86-64 26.7.2). While a
game hides it, WindowServer keeps writing its place into the framebuffer's
shared cursor state, and the tablet moves that place: disassociated,
associated, warped and captured-display games all did (potluck jobs
m3-max-78716 and m3-max-78811). A system recording leaves it where it hid
it while the tablet and the guest's mouse move the cursor (m3-max-78811).

So the wire gains HIDDEN_PLACES (command 12: the guest reports where its
hidden cursor goes) and POINTER_LOOK (event 0x107: the host's pointer moved
the tablet during a hide). For a guest that declared it, each tablet move
during a hide sends POINTER_LOOK, one every 50 ms at most, until the guest
reports its hidden cursor at a new place, a MOVE_CURSOR that leaves it
hidden. Until then cursor_hidden_for reads None, so the window keeps the
tablet. A show and each new hide start over. A MOVE_CURSOR that leaves a
hidden cursor hidden no longer reaches the screen (the window and the
host's cursor callbacks): nothing of it shows.

For the guest: a game's mouse is driven a move later. A recording keeps the
absolute pointer.
Mixed, old kext with this host: it sends no HIDDEN_PLACES, so it is sent no
POINTER_LOOK and every hide counts as before
(a_guest_that_reports_no_hidden_places_hides_as_before).
Mixed, new kext with an old host: the host answers HIDDEN_PLACES
UNKNOWN_COMMAND and sends no POINTER_LOOK, so the kext never looks (the
kext's hidden_cursor_test, "no POINTER_LOOK: no look").
2026-12-02 10:19:17 -08:00
Anees Iqbal 39da9779ea 🐛 End a reset's settle within its bound, and none inside a raise
The reset batch hung on a_raise_may_call_the_device_at_once, past its 540 s
slow mark, on every leg. Its raise resets the device, as the header lets it.
On the doorbell's thread, inside mmio_write_taking, the raise comes as a
CB_SUBMITTED is answered, with the decoder's contexts' lock held. The reset's
new settle (Host::reset_settles) then took that same lock and waited for it
for good: gdb's stacks in job m3-max-79063 show the thread blocked in
release_waits_for_reset on the lock it holds. api.md section 5 lists that
lock, a context's table read and the device caches' lock among those the
library may hold around a raise, and said no function of the device takes
them. The settle took all three.

A behaviour change the host observes, in two parts:

- A reset made inside the device's raise, on the raising thread, asks for no
  settle and waits for no GPU work, so that work may write the guest's memory
  after the reset returns: the one reset without the settle. That thread may
  hold what the settle takes, and the work it raises for began before the
  reset and ends only once the reset returns. The device crate counts the
  raises on each thread (raise_through) and skips Host::reset_settles inside
  one. QEMU's raise never resets the device or writes STATUS.
- The 30 s bound now covers every wait of the settle. Before, it covered only
  the GPU wait, and the hang was a lock taken before that wait, which no timer
  reached. The settle now takes the contexts' lock, each context's table read
  and the caches' lock in 10 ms slices against the same bound, on the
  platform's clock. Past the bound the process ends with the bound's death,
  naming the lock.

The raise rule widens with this: no raise_interrupt, on any thread, may wait
for a lock the host holds around a reset. The settle waits for locks the
library may hold around any raise, not only for the threads that run completed
handlers. QEMU's raise waits for none: reims_graphics_pci_raise_interrupt_cb
writes the vector's irqfd, or takes msi_lock, which the vector's mask and
unmask hold under the BQL and which waits for nothing else, or schedules a
bottom half.

The header's raise and reset docs and docs/api.md sections 1 and 5 say so.
Tests: a_raise_may_call_the_device_at_once, unchanged, hung before this change
and passes now; a_reset_inside_a_raise_asks_for_no_settle (device crate); and
a_reset_whose_settle_waits_past_the_bound_for_a_lock_ends_the_process.
2026-12-02 10:19:13 -08:00
Anees Iqbal 0cebed6f6b 📝 Move vendor/qemu to the comment on a reset's settle
The register accesses' comment in reims-graphics-pci.c said an access waits
at most for the command the control thread is taking. Since the previous
commit a STATUS write of 0 also waits for the settle of the GPU work the
guest committed before it, which waits for nothing of QEMU's, so the
accesses still need no BQL. The fork's 80d97bea2e says so, a comment alone.
2026-12-02 10:19:13 -08:00
Anees Iqbal 70698aef1c 🐛 Wait at a reset for the GPU work the guest committed before it
A behaviour change the host and the guest observe. design.md says nothing
begun before a reset reaches the guest after it, as a GPU's reset stops its
DMA. But the reset returned while the guest's command buffers committed
before it were still on the GPU: they and the completed handlers that merge
copied ranges back went on writing the rebooted guest's memory.

Now the reset, on the thread that resets (rvg_graphics_device_reset, which
QEMU calls under its BQL, or the guest's STATUS write of 0 on the vCPU),
ends with Host::reset_settles. reims-vgpu first sets every event the
guest's buffers could wait for past every value, and each deferred device
cache copy's event to its number, so no buffer waits for a signal nothing
will send any more. Then it waits for every command buffer committed before
to complete and run its completed handlers (GpuDevice::settle). It waits
for no thread of the device's: a route callback on ring 0's thread or the
control thread takes the BQL. It logs its time and how many it waited for.

The settle is bounded at 30 s, and past it the process ends: a new death,
"the device's reset". Only a GPU no driver recovered reaches it. The drivers
end hung work as a lost device, whose command buffers rt then completes,
failed: amdgpu at 2 s (lockup_timeout's default), and i915's last resort,
its heartbeat's engine reset, at most 25 s after work hangs (a pulse at the
next 2.5 s tick, raised one level a tick to the highest three ticks later,
then twice the 7.5 s preempt timeout; read from intel_engine_heartbeat.c).
The code is absent from the counts of the last good boots, as a new one is.

The BQL's hold grows by the settle. Typically that is the time the GPU
takes to finish what the guest committed before the reset: a settle over
a 1 MiB fill committed just before it took 1.3 ms on an RTX 3090, and one
with nothing in flight waits for none. At worst it is 30 s, only on a GPU
no driver recovered. The host gains one rule: raise_interrupt on the
platform's thread that runs a completed handler must not wait for a lock
the host holds around a reset. QEMU's waits for none: the irqfd's write,
msi_lock, which waits for nothing else, or a bottom half.

The header, docs/api.md (sections 1 and 4, and 5's locks around
raise_interrupt), design.md's Reset and qemu.md's BAR 0 say so. Tested by
a_reset_returns_once_the_guest_s_command_buffers_before_it_have_completed,
red before this change (the reset returned with the buffer on the GPU), and
a_reset_whose_gpu_work_runs_past_the_bound_ends_the_process.
2026-12-02 10:19:11 -08:00
Anees Iqbal 27f5e56340 🆕 Let a device wait for its command buffers committed before
The device's reset is to wait until the guest's GPU work committed before
it can no longer write the guest's memory: until each such command buffer
has completed and run all its completed handlers, since a handler may still
merge a copied range back into the guest's pages after rt's first handler
takes the buffer off the list of those in flight. Nothing tracked that end.

GpuDevice::settle(bound) waits for every command buffer committed on the
device before the call to complete and run all its completed handlers, or
to have its commit refused, at most `bound`, and answers how many it waited
for; past the bound it names the oldest left, as the loss's line names a
buffer. On rt the device's Flights keep its own command buffers (not a
swapchain's clear) unsettled from their listing until hand_on has run the
last handler, on rt's thread or the handed-on one, or rt refused the
commit. The testkit numbers commits and settles them as their completed
handlers end, and waits on virtual time only where a test holds settles,
so the tests that leave work committed across a reset run as before.

Nothing calls it yet; the reset's use of it is the next commit. Tested by
a_settle_waits_for_the_platform_s_command_buffers_through_its_number and,
on the GPU, a_settle_waits_for_a_command_buffer_and_its_handlers_on_vulkan
(on an RTX 3090, a settle over a 1 MiB fill committed just before it took
1.27 to 1.43 ms).
2026-12-02 10:19:10 -08:00
Anees Iqbal 79e0c63021 📝 Say the register write calls the route callbacks
The doc of rvg_graphics_device_mmio_write_taking named raise_interrupt
as its only callback, but a STATUS write of 0 resets the device, which
drops the ended queues' doorbell routes on the writing thread through
route_doorbell and route_doorbell_page, and a DOORBELL_PAGE_BIND write
that binds a page to another context drops the routes on the page
through route_doorbell_page there too (the device crate's module doc).
docs/api.md section 4's row already says so; the source doc and the
header now say the same. Nothing changes for the host or the guest. The
header is cbindgen's output of the new doc.
2026-12-02 10:19:10 -08:00
Anees Iqbal eff25e2492 📝 Say the reset calls the route callbacks
The doc of rvg_graphics_device_reset said it calls back never, but the
reset ends every command queue and drops each one's doorbell route
there, on the calling thread, through route_doorbell and
route_doorbell_page (Shared::reset's unroute). docs/api.md section 4's
row and its "Calling back" list already say so; the source doc and the
header now say the same. Nothing changes for the host or the guest. The
header is cbindgen's output of the new doc.
2026-12-02 10:19:10 -08:00
Anees Iqbal f9d334b0c0 📝 Say how dsound trims its reserve and rate [ci skip]
qemu.md's "Windows hosts: sound" says what vendor/qemu 364cd364 does: the
trim of a dsound voice's margin to 15 ms and of its rate to the device's
clock, through the mixing engine's resampler. It also says why
DirectSound's own frequency was not used (each change of it shifted the
audio, a click). It gives the mini's base and fix runs, with the drift
phase, beside the Linux host's wait to PipeWire's ring, and the A/V lead a
player now shows on each host. known-issues.md's "Sound comes after video
on Windows" gives 0.07 s for 0.1 s, and the Linux host's 0.03 to 0.05 s.
lessons.md records the SetFrequency trap and how to spot the next one.
2026-12-02 10:19:10 -08:00
Anees Iqbal 339d12f775 🐎 Move QEMU to dsound's trimmed playback reserve and rate
vendor/qemu 364cd364 trims a dsound playback voice to its guest's posts and
its device's clock, through the mixing engine's resampler. The voice still
starts 60 ms past DirectSound's write cursor, then plays a little faster or
slower than its own rate, within 1000 ppm, until its margin past the write
cursor comes down to 15 ms at its least and the device's drift is taken up.

What the guest hears on a Windows host: its sound about 35 ms sooner. A
period's first frame waited 106.7 ms to play at the median at rest (p99
129.3) and now waits 71.7 (p99 96.4); busy 104.6 and now 72.7. A device
whose clock runs fast no longer runs the audio out: forced 227 ppm fast,
the old reserve had 3 gaps of silence in 834 s and the trim none. 0 clicks
at rest, busy and in the drift phase, against the base's 0, 0.93 and 0.58 a
minute. The pitch moves by at most 1.7 cents. Measured on the mini, jobs
m3-max-78857 (base) and m3-max-79145. The guest is still told 2 ms of
latency, so video still leads sound, now by about 72 ms
(docs/known-issues.md).

Other hosts: nothing changes. Only dsound trims, and the resampler's new
setter is used nowhere else. The fork's tests: test-dsound-ring and the new
test-audio-rate.
2026-12-02 10:19:10 -08:00
Xiaochi You 6b7e7d7cad Merge pull request #1 from YinLiaoCo/feat/window-file-drop
feat(window): forward SDL3 file and text drops with normalized coords to host bridge
2026-12-03 02:08:14 +08:00
Anees Iqbal 8a470a3874 📝 Say the create refuses a memory map whose ranges overlap [ci skip]
The config's memory_map said only that its ranges may not overlap, and
api.md's status table did not list the refusal. The create refuses, with
RVG_ERR_INVALID_ARGUMENT, a map whose ranges overlap or run past the
address space (core's MemoryMap::new), and one whose ranges are NULL but
counted (the C API's memory_map). The field's doc, the header and the
table now say so.
2026-12-02 09:50:13 -08:00
Anees Iqbal b7f2948592 🐛 Refuse a second pool_added of a piece on its way back
docs/api.md and pool_added's doc refuse a second pool_added of one piece
(RVG_ERR_INVALID_ARGUMENT). But a piece the pool sends back (the guest
emptied it, past the delay) went to Removing whatever it was before, and an
add there answered RVG_OK, also where the host had added the piece already.

Removing now keeps whether the host added the piece. The first add of a
piece given back before the host's add answered is still taken; a second
is refused. A behaviour change the host observes: that second add answers
RVG_ERR_INVALID_ARGUMENT. QEMU adds each piece once. Tested by
a_second_add_of_a_piece_on_its_way_back_is_an_invalid_argument and
a_piece_given_back_before_the_hosts_add_answers_still_waits_for_the_remove,
both red before this change (the second add answered Ok).
2026-12-02 09:50:13 -08:00
Anees Iqbal be57a30523 🐛 Answer a NULL device with INVALID_ARGUMENT where a status answers
The header's preamble and docs/api.md section 1 say a NULL handle is
RVG_ERR_INVALID_ARGUMENT from every function that returns an RvgStatus, and
ends the process only from a function without one. Six of the functions
that return a status ended the process instead, taking the handle as
rvg_graphics_device_reset does: pool_added, pool_removed, pool_grow,
set_doorbell, read_display and read_display_at.

A behaviour change the host observes: they now answer
RVG_ERR_INVALID_ARGUMENT for a NULL device, and the two reads write nothing
to the destination and a size of 0 by 0, as for a display past the
device's count. Their Safety lines allow NULL. QEMU passes no NULL device.
Tested by a_null_device_is_an_invalid_argument_where_a_status_answers,
which ended with SIGABRT at its first call before this change.
2026-12-02 09:50:13 -08:00
Anees Iqbal 21d25716bd 🆕 Rebuild both kext sets and the ROM's record for GUEST_BUNDLE
guest/prebuilt and guest/prebuilt-arm64e built from this tree on the Mac
(make -C guest prebuilt, prebuilt-arm64e): ReimsGraphics, whose accelerator
writes GUEST_BUNDLE once a boot, and RgfxGate, which publishes its install
pass's result. The option ROM's bytes are unchanged; its record names the
wire header the register's constants changed. prebuilt-check passes for
both sets and the ROM.
2026-12-02 09:49:26 -08:00
Anees Iqbal 629cade8b0 📝 Add the arm64 TCG boot's gap to the guest drivers' measurements [ci skip]
Under TCG, arm64 macOS 26's kexts went on 38 and 35 us after their read of
VERSION, 70 s into the boot: the 60 s window holds there too.
2026-12-02 09:49:26 -08:00
Anees Iqbal 2db89e0c79 📝 Record the boots that measured the guest drivers' lines [ci skip]
Boots through reims-ctl on a Radeon 780M of macOS 26.7.2 measured what
the device's watch and lines rely on: a kext of another build was told 71
and 72 s into the boot, and a healthy kext's next register access came at
most 65 ms after its read of VERSION, against the 60 s window. A throttled
disk did not stop RgfxGate's pass; an older RgfxGate keeps an older bundle,
and the next start repairs it. A start killed mid-renewal left the image as
it was.
2026-12-02 09:49:02 -08:00
Anees Iqbal 41a1bbae72 📝 Say why RgfxGate's pass can leave another build's bundle [ci skip]
The pass leaves the old bundle where the Data volume mounts late, a write
fails or it cannot start, and it publishes which as its result. The sealed
system volume and a bundle in use stop nothing, and the next boot tries
again.
2026-12-02 09:26:00 -08:00
Anees Iqbal 871a331592 🎨 Word the last boot's kexts message as a sentence about the boot
A stopped VM's message read "t's macOS last boot ran ...". It now reads
"t's last boot ran reims-vgpu's macOS drivers of another build ...", and
a running VM's reads "t's macOS runs reims-vgpu's drivers ...".
2026-12-02 09:26:00 -08:00
Anees Iqbal 83e1e38de6 🔥 Drop reims-ctl helpers that only the tests called
holds_other_guest_kexts had no caller left once a start asked
older_guest_kexts what an older image holds, and guest_drivers_said served
only the tests, which now keep it for themselves. clippy's dead-code check
fails on both. The rest is rustfmt's layout of the new lines.
2026-12-02 08:35:56 -08:00
Anees Iqbal a2e6a31afb 🎨 Format the guest drivers' library and wire lines with rustfmt
rustfmt's layout of the lines that the register table test, the device's
watch for kexts of another build and the library's guest drivers' lines
added; no change in what they do.
2026-12-02 08:35:56 -08:00
Anees Iqbal 02c26211a6 🆕 Tell a VM's user when its guest drivers are of another build
Where a guest boots reims-vgpu's kexts of another build, or an older
build's Metal bundle, macOS draws its desktop without Metal, and nothing on
the host said so. The library now writes a line in QEMU's log for each
case. reims-ctl reads those lines from where its last read ended, since
they come early in a boot and the log grows long after them, and says what
to do in the start's output, in reims-ctl show and in the VM's pane:
- kexts of another build: stop the VM, then press U or run
  reims-ctl update-opencore NAME. For a stopped VM this shows only while
  its image still holds the old kexts;
- a bundle not used: the library's words (RgfxGate's pass, and the
  errno of a failed write), then restart macOS or start the VM so
  RgfxGate replaces the bundle, freeing space first where the disk was
  full.

A healthy run says nothing.
2026-12-02 08:35:48 -08:00
Anees Iqbal 7811962a81 🆕 Say when a later boot uses the guest's bundle again
The bundle line stays in QEMU's log for the whole run. After the guest
restarts and RgfxGate replaces the bundle, the line would go on saying the
desktop runs without Metal. The library now writes a "guest bundle used"
line where a boot finds its own bundle after an earlier boot of the same
run did not, so the last line says how the guest draws now.

The installer and Recovery get no line: RgfxGate installs nothing there
(RGFX_GATE_SKIPPED), and they draw without Metal on every host, so the line
would only alarm someone installing macOS.

docs/api.md gains "The guest drivers' lines", which describes all three.
2026-12-02 08:35:48 -08:00
Anees Iqbal abaaad447a 🆕 Tell the host what the accelerator found of its Metal bundle
A guest whose OpenCore image carries the current kexts but whose
/Library/GPUBundles still holds an older build's bundle runs its desktop
without Metal, and until now only the guest's kernel log said why: RgfxGate
had given up on the Data volume, or its write had failed.

RgfxGate now publishes each install pass's result on IOResources,
RgfxGateInstallResult (an RGFX_GATE_* and the errno of its first failed
write, mkdir or rename), before it publishes the pass ended; on x86-64 too,
where only arm64 recorded the state before. The accelerator, as
WindowServer's first connection settles its registration, writes
GUEST_BUNDLE once a boot: what it found, the version another bundle's
marker names, and RgfxGate's pass, so the host can say why.

start_order_test pins what the host's watch for kexts of another build
relies on: ReimsGraphics::start and RgfxAccelerator::start read MAGIC,
then VERSION, then REGION_SIZE_HI, with nothing that waits between the
version check and that read.
2026-12-02 08:35:48 -08:00
Anees Iqbal 89a5d3e280 📝 Name the start order test, and claim no gap not yet measured
The device's watch for kexts of another build named start_order_test.sh,
which is start_order_test.cpp, and said the boots had measured the gap to
the kext's next register access, which no boot had yet: each boot logs it
at info, and the measurements go in the doc once boots have made them.
2026-12-02 08:35:48 -08:00
Anees Iqbal 41be23d6a8 📝 Name the start order test as it is written [ci skip]
The register table's section named guest/kext/tests/start_order_test.sh;
the test is start_order_test.cpp, which reads the kext's sources.
2026-12-02 08:35:48 -08:00
Anees Iqbal 5be18b1995 🎨 Match the wire header to cbindgen's output
cbindgen puts a blank line after the RgfxGate pass constants that
GUEST_BUNDLE added; cargo xtask header --check fails without it.
2026-12-02 08:35:48 -08:00
Anees Iqbal d75fc47da4 🆕 Say on the host when the guest's graphics drivers are another build's
With wire version 3, a guest whose kexts or Metal bundle are of an older
build comes up with its desktop drawn in software, and only the guest's
kernel log said why: the host's user saw a slow desktop and nothing more.

The device now sees both ends, and the library writes one line on stderr
for each, whatever REIMS_VGPU_LOG says, once a boot:
- A kext of another version reads MAGIC and VERSION (twice, for its log
  line) and leaves, writing nothing; a kext of this version reads
  REGION_SIZE_HI right after VERSION, and the option ROM and Ambrosia's
  module read VERSION before they reset the device. So a read of VERSION
  while the device is started, with no other register read or written in the
  60 s after, is told as "reims-vgpu: guest drivers left: ...", on display
  0's refresh, at most once a reset.
- A GUEST_BUNDLE write tells the host what the accelerator found of its
  bundle and RgfxGate's pass; one that is not its own version's is told as
  "reims-vgpu: guest bundle not used: ...", naming both versions and why
  RgfxGate did not replace it.

A guest whose drivers and bundle are this host's gets no line. Each access
after a watched VERSION read is logged at info with its gap, so boots
measure the 60 s margin. The device's tests hold the leave (told after 60 s,
not before, once a reset, again after the host's reset), a driver that goes
on (never told), and GUEST_BUNDLE's fields; the library's, the lines.
2026-12-02 08:35:48 -08:00
Anees Iqbal 77d937cf70 🎨 Format the older-set renewal with rustfmt
rustfmt's layout of the lines that the start's renewal of an image an older
kext set made added; no change in what they do.
2026-12-02 08:35:48 -08:00
Anees Iqbal 2259d94d70 🆕 Add GUEST_BUNDLE, the accelerator's word on its Metal bundle
With wire version 3, a guest whose Metal bundle is of another version comes
up with its desktop drawn in software: the accelerator registers for no bundle
but its own version's, and says why only in the guest's kernel log. Nothing
told the host, so a user saw a slow desktop and nothing saying why.

GUEST_BUNDLE (0x054, WO) is where the accelerator will say what it found as
WindowServer opened the display, once a boot: its bundle, another version's
(with the version the bundle's marker names), none, or RgfxGate's pass not
ended; and RgfxGate's pass, an RGFX_GATE_*, with the errno of a failed write.
design.md describes the register and its values, and how the host also sees a
kext of another version leave at VERSION.

RGFX_VERSION stays 3. No register of an earlier version sat at 0x054, and the
guest acts on nothing of it. A guest set built after this on a host built
before it writes to an offset that host ignores, as Device::mmio_write's last
arm ignores every offset it does not know, so the write changes nothing there.
A guest set built before it never writes the register, so the host built after
it hears nothing and says nothing of the bundle. The size table, whose register
rows the previous commit added, names it at version 3, and both sides' tests
pass with it.
2026-12-02 08:35:32 -08:00
Anees Iqbal 2f002e0cdf ✅ Pin each BAR 0 register's offset to the wire's version
The size table pins each wire record's size to RGFX_VERSION, so a record that
grows without the version moving fails a test on each side. A register that
moved would be misread the same way, and nothing held their offsets. The table
now has one RGFX_WIRE_REGISTER(register, offset) row for each register of BAR
0, which the wire crate's tests and the guest's wire_sizes_test check as each
side compiles the header, with a test that the table names each register the
header defines once, at an offset of its own.

It also names GUEST_BUNDLE at 0x054, the register the next commit adds, which
the header does not define yet: both sides fail here until it does.
2026-12-02 08:35:32 -08:00
Anees Iqbal 2aae00288d 🐛 Renew at start an OpenCore image an older kext set made
A start warned of a VM on reims-vgpu whose OpenCore image lacked a kext of
the guest's set, and made nothing again, because such an image may be one
the user gave (create --opencore), whose own kexts, patches and settings a
new image does not carry over. An image a reims-util made before Graft
(11-08) fell there too: it lists ReimsGraphicsLoader, its two shims,
ReimsGraphics and RgfxGate and no Graft, so its guest kept the old kexts
after an update of the host, and with wire version 3 they leave the device:
macOS drew its desktop in software at every boot, and only the start's
warning said why.

That reason holds only for an image that lists none of reims-vgpu's own
kexts. Only reims-util ever put this set's kexts or the old set's loader
and shims in an image, so one listing any of them is reims-util's, older,
and a start now makes it again with this reims-ctl's set, as it does an
image holding other builds, telling what it lacked. An image listing none
(Lilu is not reims-vgpu's) stays as it was and is warned of, as before,
naming update-opencore and U.

A renewal is now refused while another VM runs on the same image, as well
as while the VM itself runs. It writes and then renames: reims-util writes
the new image through a file it syncs and renames, and reims-ctl reads it
back and renames it over the old one, so a renewal stopped at any point
leaves the old image or the whole new one at the VM's path.

update-opencore's help and the interface's help for U say which images a
start makes again. The previous commit's tests pass here, and the image
classification's own test now holds the older-set and lacking cases.
2026-12-02 08:35:32 -08:00
Anees Iqbal 0f4522d88b ✅ Expect a start to renew an image of an older kext set
An image an older reims-util made for reims-vgpu before Graft (11-08) lists
ReimsGraphicsLoader, its two shims, ReimsGraphics and RgfxGate, and no Graft.
A start of its VM only warns of it today, as of an image of the user's own,
though only reims-util ever put those kexts in an image.

These tests hold what the next commit makes of it: a start renews an image
that lacks some of the set but lists others of reims-vgpu's own kexts, of this
set or of the one before Graft, and warns of nothing; an image that lists none
of them, as one of the user's own may, stays as it was and is warned of, with
update-opencore named; a renewal whose reims-util is killed part way leaves the
old image and the settings as they were, and the next start renews; and a
renewal waits while another VM runs on the same image. They fail on the tree
before it where it differs.
2026-12-02 08:35:32 -08:00
Anees Iqbal e8f8e88c60 📝 Say which destroys the release runs
The header and docs/api.md section 4 said rvg_graphics_device_release
calls back never. Section 5 and the tables' own rules say otherwise:
the release closes the window, which runs the window table's destroy on
the calling thread unless a window callback is running then, and the
handle lets go of the device table before the device, so a table with
no functions, or one whose last closure the release drops, has its
destroy run inside the call. The release's row, the "Calling back"
list and the header now say so. The row also says that the release of
the process's last device waits at most 5 s for its threads, as the
"Waiting" list and the header already said. Nothing changes for the
host or the guest. The header is cbindgen's output of the new doc.
2026-12-02 08:05:31 -08:00
Anees Iqbal 365580a019 🐛 Name ring 0's threads in RAISE_THREADS as the device names them
RAISE_THREADS, the threads the header names for the device's raise,
still held "graphics-context-", "graphics-presents" and "graphics-block-",
the names ring 0's lanes had before their threads became
reims-vgpu.graphics-ring0-<i> (reims_vgpu_graphics' lanes::thread_name).
foreign_committer read a ring 0 thread as one the raise is not named for,
so a submission handler run inside its commit handed its CB_SCHEDULED or
CB_SUBMITTED to the queue's service thread instead of posting it there.
The header allows either, and rt runs no handler inside a commit, so
nothing changes on rt: only the testkit's platform, which runs them inside
a commit, now posts those records on ring 0's thread.

The test raises on the presents' lane and holds the thread's name to
RAISE_THREADS.
2026-12-02 08:01:05 -08:00
Anees Iqbal afd1ae46a5 📝 Name the release pace's and shared events' threads for raise
Two more threads the library raises on were missing from
raise_interrupt's threads. The releases' pace thread
(reims-vgpu.graphics-release-pace) carries out a BLOCK_RELEASE as its
turn comes, and answers it there where nothing is left to copy, so its
COMPLETE is posted and raised there. The shared events' thread
(reims-vgpu.graphics-shared-events) tries again the EVENT_SIGNALLED to
another holder whose ring had no room for it, through the ring's
try_post, which raises. As with the take workers and the UI thread, the
code has always raised there and QEMU's raise is safe on any thread, so
the header and docs/api.md section 5 name them. The header is cbindgen's
output of the new doc.
2026-12-02 08:01:05 -08:00
棠渚听潮 0427583422 🐛 Commit each unattached surface cache writeback before acquiring the next command buffer 2026-12-02 23:58:44 +08:00
Anees Iqbal 76ebbc0d72 🎨 Allow the release-order test's own thread to spawn
the_release_closes_the_pool_before_its_windows starts a thread of its own to
let the host's pool_add return 200 ms into the release, and clippy's
disallowed_methods refused std::thread::spawn there on every target (lint
jobs m3-max-78673 and m3-max-78674). The test keeps its thread, with the
allow and its reason, as the crate's other test-owned threads do.
2026-12-02 07:50:14 -08:00
Anees Iqbal f57814d61f 📝 Name the take workers and the UI thread among raise's threads
raise_interrupt's threads left out three the library raises on. The take
workers of the guest's Shared pool and of its Private blocks
(reims-vgpu.graphics-pool-take and reims-vgpu.graphics-private-take)
post the POOL_BLOCK and PRIVATE_BLOCK answers they give. The windows' UI
thread (on macOS the process's main thread, on Linux and Windows
reims-vgpu.ui) posts the POINTER_OVER, POINTER_MOTION and SCROLL it tells
the guest. The code has always raised there, and QEMU's raise is safe on
any thread. Handing those posts to the control thread instead would add
a wake on the pointer's input. The header and docs/api.md section 5 now
name them. The header is cbindgen's output of the new doc.
2026-12-02 07:43:01 -08:00
Anees Iqbal 8ec0f38716 📝 Name doorbell_write among the calls raise_interrupt runs in
raise_interrupt's threads named the host's own inside
rvg_graphics_device_mmio_write_taking alone, while
rvg_graphics_device_doorbell_write says it calls raise_interrupt as that
write does, and docs/api.md section 5 names both. The header now names
both, there and in the lock the raise must not wait for. The header is
cbindgen's output of the new doc.
2026-12-02 07:43:01 -08:00
Anees Iqbal 25eca59cf7 🐛 Raise for no answer inside the host's read of a display
The host's read of a display holds the presented surface's block while
its draw reads it, and let go of that hold on the host's thread once the
draw had finished. Where the hold was the block's last, the block's
release was answered there: its COMPLETE was posted, and raise_interrupt
called, inside rvg_graphics_device_read_display, which the header says
calls nothing back and which raise_interrupt's threads leave out. A
window's draw that lets go of a hold in a refused frame, and the device's
release, answered the same way on the window's drawing thread and on the
releasing thread.

An answer given in those places is now handed to the control thread,
which posts it and raises the control vector, as it does for one that
finds the ring full. What changes for the host: raise_interrupt is no
longer called inside a read of a display or the release, nor on a
window's drawing thread. For the guest, the answer comes from the control
thread a moment later, with the same contents.

The test holds a read's draw on the GPU while the guest presents the
scanout and releases the surface's block, then checks that the release's
answer raises off the reading thread.
2026-12-02 07:43:01 -08:00
Anees Iqbal 75b42c7900 📝 Say the release closes the pool at its start, and waits
The header said pool_remove is not called once rvg_graphics_device_release
has begun. The release now closes the pool at its start, and a call the
pool's thread began before that may still be running, which the release
waits for: pool_add and pool_remove say so, and so do the release's own
doc and docs/api.md's sections 4 and 5. The header is cbindgen's output
of the new docs.
2026-12-02 07:43:01 -08:00
Anees Iqbal af690afff2 🐛 Close the pool at the release's start, before the windows
The header says the host's pool_remove is not called once
rvg_graphics_device_release has begun, but the release closed the
windows before it closed the pool, and until then the pool's thread went
on placing and removing pieces: a pool_add or pool_remove could begin
after the release had begun.

The release now closes the pool first. What changes for the host: the
pool's callbacks stop at the release's start instead of after its
windows closed. A pool_add or pool_remove the pool's thread began before
that may still be running, and the release waits for it, as it did.
QEMU's side needs no change: its teardown closes its side of the pool
before it calls the release, and its callbacks drop any ask made after.

The test holds the pool's thread inside the host's pool_add as the
release begins, and checks that the add ends before the window closes.
2026-12-02 07:43:01 -08:00
Anees Iqbal fc5b3cfd07 📝 State the 0 Hz rule without where it was read [ci skip]
The rule for a mode's rate in an x86-64 guest stands on the boots it names
(m3-max-78416, m3-max-78544). Its two notes on where the rule was read are
dropped, so the docs describe the rule and its measurements only.
2026-12-02 07:41:30 -08:00
Anees Iqbal d26cf49d22 📝 Say why x86-64 guests list their modes at 0 Hz [ci skip]
An x86-64 26.7.2 guest lists every mode at 0 Hz (CGDisplayModeGetRefreshRate,
System Information) though the framebuffer answers the device's rate in each
mode's information and detailed timing. The 0 is x86-64 macOS's own:
CoreDisplay's mode building gives every mode the rate 0, and records IOFB0Hz
in the framebuffer's IOFBConfig, where all the display's valid modes are
progressive and between 57.5 and 62.5 Hz, as for an Intel Mac's 60 Hz-only
panel. A scratch framebuffer giving every mode 120 Hz listed all seven at
120 Hz with no IOFB0Hz; dropping the Apple timing ID changed nothing.

The framebuffer lists no mode at a rate the host screen does not run, so a
guest on a 60 Hz screen keeps reading 0 Hz, and one on a screen of another
rate reads it. Nothing changes for the guest; design.md says what the rule
is and lessons.md how to tell it from a wrong answer of ours.
2026-12-02 07:41:21 -08:00
Anees Iqbal 06b0ed4e46 📦 Rebuild the ROM and both guest sets for wire version 3
The option ROM, the x86-64 kexts and the arm64e kexts are built from the
wire header, which now reads RGFX_VERSION 3, so each is rebuilt from this
tree: the ROM and its record, and both sets with their records, which now
name the size table among their sources. The kexts accept a device of
version 3 only, and RgfxGate carries a bundle marked wire-version-3, which
it installs over any other at the next boot.

Built by make -C firmware prebuilt, make -C guest prebuilt and make -C guest
prebuilt-arm64e on the Mac (job m3-max-78554), whose guest tests passed.
2026-12-02 07:29:40 -08:00
Anees Iqbal aa9cf71a7f 📝 Record the wire record that grew without the version [ci skip]
A guest of a wire version reads and lays out each record at its own size, so a
record that grows at the same version is misread rather than refused, as the
11-28 report's old bundle was. The lesson says why only a version the kext reads
before it registers its accelerator ends in a picture, and how to spot the next
one in a host's log.
2026-12-02 07:29:40 -08:00
Anees Iqbal 1b8cf2f69e 🐛 Move the reims-graphics wire to version 3
A guest bundle built before 11-18 sends RgfxRenderPipelineCreate at 464
bytes with its private state after it. A host since then reads the record
at 496 bytes, so it took that state's sample mask, UINT64_MAX, as the
pipeline's tessellation partition mode and refused WindowServer's
pipelines: after an update whose guest still ran the old bundle,
WindowServer restarted at every boot. The wire stayed at version 2 through
that change, so the kext let the old bundle in.

Three records changed size at version 2, which the size table from the last
commit names: RgfxVideoCaps (776 to 1552 bytes), RgfxRenderPipelineCreate
(464 to 496) and RgfxPoolBlock (40 to 48). No register, region offset or
message number moved after 11-05, the day version 2 began, and every other
change since then was a feature the guest takes, a tail after a record, or a
reserved field put to use. The wire is now version 3, and the table pins
every record's size there.

What the guest sees: VERSION reads 3. Kexts and option ROMs built before
this commit leave the device, and name both versions: macOS then drives the
display through the firmware's framebuffer and WindowServer composites in
software, so an old guest comes up with a desktop instead of looping. Kexts
of version 3 register no accelerator for a bundle of version 2 on disk, and
RgfxGate replaces it on the same boot before they register. reims-ctl's
start already makes a VM's OpenCore image again with its own kexts where
the image holds other builds. The peer traces read VERSION 3, and
design.md lists the versions and the size rule. The option ROM and both
kext sets are rebuilt in the next commit.
2026-12-02 07:29:40 -08:00
Anees Iqbal 14ef691cd7 ✅ Pin each wire record's size to the wire's version
A guest of a wire version lays out each record it sends, and reads each one
the host sends, at the size it was built with. Nothing held a record's size
to the version: on 11-18 RgfxRenderPipelineCreate grew from 464 to 496 bytes
at version 2, so a guest bundle built before then still matched a newer
host's version, and the host read the private state the old bundle put at
byte 464 as the pipeline's tessellation partition mode. WindowServer's
pipelines were refused and it restarted at every boot.

include/reims_graphics_wire_sizes.h now pins every record of the header to
its size at RGFX_WIRE_SIZES_VERSION, one RGFX_WIRE_SIZE row a record. Both
sides check it: the wire crate's tests compile the header against it in C11
and C++17 and hold the table to RGFX_VERSION and to the header's records,
and the guest's kext tests compile it for x86-64, arm64e and the Mac.

The table holds version 2 as its guests were built, each record at its size
when it first appeared at that version, so the tests fail: three records
changed size at version 2 without the version moving, RgfxVideoCaps (776 to
1552 bytes, 11-05 to 11-08), RgfxRenderPipelineCreate (464 to 496, 11-18)
and RgfxPoolBlock (40 to 48, 11-19). The next commit moves the version.
2026-12-02 07:29:40 -08:00
Anees Iqbal 78bdc71d66 📝 Name the other host's plane function without a doc link
texture.rs's docs of surface_plane (Windows only) and exported_plane (Unix
only) linked each other, and each link is unresolved on the other host's
target: rustdoc -D warnings failed for Linux, Windows and the Mac in the video
branch's merge lint (m3-max-78581 at 2221d7004d). Each now names the other in
code text and says which hosts have it. Docs only.
2026-12-02 07:20:39 -08:00
Anees Iqbal 2221d7004d 📝 Fill the UHD 630's cells and record the restore's wait on the Iris [ci skip]
vainfo -a on the UHD 630 (m3-max-78560) lists vaon12's decoders: H.264, HEVC
Main and Main 10, and VP9 profile 0 and profile 2 at 10 bits, 4:2:0 up to
8192x4352, and no encoder, AV1 or range extensions. The Windows column's
open cells (Q3) now say that, and Q3 is gone.

The planner kept the restore of H1: the decode's wait VA-API asks for before
a read stays. Its remainder on the Iris Xe against issuing the runs with no
wait, 0.2 to 0.7 ms a decode with the guest's numbers equal (m3-max-78524), is
recorded in B95 as its cost.
2026-12-02 07:18:17 -08:00
Anees Iqbal 9bdd4c633b 📝 Name the x86-64 guest's -19092 as its own synchronous wait [ci skip]
With the paravirtual service published, x86-64 macOS 26.7.2's framework
returns at once from a reply wait whose timeout is above 2.147 s, and a
synchronous decode's waits are 10 s: each synchronous frame fails -19092 as it
is sent. The same decode with asynchronous decompression handed 60 of 60 AV1
and 60 of 60 VP9 pictures on the 780M (m3-max-78509). The docs said what fails
was not known; F3 and F4 now say what the service, which x86-64 guests stay
off, decodes. devices.md also said the host answers dfin kVTUnimplementedErr,
which it no longer does.
2026-12-02 07:18:17 -08:00
Anees Iqbal 2377728268 ✅ Expect Metal's refusal of a compute encoder's execution
indirect_command_buffers_on_vulkan executes an indirect command buffer of
draws in a compute encoder, which the encoder refuses at Metal's refusal and
counts. Its answer is REFUSED, as for every command the encoder stops at; the
test, changed when the encoder began to answer, expected RECORDED.
2026-12-02 07:18:17 -08:00
Anees Iqbal d8ba75224f 🎨 Order the Vulkan crate's re-exports of the pages' hold as rustfmt does
rustfmt sorts the crate-internal re-export of the tests' page helpers above
the dma-buf ones once the hold's names left that list (1eb4e7df78); the
merge's format check would refuse the old order.
2026-12-02 07:18:17 -08:00
Anees Iqbal 33dd5b7b27 🐛 Hold a CUDA-registered view's pages as mapped while it is registered
A view's host view, which NVIDIA's arm registers with CUDA (cuMemHostRegister
pins a pointer's pages), mapped the view's pages from their files first
(map_for_pointer) but held them so for no time at all. A fold of the views
could then map them through a dma-buf again: between that mapping and the
registration, which fails on a VM_PFNMAP mapping and leaves the buffer
without zero copy, or under a live registration, whose undoing by its
pointer had never met such a mapping. What CUDA reads was not at stake: it
pinned the pages it found, and a fold maps the same guest pages back.

The host view now holds the pages as mapped (hold_mappings, the rt
platform's hold for its own imports by pointer, made public with
mappings_held, which tells whether a hold covers a range), from before they
are mapped from their files until the registration lets go of the view.
Its test, a_view_s_host_view_holds_its_pages_as_mapped_while_it_lives,
fails with the hold taken out.
2026-12-02 07:18:17 -08:00
Anees Iqbal 4b019b5bfd 🐎 Issue a VA-API frame's processing runs right behind its decode
bbe52c1aae made the zero-copy write wait for the frame's decode before it
issued the video-processing runs that read it, because nothing in va.h or
va_vpp.h promises that a driver orders a run on another context after a
pending decode of its input. That text is silent; it asks for one wait
only, before the planes are read (vaExportSurfaceHandle), which the runs'
own wait is. The drivers do order it: radeonsi's winsys schedules each
submission after earlier flushed ones on other rings that use one of its
buffers (RADEON_USAGE_SYNCHRONIZED, read from Mesa's code), and the
hardware test of the old order passed on the Iris Xe (iHD) and the Radeon
780M. The wait cost about 1.9 ms a landing on the Iris (B 6.68/6.27 ms
against A 4.01/4.03 in m3-max-78259; a decode sync of 608 us mean, issue
225 us, runs 1812 us in m3-max-78313).

The runs now go right behind the decode again, the decode is waited for
between their issue and their wait (runs_behind_the_decode), for its error
and its word that it is done, and the runs are waited for once. The
call-order test now holds that order, and the hardware test is again
runs_issued_right_behind_a_decode_write_what_it_decoded.

For the guest: a reference picture's landing starts its copy as the GPU
finishes the decode instead of a CPU round trip after it; what lands is
unchanged, and a failed decode's error is still the frame's.
2026-12-02 07:18:17 -08:00
Anees Iqbal 98c2a68362 ✅ Find the shown row's frame draw as its sampling pass
The test of the shown frame's middle row found the frame's draw as a copy of
the surface into the drawable. Since the display samples a frame of another
size than its place over it (fb3108a832), its 64x32 surface drawn into a
16x20 region is a pass, the first of the draw, so the test found no copy and
failed. It now takes the first pass as the frame's draw and checks the row's
copy comes after it and before the cursor's pass. The row's copy, its
origin and the line it logs are unchanged.
2026-12-02 07:18:17 -08:00
Anees Iqbal 0292d40635 🎨 Class a zeros picture's flat green as green in the shown row
The shown row called a pixel green only at G >= 96 and 64 over R and B. A
picture of zeros (Y=0, Cb=Cr=0) shows about (0, 77, 0) under BT.709 and the
user's report measured (0, 87, 0), so the self-checking stream's known-bad twin
(job m3-max-78307) had its flat-zeros frames described as 98% other. Green is
now G >= 64 and 48 over R and over B, tested after black and white.

This changes the debug description alone: a harness's verdict reads the bars,
and a present with none is bad whatever its class, so no verdict changes.
a_row_s_pixels_are_two_bits_each_by_their_class takes the new edges and the
zeros colours of BT.709, the report and BT.601.
2026-12-02 07:18:17 -08:00
Anees Iqbal 70d02fed49 📝 Name each video format's proof run, and close JPEG and ProRes [ci skip]
Part 4's table now says how each offered cell was shown: the job of a run in
which a guest decoded or encoded the format on that card, a card test, the
driver's listing alone, or no run on file. The x86-64 rows take today's walks
(H.264 and HEVC Main playback, and the HEVC and H.264 encode rows of
319f54dabb); the arm64 rows take the runs devices.md already names.

VP9 profile 2 at 12 bits on the RTX 3090 is offered on its card test (job
m3-max-78301: every frame libvpx's), not yet a guest run, and known-issues says
which formats each GPU decodes. JPEG on Intel Mac guests is the guest's own,
as a real Intel Mac's is. ProRes has no route: no lab card's driver lists it.
The x86-64 encoders' AppleGVA paths are named under the table.
2026-12-02 07:18:17 -08:00
Anees Iqbal a774a7fcf2 📝 Settle the JPEG and HEVC range extensions encode cells [ci skip]
Part 4's Q1 and Q2, answered by a read of an Intel Mac's video plug-ins,
registry and shared cache (potluck job m3-max-78260) and of the arm64 HEVC
encoder's Info.plist as macOS 27.0.1 ships it.

JPEG is the guest's own on both arches. VideoToolbox's JPEG plug-ins load only
where Apple's JPEG engine's key is in the registry, and AppleGVA has no JPEG
path an app uses. No GUI or VT route ever asks a GPU.

HEVC 4:4:4, 12-bit and SCC encode are the guest's own as well: VideoToolbox
names no profile for them. On x86-64 no encoder takes 4:2:2 either. On arm64
the paravirtual encoder lists the range extensions profile, so Main 4:2:2 10
on the Iris Xe becomes N4, sized and waiting for the planner.
2026-12-02 07:18:17 -08:00
Anees Iqbal 221d6933e6 🆕 Decode VP9 profile 2 at 12 bits on NVDEC where its caps list it
The owner's order is to offer what the host lists. An RTX 3090's NVDEC
lists VP9 at 12 bits, 4:2:0 (m3-max-77186), but the NVDEC arm declined
every 12-bit profile 2 stream at its paravirtual session's start, so an
arm64 guest decoded none on an NVIDIA host, while iHD's already land in
`tv20`.

What changes for the guest: on an NVIDIA host, an arm64 guest's
paravirtual VP9 session of profile 2 at 12 bits, 4:2:0, is now taken
where NVDEC's caps of VP9 at 12 bits, asked at the session's start as
HEVC's range extensions are, list it at the stream's size. Its frames
decode into P016 (the samples at the top of their words) and land in
`tv20` as HEVC's 12-bit 4:2:0 pictures do. Elsewhere the session is
refused at its start as before, its reason named.

vp9_s_caps_are_nvdec_s_answers_and_decline_what_they_lack held the old
answer (12 bits declined) and now holds the new one: taken where the
caps list it; declined where they do not, write no P016, or lack the
size. It fails with the 12-bit branch cut off (m3-max-78250, msi). The
new ignored NVIDIA-host test a_12_bit_profile_2_stream_decodes_to_libvpx_frames
checks the codec module's 12-bit libvpx stream against vpxdec's MD5s, to
run on an RTX 3090. docs/video/formats.md's cell reads "listed, not run"
until it does.
2026-12-02 07:18:17 -08:00
Anees Iqbal 78b3bc8ac6 📝 Table every video format by guest and host route [ci skip]
Part 4 asks for one table of what the lab's cards decode and encode
against what the device gives each guest: for each format, guest route
and host arm, offered, a finding with its evidence, or not built with its
reason. docs/video/formats.md is that table, from the drivers' lists of
2026-11-27 (m3-max-77185 to 77188) and the arms' caps code.

It shows one format the code could offer and does not (G1: VP9 profile 2
at 12 bits on NVDEC, which the RTX 3090 lists), and three cells no lane
has studied (JPEG on x86-64 guests; HEVC range extensions and SCC encode;
the UHD 630's formats past H.264 and HEVC Main 10).
2026-12-02 07:18:17 -08:00
Anees Iqbal 4580ac311d 🆕 Log the shown frame's middle row where its target is named
A harness that judges what a guest's video looked like needs the frame
each present showed as the user saw it: the guest's composited frame
after the display's colour, not the decoder's surface. A frame the
guest's compositor failed to draw shows only there, and no such read was
left in the library.

Where the filter names reims_vgpu::graphics::shown_pixels at debug, the
window's draw of a presented surface now copies the middle row it drew,
inside the image's region and before the cursor's and the overlay's
passes, into a buffer of its own, and logs it once the draw has finished:
two bits a pixel (black, white, green, other), with the latest present's
number, how many presents the draw took, and the IOSurface ID shown. A
drawable that is not BGRA8, a refused buffer, encoder or copy, or a draw
that did not complete gives a line that the row was not read.

Off means nothing: whether the filter names the target is decided at
the first draw, and where it does not, a draw reads one flag and makes
and encodes nothing of the row. The test
with_the_shown_frame_s_row_off_a_draw_copies_and_makes_nothing_of_it
holds that: no copy, no buffer and no handler of the row's.
a_draw_of_a_presented_surface_logs_the_middle_row_it_drew_once_it_has_finished
fails with the read cut off at its call (m3-max-78230, msi).

Diagnostics only: nothing the guest or the host observes changes.
2026-12-02 07:18:17 -08:00
Anees Iqbal edeed54e7a 🎨 Hand the zero-copy run its issue as it is
Clippy's redundant_closure flags the closure around `issued` in the
VA-API zero-copy run that 66d6c19abb added: passing the issue straight to
the import's run is the same call, and the merge's clippy (warnings
denied) would refuse the closure.

Checked with clippy on reims-vgpu and reims-vgpu-video, warnings denied,
in m3-max-78230 on msi.
2026-12-02 07:18:17 -08:00
Anees Iqbal d8fa6b3104 🆕 Count a paravirtual decoder session's frames by what they handed
A VideoToolbox decoder session on the paravirtual route said nothing of its
frames as it ended, so a log could not tell a session whose frames all landed
from one whose frames all failed or were dropped.

A session now counts each frame it emits: emitted with the buffer its picture
landed in, dropped with no picture decoded, or failed with a status. It logs
the counts at info as it ends. On this route only the first class hands the
guest a buffer, so no reader is handed a buffer that no picture landed in, and
the line says so.

Nothing changes for the guest.
a_sessions_frames_are_counted_by_what_they_handed_the_guest holds the classes
and the line.
2026-12-02 07:18:17 -08:00
Anees Iqbal 313d049cdd 🆕 Count each decoded picture handed the guest by its class
A report at the default level could not say what the guest's readers were
handed. The session's end line, which counts its pictures, is at info, and
with logs off the library writes warn alone. Only a session's first picture
that did not decode was said at warn.

Each picture a decode hands the guest is now counted in one of three classes,
from the session's own state, with no pixel read and nothing added to a
picture's path:
- video-pictures-handed-landed: it landed in its output;
- video-pictures-handed-failed: it failed to land, or its decode was refused
  at its take (its command buffer faulted);
- video-pictures-handed-undecoded: no decode ran for it, as a decode answered
  no picture (a stream entered at a P picture among them).
The counts are per process, in the degradation counts that reims-ctl report
asks for at any level. They are also per session, on the session's end line,
which now says how many decodes were refused at their take.

Nothing changes for the guest.
each_picture_handed_the_guest_is_counted_in_its_class holds the classes, and
docs/conventions.md lists the codes.
2026-12-02 07:18:17 -08:00
Anees Iqbal c5e35afb0e 🐛 Decline a gathered picture whose pass or zeros the platform refuses
The 4:4:4 gatherer and the scratches' zero fills took only a raise from their
commands. A refusal of anything else recorded nothing, yet the command buffer
was committed and waited for:
- a refused pipeline state, dispatch or end of the gather's pass left the
  guest's surface unwritten, and the picture counted as gathered;
- a refused fill or end of a new scratch's zeros left the scratch unzeroed,
  and the driver's first write into it could then come before the platform's
  own fill of a new buffer's zeros.

The gather now fails a refused command of its pass with why, its command
buffer never committed, and the picture goes the CPU's way, as with the
gather's other refusals; the next picture's pass is tried again. One zero
fill, gather::zero_fill, now serves the gatherer and the VA-API copier's
scratch. A refused fill or end commits nothing and answers Unzeroed::Refused.
Each scratch maker (the VA-API copier's, the XYUV gatherer's and NVDEC's
4:4:4 route) then keeps no scratch and declines that picture alone, and the
next picture's ask makes and fills one again. A raise or a failed fill still
ends the route for the session, as before.

For the guest: a 4:4:4 picture, or a picture copied into a device cache,
whose pass or scratch the platform refuses is copied by the CPU, not left
unwritten or written from an unzeroed scratch. The two fake tests
a_command_of_the_pass_the_platform_refuses_gathers_nothing and
a_zero_fill_the_platform_refuses_answers_refused_and_commits_nothing hold it.
2026-12-02 07:18:17 -08:00
Anees Iqbal 927f2c41ec 🆕 Record an exported surface as the replay format's surface records
A recording held an exported surface's planes as two textures of the device's
own (newTextureWithDescriptor: of a descriptor marked outside the guest's
indices), and nothing of the surface itself: not its make, its exports or the
pictures the host's video landed in it. A player could not make the surface,
hand it to a stand-in for the other API, or replay its hand-overs, and the
planes read as never written.

The rt platform now records metal2vulkan's exported-surface family (its replay
format's "Surfaces and the guest's RAM", as of metal2vulkan abf7b8f873):
- m2v.newExportedSurface on the device, with the handle, the multiples and the
  planes, its result the surface;
- m2v.surfacePlane on the surface for each plane's texture;
- m2v.exportSurface at each export;
- m2v.surfaceWritesDone at each picture landed, with no bytes, as the stream
  holds none of the picture's;
- the surface's release, as its memory's last reference goes.
A surface over Direct3D 11 textures keeps the old form. The recorder's FIXES
list names the change (exported-surfaces), and docs/api.md lists the records.

Nothing changes for a process that does not record. Replaying the records needs
metal2vulkan's player at abf7b8f873 or later, which the pin does not hold yet.
on_vulkan_rt_an_exported_surface_is_recorded_as_the_replay_format_s checks
the records and their order on the GPU. The test that held the old form,
on_vulkan_an_rt_surface_s_planes_are_named_where_they_are_used, now checks
each plane's m2v.surfacePlane on the surface the make named.
2026-12-02 07:18:17 -08:00
Anees Iqbal 0fbd0ed004 🐛 Decline a VA-API fill whose pass the platform refuses
The fill took only a raise from its pass's commands. Any other refusal of a
pipeline state, a plane's dispatch or the pass's end (on rt,
metal2vulkan-runtime's refusal, counted under its kind) recorded nothing, yet
the command buffer was committed and waited for. The encoder then coded an
input the pass never wrote, holding an earlier frame's bytes or none. The
fill's blit end folded its refusal in the same way.

Now a refused command declines the frame. Its command buffer is never
committed, and the frame is uploaded by the CPU, said once a session, as with
the fill's other refusals before submission. The next frame's fill tries
again. A decode's GPU copy into its caches, which shares the pass
(encode_planes), declines its picture in the same way, and the CPU's copy
writes it.

For the guest: a frame whose fill the platform refuses is coded from the
guest's own bytes, not from an input nobody wrote.
2026-12-02 07:18:17 -08:00
Anees Iqbal b90ad2e8d7 🆕 Answer whether the compute encoder recorded each command
The compute encoder answered nothing for a command the platform refused
without dying. metal2vulkan-runtime counts such a refusal (rt-refused-<kind>,
rt-unbuilt-<piece>, Metal's own) and goes on, and the command buffer still
completes. So the host's own work that dispatched through the encoder could not
tell a refused dispatch from a recorded one: VA-API's fill committed a pass
that wrote nothing and handed the encoder its input as written.

ComputeEncoder::encode now answers Encoded, the blit encoder's must-use
answer. The rt platform answers refused where it stopped the command, and the
fake where its script answers nil. compute_encoders_on_vulkan checks that rt
refuses exactly the commands it counts, and
a_compute_command_the_script_answers_nil_is_refused checks the fake. The rt
and decoder tests that run the host's kernels assert that their commands were
recorded.

Every caller takes the answer with go_on(), so nothing changes for the guest
or the host. The guest's own dispatches, the decoder's argument, escape and
cost passes, and the gathers go on past a refused command as before, counted
where it stopped. VA-API's fill uses the answer in the next commit.
2026-12-02 07:18:17 -08:00
Anees Iqbal 265f8bc27f 🐛 Fail an NVENC frame whose copy into its input the platform refuses
What the host and guest observe changes. The NVENC fill copies each frame
from its source's planes into the input NVENC reads with a blit, and took
each copy's answer as `if let Err(..)`, dropping Ok(Encoded::REFUSED): a
copy metal2vulkan-runtime refused recorded nothing, the command buffer was
committed and waited for, the frame counted as copied, and NVENC encoded an
input nobody wrote for it (a new input's zeros, green; else the last
frame's bytes).

Now the copy is copy_frame, which takes each command's Encoded: a refused
copy or end answers Copied::Refused, its command buffer is not committed, so
nothing is submitted and NVENC is handed nothing. The frame fails, an encode
error to the guest; the session's first such refusal is said at WARN, and
its end line counts the frames that failed this way. The session's next
frames are copied as before, as nothing of the refused one is in flight.

This is the (c)2 class for the encode side: a command the host makes for
itself, refused, and its result used as if done. It is not what turned the
screen recordings on the RTX 3090 green: those copies were recorded (the run
counted no blit refusal); the refused command there was the guest's own
render pass.

Red first: a_copy_the_platform_refuses_writes_no_frame_and_submits_nothing
fails with the refusal folded as before and passes with the fix (job
m3-max-78068, with the nvidia and video_host fake tests, 51, passing).
2026-12-02 07:18:17 -08:00
Anees Iqbal 71c6412cd8 🐛 Answer a paravirtual decoder's FinishDelayedFrames with noErr
The host answered the guest's dfin, VideoToolbox's FinishDelayedFrames,
with kVTUnimplementedErr (-12782), so a guest that waits for its delayed
frames heard that the wait failed. Nothing is delayed at that point: the
session reads its messages in order, and each dfrm emits its frame, or its
failure, before the next message is read, so every frame sent before a dfin
is out when it is answered. dfin now answers noErr; dsav still answers
kVTUnimplementedErr.

For the guest, a FinishDelayedFrames (VTDecompressionSessionFinishDelayedFrames,
and the wait of a synchronous decode or WaitForAsynchronousFrames where
VideoToolbox asks the decoder) now succeeds where it failed -12782.

a_finish_is_answered_once_every_frame_before_it_is_out sends a dfin while a
frame waits for its buffer, and checks that the frame's Demt, its surface's
release and its dfrm reply come before the dfin's noErr. It and the changed
an_invalidated_decoder_answers_frames_with_no_decoder fail on the old answer
and pass on the new one (job m3-max-78022).
2026-12-02 07:18:16 -08:00
Anees Iqbal 584d57e6c4 🐛 Issue a VA-API frame's processing runs once its decode is done
A frame written by video processing had its runs issued right behind its
decode, before the decode was waited for, resting on the driver to order a
run on another context after a pending decode of the surface it reads.
Nothing in va.h or va_vpp.h promises that, and va.h's own example of a
surface handed on waits for the decode first. The write now waits for the
decode, then issues the runs and waits for them, as runs_after_the_decode
orders it.

Its fake call-order test, a_frames_runs_are_issued_once_its_decode_is_done,
fails on the old order and passes on the new one (job m3-max-77975). The
hardware test that held the old order, now
a_write_asked_as_its_decode_is_issued_writes_what_it_decoded, checks that a
write asked while its decode runs still writes what it decoded.

For the guest, a reference picture's landing starts its copy one CPU round
trip after its decode ends instead of as the GPU finishes it; what lands is
unchanged. A failed decode is still copied, and its error is the frame's.
2026-12-02 07:18:16 -08:00
Anees Iqbal 19bdf32b38 🆕 Log each hardware decode's time from its take to its signal
A host video session's end line now says how long its decodes took, on
average and at most, from the session's take of each to the signal of its
value, which the command buffer waiting for the picture waits for. It
covers the decode, any wait for the session's earlier pictures and the
landing, so a change to how a picture lands (the VA-API arm's processing
runs among them) can be costed per picture from one playback's log. It is a
diagnostic: nothing the guest or the host's API sees changes.
2026-12-02 07:18:16 -08:00
Anees Iqbal 3221bd66ad 🐛 Hold a decode until its output's earlier users on its queue end
A video session's decode writes its output off the device's queues as the host
walks the decode's command buffer, so the queue's order of its buffers' GPU work
did not hold it: a buffer of the decode's own queue that read the output,
committed before the decode and not yet finished, read the next picture or a mix
of the two (the video lane's hand-over table, row 15, and its harness's first
seed). The host waited on the CPU only for the other queues' buffers the
guest's order named.

Now each committed command buffer that used a device cache and held no video op
leaves a mark in the cache: for its queue, the value its queue's end event
reaches as it ends, and its value again where it may write the cache. Before a
decode writes a cache, it waits on the CPU for every queue's mark, its own
queue's among them; an encode, which only reads its source, waits for the
writers' marks alone. The queues' end events are shared events now, so the CPU
can read and wait on them (a recording names newSharedEvent where it named
newEvent for them).

The record is bounded at one mark a queue a cache: a queue's later buffer
replaces its mark, as the queue's end event reaches the later value only after
the earlier, and marks reached go at the queue's next mark, at each wait, and
for a queue gone at the sweep of its end event. A device recovery clears them.
A test fills one queue past that bound with three reads and shows the decode
waiting through the first two reads' ends for the third's.

Counted on the caches' summary line: the waits that found an end not reached,
the longest, and the other queues' uses found in flight then. Tests: the seed's
red test, a decode waiting for another queue's read it does not name, the bound,
and an encode held by a writer of its source and not by a reader.

What the guest sees: a decoded picture is no longer written under its own
queue's earlier reads of it. The residual, an output in the pages and no device
cache, which keeps no marks, is in docs/known-issues.md. Whether this fixes the
green frames the guest's screen recording was reported to make is not known: no
red recording has turned clean with it.
2026-12-02 07:18:16 -08:00
Anees Iqbal bf62772b7a ✅ Show a decode not waiting for a read on its own queue
A video decode's session writes its output off the queue, as the host walks
the decode's command buffer, so the queue's order of its buffers' GPU work
does not hold the write behind an earlier buffer of the same queue that reads
the output and has not finished. Nothing waits for that buffer today: the
surface order's CPU wait names only other queues' buffers. The test commits a
read of a landed picture on queue 1, then the next decode into the same output
on queue 1, and fails while the session is handed the decode before the read
has finished. The fix follows in its own commit.
2026-12-02 07:18:16 -08:00
Anees Iqbal 1d848303c1 📝 Describe guest page imports as the code does them [ci skip]
docs/qemu.md's Linux mapping section, design.md's view room note and the
cold-device test's doc still named the deleted platform's probes and gate
(ONE_DMA_BUF, ONE_DMA_BUF_VIEWS, probe_fold, the import gate and HostRam).
They now say what the code does: rt answers each import at the call, its
first refusal of a view's dma-buf maps views from their files from then on
(views_need_files), NVIDIA's driver is refused on its 0x11 types and ANV by
rt's first-type rule at d8735b75f0, RADV takes the dma-buf, and an import
past the headroom or refused both ways is made over a copy. budget.rs and
vm.rs's unfold named the same deleted gate where the import is now copied.
2026-12-02 07:08:39 -08:00
Anees Iqbal 668638875a ✅ Give the PATH advice test's script to bash on its input
the_installers_path_advice_names_the_directory_it_installed_into ran the
installer's check_note through `bash -c` with the script as one argument. On
Windows that argument goes through the command line's quoting, and MSYS2's bash
read the quotes in the installer's text back otherwise: batch b1203's Windows
leg failed it with "check_note: -c: line 34: unexpected EOF while looking for
matching `''" (winleg b1203-win, m3-max-78510). The script now goes to bash -s on
standard input, which no quoting touches. The installer itself is unchanged:
ctlwin's install.ps1 run printed the right advice. Test only.
2026-12-02 07:03:11 -08:00
Anees Iqbal 16f03734c9 📝 Say what bounds a surface block, and where planes go in place
RgfxSurfaceBlockShape.hpp gets the header the kext's others have: what a
copy block and a block in place hold, and the bounds that follow, a plane of
up to 4 GiB in place and of 256 MiB in a copy block. Its comment and its
test's messages said what changed ("existing", "original", "still") rather
than what the code does. design.md states the limits where it describes the
blocks in place, and that where every surface is cached the host keeps one
only within its device's maxBufferLength, as two boots on the Radeon 780M
showed (2 GiB in place; 2.15 to 4 GiB, a nil texture). Both prebuilt sets'
records take the header's new hash; the rebuild left their binaries as they
were (potluck m3-max-78425).
2026-12-02 06:47:37 -08:00
Anees Iqbal 2525fc4ac2 🐛 Charge a kept decoder by its pool's format and its own measured bytes
An idle epoch's 64 MiB bound charged each kept context 16 bytes a coded pixel
for each pool surface, twice Y412's eight and over ten times NV12's 1.5, so
no 4K decoder was ever kept (one surface's charge, 127 MiB, is past the
bound) and a 1080p one only with two surfaces. A kept context is now charged
its pool's surfaces at their format's bits a pixel, and its own allocations
at the 34,905,201 bytes DXGI's local count grew by for each 4K H.264 context
kept on the UHD 630 (m3-max-61642, in vaapi.md), scaled by its coded pixels.
A one-picture 4K session (context and two NV12 surfaces, 59.8 MB) is kept;
the bounds stay 16 contexts and 64 MiB.

The display counts the contexts taken back, and the cache's end logs the
count. The cache's hardware tests decode our own stream (target_check's
H.264, its level now sized to its picture, 240x144 still at level 3) instead
of an MP4 an environment variable named, and a measurement times one-picture
sessions at 720p, 1080p and 2160p with and without a cache. The lifecycle's
items, the idle bounds and the lock order are documented, the call thread's
taking the lifecycle gate inside the display's gate among them.
2026-12-02 06:47:28 -08:00
Anees Iqbal b950121daf ✅ Hold the decoder cache's entry cap with contexts alone
The test named for the cap filled an epoch with held teardowns, which make
the epoch by themselves, so it passed with the cap gone. The new test keeps
16 contexts with none living, one of them taken back and let go again, then
lets a 17th go and finds every entry made in the order let go: without the
cap's check it fails, the 17 kept. The old test is renamed for what it holds,
teardowns held while a context lives made with it, in order, under a cache.
2026-12-02 06:40:48 -08:00
Anees Iqbal 4c1c1c0cae 🐛 Build the decoder cache's take for Windows alone
Lifetimes::take has callers on Windows only, and its module is built for
tests on every host, so on Linux and the Mac the video crate's test build
left it unused and `cargo clippy --all-targets -- -D warnings` failed
(potluck m3-max-78365). It is built where it is called.
2026-12-02 06:40:48 -08:00
evanlau1798 c0d05f86f3 fix: retain bounded VA-API decoders between Windows sessions
Keep compatible idle decoder contexts under a device-owned epoch with entry and pixel-charge bounds. Serialize creation reservations with teardown dispatch, roll back failed creation, and drain retained resources when the final owner ends. Cover reuse, failure ordering, late frames and terminal cleanup.

(cherry picked from commit 2cb0352a4a)
2026-12-02 06:40:48 -08:00
evanlau1798 fb6a72bfc2 Merge pull request #212 from Evanlau1798/steelbrain/windows-idle-decoder-cache 2026-12-02 06:40:48 -08:00
Anees Iqbal 7414866224 🐛 Rebuild both guest kext sets for in-place IOSurfaces over 256 MiB
Our rebuild of ReimsGraphics for x86_64 and arm64e from PR 211's source, by
make -C guest prebuilt and prebuilt-arm64e with this repository's toolchain
(Xcode 27.2 27B52, Apple clang 21.0.0 clang-2100.4.1.1). The PR's own binaries
were built with another one (clang-2100.1.1.101, Xcode unrecorded) and are not
byte-equal to ours: rebuilt at the PR's head, ReimsGraphics differed on both
arches while RgfxGate and Graft matched (potluck m3-max-78354), so they are
left out of the tree.
2026-12-02 06:40:43 -08:00
evanlau1798 66b7fd8882 fix: keep large IOSurfaces in place within metadata bounds
(cherry picked from commit 52f4879747c0d19410b7c770e37fa2b6d85b3a52;
its two ReimsGraphics binaries and their records are left out for our rebuild.)
2026-12-02 06:40:41 -08:00
evanlau1798 5daeeb5aa8 Merge pull request #211 from Evanlau1798/steelbrain/iosurface-mapping-bounds 2026-12-02 06:40:41 -08:00
Anees Iqbal bf006c98ec ✅ Spawn the replaced-binary test's copy again while busy
linux_names_a_replaced_running_binary_deleted copies /bin/sleep and runs the
copy at once. Another test's child, forked while the copy's write handle was
open, keeps that handle until it execs, and the kernel refuses an exec of a
file open for writing with ETXTBSY: batch b1203's reims-ctl leg failed so
(m3-max-78396, "Text file busy" at the spawn; it passed in 78360). The test now
spawns again for up to 10 s while the exec answers ETXTBSY. Test only: nothing
changes for users.
2026-12-02 06:27:30 -08:00
Anees Iqbal 42cb346db3 🎨 Lint and format the batch's new tests
The batch's merge lint (b1203 legs, m3-max-78358/78359) failed on its own
tests: rustfmt wraps two asserts, clippy calls a one-element array of a range
in two surface-pages asserts (they now compare with a slice of one range), a
borrow of an already borrowed draw in a sink test, and std::thread::spawn in
the fold-race test, which now says why a test's own thread is allowed there.
Tests only: nothing changes for the guest or the host.
2026-12-02 06:23:20 -08:00
Anees Iqbal a2b6cb0cfc 🐛 Answer Encoded from rt's batched vertex draws
The replay of audit-f12 onto development put 4031863be8, which makes
RenderEncoder::encode_draws answer Encoded (recorded where the platform
recorded every command, refused where it refused any), beside development's
f4003f3ddb, which gave the rt platform its own encode_draws, batch_draws,
answering RaiseResult<()>. Each side built alone; together the Vulkan crate
did not compile.

batch_draws now answers as the commands one at a time answer: recorded where
rt recorded every bind and draw of the run, refused where it refused any, the
draws after a refused one still sent one at a time as before. Its tests
expect Encoded::RECORDED where they expected Ok(()), and check_draw_batch
compares the batch's answer with the one-at-a-time answer and checks it
against the refusals it counted: refused wherever one was counted.

Nothing changes for the guest or the host: the decoder takes encode_draws'
answer with go_on() (graphics/decode/cmdbuf.rs), as it does each command's.
2026-12-02 06:10:00 -08:00
Anees Iqbal 51be62538b 🐛 Wait out a fold in flight before an import looks at its pages
A fold of the views reads the imports' holds once, as it takes the views'
lock, then maps the runs no hold covers through dma-bufs. An import's hold
went into its table under no lock a fold holds, so a hold made while a fold
ran was missed: the import looked at where its pages lie before the fold
mapped them, found them mapped from their files, and handed rt their pointer,
which the fold then remapped as a VM_PFNMAP mapping. A driver that takes a
pointer's pages again once their mapping changed, as Intel's do (the fold
probe in docs/lessons.md), finds no pages there at the import's next use.

A hold now waits for a fold in flight once it is recorded, so the import's
look sees what that fold mapped and takes the dma-buf path, and a later fold
reads the hold. Folds run only at the views' budget, near vm.max_map_count,
or where the kernel refuses a map at its limit of mappings.

The test holds a fold in flight across an import's hold; with the wait taken
out it fails ("the import's look after its hold missed what the fold
mapped"), on homelab-um870-1 with udmabuf.
2026-12-02 06:10:00 -08:00
Anees Iqbal 7fafb7f9fb 🆕 Stamp the build's commit into reims-ctl and the library
A report could not say which builds it came from: reims-ctl's version was
the package's, and the library named its commit only where `cargo xtask
dist` set RVG_BUILD_COMMIT, so a QEMU or reims-ctl from another build than
the install's went unseen.

Each is now stamped at build time by a build script of its own, with no
new dependency: `git rev-parse HEAD`, `-dirty` where a tracked file of the
tree differs from it (Cargo.lock aside, which a build rewrites), and
`unknown` outside a checkout, never failing the build. The library's is
reims-vgpu-c's, handed to the Vulkan crate at the C API's first call, so
every build of it carries it, not only dist's; xtask's RVG_BUILD_COMMIT and
the recorder's own read of it go.

`reims-ctl --version` shows its stamp. The ask for the counts writes the
library's build line, `reims-vgpu: build <commit> on metal2vulkan <pin>`,
and system.txt's head names reims-ctl's stamp, the running library's as
the QEMU log names it, the install record's commit and the metal2vulkan
commit, with one plain line where the commits differ. Display only.
2026-12-02 06:10:00 -08:00
Anees Iqbal f2be18b911 🆕 Write a pacing line at the host's ask for the counts
A report of a slow app has said what degraded, not what held the app back:
the guest's own CPU work, the host's GPU, or the library's threads. At the
ask for the counts (rvg_write_counts, QEMU's x-write-counts), where the ask
before it was 2 to 60 s earlier, the library now writes one line over the
span between the two: each display's presents a second with the interval's
p50 and p99, the GPU's time per frame (p50, p99) and busy share from the
command buffers' GPU start and end times, merged where they overlap, and
the CPU of QEMU's vCPU threads, of ours by role (decoder, completion,
window, video, the rest by name) and of the rest of the process.

The state is fixed: a ring of 4096 shows per display and a few atomics for
the GPU, nothing allocated per frame. Thread times are read only at the
ask: /proc/self/task on Linux (with a table of the names Linux cuts at 15
bytes), task_threads and thread_info on macOS, a ToolHelp snapshot and
GetThreadTimes on Windows. rt gives no GPU times for its own command
buffers (uploads, fills, staging copies), for one that ended in an error,
nor for the host's video codecs; the line counts the ones without times.

reims-ctl report asks twice, 10 s apart, before vulkaninfo loads the GPU,
and its help, conventions.md and api.md say how to read the three
verdicts beside the guest's `top -o cpu -l 2`. A diagnostic: nothing
decides on it, the guest sees nothing new, and the C API gains no call,
so QEMU's side is unchanged.
2026-12-02 06:10:00 -08:00
Anees Iqbal 1e9766df08 📝 Move a stop test's doc comment onto that test [ci skip]
The doc comment of a_stop_timeout_of_0_waits_for_the_guest sat above
a_qmp_socket_directory_others_may_write_into_is_refused, joined to that
test's own, so rustdoc and a reader took both for the socket directory's
test and the stop's test had none. Comments only.
2026-12-02 06:10:00 -08:00
Anees Iqbal 9fc77b889b 🐛 Name the directory reims-ctl was installed in, in the PATH advice
scripts/install-ctl.sh installs reims-ctl into CARGO_INSTALL_ROOT's bin
where that is set, else Cargo's home's, but its closing advice, where the
user's shell does not run that reims-ctl first, always said to open a new
terminal or run . "$HOME/.cargo/env": rustup's env file for the default
Cargo home, which puts neither CARGO_INSTALL_ROOT's bin nor another
CARGO_HOME's on PATH. On Windows both the script and scripts/install.ps1
said to open a new window and run reims-ctl, which finds no reims-ctl in
CARGO_INSTALL_ROOT's bin, since rustup put only Cargo's own bin on the
user's PATH.

The advice is now the script's check_note, and says, for Cargo's home's
bin, ". "$HOME/.cargo/env"" or that CARGO_HOME's env file; for
CARGO_INSTALL_ROOT's, "DIR, CARGO_INSTALL_ROOT's bin, is not first on your
PATH, and a new terminal won't put it there: add it in your shell's
profile, as with: export PATH="DIR:$PATH"". On Windows, with
CARGO_INSTALL_ROOT set, the check line runs reims-ctl by its full path
and a warning says to add that bin to the PATH; install.ps1's last line
names the folder and says the same. Without CARGO_INSTALL_ROOT, Windows'
lines are as they were.
2026-12-02 06:10:00 -08:00
Anees Iqbal 424fb93a34 🐛 Power an arm64 VM off at once in its first boot, saying why
An arm64 VM's first boot makes macOS's Data volume by EACS and resets the
VM, which then stops in Ambrosia, its firmware, until reims-restore's
finish-eacs readies it: no guest runs there to shut down. A stop there sent
keys and the power button that nothing answered, waited out its 90 s, and
said the guest did not shut down in time, blaming a question about an
unsaved document or Setup Assistant.

reims-ctl knows the VM is in that boot cheaply and surely: the restore
keeps its copies of the iBoot system container's partition and of the
auxiliary storage (isc.pre-eacs, aux.pre-eacs) in the VM's directory until
finish-eacs readies the VM, and finish-eacs looks for the same two files.
Whether the boot has reset yet it can't tell without the guest's own
state, so the line says what the boot does and that the finish says
whether it got that far.

A stop of such a VM now sends nothing and powers it off at once:
  NAME is in its first boot: macOS makes its Data volume and then resets
  the VM, which stops in its firmware with no guest running to shut down
  until `reims-restore finish-eacs DIR` readies it. Powering off; the
  finish then says whether the boot got that far
With a stop timeout of 0, which never powers a VM off, it ends at once
with that error and "A forced stop powers it off" in place of the
power-off. Other VMs' stops and every timeout are unchanged.
2026-12-02 06:10:00 -08:00
Anees Iqbal 996e4062a5 🐛 Say when no request to shut down reached the guest
Where a stop's keys did not reach the guest and a timeout was set, a
failure of the power button's QMP call was dropped: the stop waited out its
timeout and then said the guest did not shut down in time, blaming a
question about an unsaved document or Setup Assistant, though no request
had reached the guest to be held up. Where the keys had reached it, the
button's failure was dropped as well, unsaid.

A stop now says at once that the power button did not reach the guest,
with what QMP answered ("the power button did not reach it either: QMP
system_powerdown: ..."), and where neither the keys nor the button reached
it, its last line before the power-off is "neither the keys nor the power
button reached the guest, so nothing asked it to shut down: powering off".
Where the keys reached it, that line stays as it was. The wait and the
timeout are unchanged.

The tests' fake QMP can now answer a command with QMP's error
(fake_qmp_replying, FakeQemu::refusing).
2026-12-02 06:10:00 -08:00
Anees Iqbal ac5b41b2ed 🐛 Fail a buffer as internal where the platform refuses a host copy
What the guest observes changes. e00ce9ff74 failed a guest's command buffer
with MTLCommandBufferErrorOutOfMemory where the platform refused a copy the
host made for it: a fill or a copy into a wide home at its begin, rule 1's copy
into a plane's other shapes, or a copy between a cache and its wide home at an
encoder's end. Nothing ran short of memory there, and an app may answer
OutOfMemory by letting go of caches of its own, so that answer was wrong. Such a
buffer now fails with MTLCommandBufferErrorInternal; OutOfMemory stays on the
existing route, a cache's buffer whose memory the platform refused.

The platform's refusal of a command does not say why it refused, and copy()
answers a copy that made no view or staging piece the same way, so every
refused copy answers the internal error, and none is mapped to OutOfMemory.
Where one command buffer meets both kinds, the memory's wins.

The host's writers' fence update at a guest encoder's end, which those copies
wait for, now folds its answer too: refused, the copies could not wait for the
encoder's writes, so the buffer fails with the internal error, counted under a
code of its own, surface-fence-refused, since it is no copy. The compute
encoder answered nothing of its commands, so ComputeEncoder gains
update_fence, which answers Encoded as a blit or render encoder's command does,
and CommandBuffer gains fail_internal, which rt keeps as it keeps a skipped
dispatch's failure: the first failure set is the one the buffer ends with.

Two new tests pin the fence fold, for a blit and a compute encoder; the fill
and rule 1 tests now expect the internal error and no OutOfMemory, and the
refused-memory test no internal error. Red before (m3-max-78155: the four
failed, the memory test passed). Green after: the reims-vgpu fake set
(m3-max-78157, 1172 passed, 115 skipped), its surface, shape and command buffer
rt tests with rt's compute and command buffer tests on the 5080 (m3-max-78159,
48 passed), and reims-vgpu-vulkan's own (m3-max-78160, 789 passed, 1 skipped).
2026-12-02 06:10:00 -08:00
Anees Iqbal aaedba617b 🐛 Answer a download failed where the platform refuses its copy
What the guest observes changes. Before, each copy the host makes for itself
between a surface's device cache, its shapes, its wide home and its pages took
the platform's answer to each command with go_on(), so a refused one changed
nothing of the caches' state. A shape whose write-back was refused was marked
written back, a refused fill marked its shape filled and the cache at the new
generation, and a SURFACE_DOWNLOAD whose copy into the pages was refused was
answered RGFX_STATUS_OK over the pages' older bytes, and never copied again.

Now each such copy folds its commands' answers, by the ruling that keeps
today's behaviour for the guest's own commands alone, and a refused one, or an
encoder the platform made not, leaves what it was to move as not copied:

- A shape whose write-back was refused stays dirty, and one whose fill was
  refused owes it still. A refused fill of the buffer leaves the cache at its
  older generation.
- A download whose copy into the pages was refused, or that waits for a copy
  that landed short (a refused later round of one that circulates its pieces),
  is answered failed (RGFX_STATUS_REFUSED) through the driver's existing path,
  where it was answered OK on stale bytes before. The cache stays written, so
  the next download copies it again. A refused copy's pieces put none of their
  bytes into the pages.
- A fill or a copy into a wide home refused at a command buffer's begin, and a
  write's copy into its plane's other shapes or a copy between a cache and its
  home refused at its encoder's end, fails that command buffer with
  MTLCommandBufferErrorOutOfMemory, as a cache's refused memory already does.
- An early copy refused is not made, its command buffer not committed, and the
  refill it carried no longer marks the buffer as holding the pages; that also
  holds where the platform refuses a copy by runs, which left it so before.

The host tries none of these again by itself: the next use, download or
release that needs the copy makes it. Each refusal is counted under
surface-copy-refused, the process's first logged at warn. The guest's own
blits and draws still go on past a refused command.

No rt-refused or rt-unbuilt code shows in the degradation counts of the 30
latest kept boot logs, so no boot has reached these paths so far.

Five new fake-platform tests, red before (m3-max-78078, all five failed), pass
with the fix: the reims-vgpu fake set (m3-max-78128, 1170 passed, 115 skipped)
and its surface, shape and command buffer rt tests on the 5080 (m3-max-78131,
31 passed).
2026-12-02 06:10:00 -08:00
Anees Iqbal 62ab502c71 🐛 Reserve no more of a library's chunks than the guest has sent
A LIBRARY_FROM_REGION's first chunk reserved the library's stated length, up
to 1 GiB, before any more of it came: total_length is the guest's and nothing
bounds it before the chunks arrive. A guest that started many library objects,
one small first chunk each, had the host reserve 1 GiB for each, without
bound; on a Windows host that is commit charge.

The form: nothing is reserved for the stated length. The kept bytes grow as
the chunks come, each time to at most twice the bytes that came, and never
past the stated length, which the chunk check already holds each chunk
within. A library sent in chunks reallocates a few times as it grows, which is
small beside its copy out of the region. What reaches the guest is unchanged.

a_library_s_chunks_keep_no_more_than_came sends a 64-byte first chunk of a
library said to be 2^40 bytes long: red at m3-max-78027 (1073741824 bytes kept
for 64), green at m3-max-78030 (reims-vgpu's fake set: 1165 passed, 115
skipped: the Vulkan and cost tests and the seed-1 decode test).
makes_a_library_from_region_chunks holds the valid chunks unchanged.
2026-12-02 06:10:00 -08:00
Anees Iqbal 5a965bdb69 📝 Say a pipeline create refused at its op is answered at once
The decoder's prepare_pipeline doc said a malformed create or one naming no
library "is not answered", and the device's start_pipeline said it is refused
"unanswered". Both callers answer it refused at once through refused_reply,
since its process waits for the reply, as
a_pipeline_create_refused_at_its_op_is_answered_at_once holds. The docs now
say what the code does.
2026-12-02 06:10:00 -08:00
Anees Iqbal bc613120fd 🐛 Hold the window's last frame where part of a frame is refused
The platform may refuse a pass or a command of a draw with no death (rt
counts it and the command buffer still completes). The window went on past
such a refusal and presented what was recorded: a frame with the scanout's
blit, the colour's pass, the cursor's or the overlay's pass missing or cut
short, shown to the person at the host as if whole.

Now a frame of the window in which any pass or command was refused, the
cursor's, the overlay's and the overlay-over-black clear among them, is not
presented: nothing of it is committed, its presents are let go as at any
draw that shows nothing, and the window keeps its last complete frame. The
frame is counted under display-frame-refused, which the report's counts
carry, and the first is logged at WARN saying the window holds its last
frame. The next frame is drawn and judged afresh: no latch, no retry. A
colour's table whose draw is refused still answers for itself (the frame
takes the colour's pass and is presented), and the host's read of the
display already failed on a refused draw.

What changed for the host: a frame refused in part is no longer shown.

a_frame_the_platform_refuses_part_of_is_not_presented refuses the scanout's
copy, the colour's draw, the cursor's draw and the cursor's pass in turn on
the fake: red at m3-max-77985 (a refused copy's frame was presented), green
at m3-max-77996 (1164 passed, 115 skipped: the Vulkan and cost tests and the
seed-1 decode test).
2026-12-02 06:10:00 -08:00
Anees Iqbal d6fbeca2dc 🐛 Walk a SURFACE_PAGES's runs only over the guest's RAM
Hardening: only a guest driver that writes its runs wrong reaches this; the
kext lists a surface's wired pages once each. What the host does for valid
runs is unchanged.

A SURFACE_PAGES's begin waits for the copies of released device caches into
its pages before it checks its runs (graphics.rs start_surface_pages, through
the decoder's wait_copies_into), and takes the runs' host pages for that from
SurfaceViews::host_runs, which walked every run a guest page at a time, the
pages outside the guest's RAM too, on ring 0's lane and under the views' lock.
A run near 2^63 bytes long held both for good, and runs that named the same RAM
again and again grew the list by the RAM's pages for each. Nothing else of the
device moves on ring 0 meanwhile, and design.md holds that no guest input
hangs QEMU.

Now each run is walked only where it meets the memory map's ranges, a page
two ranges hold once, and the walk ends once it has walked as many pages as
the map holds. The pages it names for runs inside the RAM are those it named
before.

Red first: a_run_past_the_ram_is_walked_only_over_it (no answer in 10 s) and
runs_that_name_the_ram_again_walk_it_once (4096 pages walked for a RAM of 4)
failed on the tree before, host_runs split into host_pages walking as it did
(job m3-max-77972), and pass with this, with every
fake test of graphics, the decoder and reims-vgpu-graphics, the surface pages'
and caches' among them (job m3-max-77976: 1335 passed, 216 skipped, the
skipped the Vulkan and cost tests, which need a GPU, and the own-queue seed
test, red until its fix).
2026-12-02 06:10:00 -08:00
Anees Iqbal 3edafe23d6 🐛 Read a VideoToolbox message's runs no further than its bytes
Hardening: only a guest driver that writes its runs wrong reaches this; the
kext lists each buffer's wired pages once. What the guest observes changes
for such runs alone.

A VT_MESSAGE's bytes, and a lent surface's run table, are read from guest RAM
by GraphicsDecoder::guest_bytes, which listed every page of every run before
it cut the list at the message's length, then reserved that length. So runs
after the bytes were walked whole (a run past the guest's RAM refused the
message, though its bytes lay in RAM), runs that named the same RAM again and
again grew the list by the RAM's pages for each, and a run table's length,
the sum of its runs, which the guest sets and nothing bounds, was reserved at
once: with_table_runs hands it over, and runs that repeat over mapped RAM made
a reservation of up to their count times the guest's RAM, which aborts QEMU.

Now guest_bytes walks the runs only as far as its length reaches
(SurfaceViews::host_pages_through), and refuses a length larger than the
guest RAM the memory map holds, which only repeated runs hold, before it
reads or reserves anything. A table read can still reserve up to the guest's
RAM once, for a table whose repeated runs hold that much; with_table_runs is
not changed. The run tables and messages the kext writes read as before.

Red first: a_vt_message_s_bytes_are_read_no_further_than_its_length failed on
the tree before (job m3-max-77972: a message whose second run leaves the RAM
was refused), and passes with this, with every fake test of graphics, the
decoder and reims-vgpu-graphics (job m3-max-77976: 1335 passed, 216 skipped,
the skipped the Vulkan and cost tests, which need a GPU, and the own-queue
seed test, red until its fix).
2026-12-02 06:10:00 -08:00
Anees Iqbal b1bc15e599 🐛 Fail a read of the display whose draw the platform refuses
What the host observes changes. A read of the display
(rvg_graphics_device_read_display, which QEMU's console and its screendump
use) draws what the display shows into a texture it keeps for the next read of
the same size, then reads it back. Where the
platform refused a pass or a command of that draw with no death (on the Vulkan
platform, metal2vulkan-runtime counts the refusal and the command buffer still
completes), the texture kept what it held and the read answered Ok with the
last read's pixels; a refused blit encoder answered Ok with black.

Now every pass and command of the display's draw folds the platform's answer
(Encoded) into the draw's own, and encode_shown gives it to its caller. A read
whose draw the platform refused any of fails with Error::Metal, as a refused
draw does, with nothing committed or written. The window's draw goes on past
a refused command as before and shows what was recorded; that is unchanged.

Red first: a_read_whose_draw_the_platform_refuses_fails failed on the tree
before (job m3-max-77937: the read answered Ok after the refused scanout blit)
and passes with this (job m3-max-77947, with every fake test of the display,
the reads, the decoder, video_host and core). The display's Vulkan tests now
take encode_shown's answer and check that nothing was refused, and pass on
the Iris Xe and the Radeon 780M (jobs m3-max-77948, m3-max-77952).
2026-12-02 06:10:00 -08:00
Anees Iqbal 6ec9f5f87b 🐛 Draw the colour through its pass where its table's draw is refused
What the host's window shows changes. A colour with no matrix is drawn through
a table, which the colour's pass first draws into its own texture; the table
counted as drawn once a command buffer that drew it completed. Where the
platform refused the table's draw at encode (on the Vulkan platform,
metal2vulkan-runtime counts the refusal and the command buffer still
completes), the table held nothing drawn and was still taken as drawn: that
frame and every later one of the colour went through an undrawn table, its
contents undefined, until the colour changed.

Now the table's draw answers whether the platform recorded its pass and every
command (Encoded). Where it did not, that frame takes the colour's pass, the
same per-pixel draw a colour with a matrix takes, so the guest's colour still
shows. The refusal is kept in the table's one place, for its colour, what it
reads and the drawable's format, logged once and counted under the new code
display-table-refused, which the degradation counts report. Each draw for
those takes the pass with no table drawn, and the table is drawn again only
for another colour, read or format, or after the device's recovery. No frame
goes through a table whose draw was refused.

Red first: a_table_whose_draw_is_refused_takes_the_pass_until_the_colour_changes
failed on the tree before (job m3-max-77937: the frame went through the
refused table) and passes with this (job m3-max-77947, every fake test of the
display, the reads, the decoder, video_host and core). The Vulkan tests of
the table, on_vulkan_the_table_draws_what_the_pass_draws among them, now also
check that the table was drawn, and pass on the Iris Xe and the Radeon 780M
(jobs m3-max-77948, m3-max-77952).
2026-12-02 06:09:59 -08:00
Anees Iqbal cd2e742ed7 ✅ Check each blit command's answer against rt's count
The rt tests' blit helpers asserted that rt recorded every command they sent,
since the blit encoder answers Encoded (84d84c687a). rt refuses some of them,
and says so truthfully: fillBuffer:range:pattern4: and copyFromBuffer:...
options: are unbuilt (rt-unbuilt-blit), and a command after endEncoding is
Metal's refusal. So blits_on_vulkan, plane_copies_on_vulkan and
indirect_command_buffers_on_vulkan failed on the GPU (job m3-max-77939, the
Iris Xe on ANV), though rt's answers were right.

Each helper now checks every command's answer against what rt counted for
it: refused exactly where a refusal was counted under an rt-refused- or
rt-unbuilt- code, recorded otherwise. An end that ends an open encoder still
answers recorded, and the second end in blits_on_vulkan answers refused.
Nothing is loosened: a command rt records and the test once took as recorded
is still checked as recorded.

Checked on the Iris Xe (ANV, job m3-max-77948) and the Radeon 780M (RADV, job
m3-max-77952): rt's render, command, buffer, blit and texture tests and the
recorder's all pass.
2026-12-02 06:09:59 -08:00
Anees Iqbal 156be1b48f 🆕 Answer whether the render encoder recorded each command
The render encoder answered nothing for a command the platform refused with
no death. metal2vulkan-runtime counts such a refusal (rt-refused-<kind>,
rt-unbuilt-<piece>, Metal's own) and goes on, and the command buffer still
completes, so host work that drew with it could not tell a refused draw from
a drawn one: the display's colour table counted as drawn though its draw was
refused, and a read of the display answered the last read's pixels.

RenderEncoder::encode and encode_draws now answer Encoded, the blit encoder's
must-use answer: encode_draws is recorded where every command of it was. The
rt platform answers refused where it stopped the command, the fake where its
script answers nil for it. render_encoders_on_vulkan checks that rt refuses
exactly the commands it counted, and
a_render_command_the_script_answers_nil_is_refused the fake.

Every caller takes the answer with go_on(), so nothing changes for the guest
or the host: the guest's own render commands, the decoder's ends and fences,
the surface caches' clears, the video planes' clears and the display's
draws go on past a refused command as before, counted where it stopped. The
display's draws use the answer in the commits that follow.

Checked: the fake's tests of the decoder, the display, the reads, video_host
and core (job m3-max-77937, all pass but the two red tests of the next
commits, which were not in this commit), and rt's render, command, buffer and
blit tests on the Iris Xe (job m3-max-77939, all pass but three of the blit
encoder's from the commit before, which assert recorded for commands rt
refuses).
2026-12-02 06:09:59 -08:00
Anees Iqbal 085a511242 🆕 Count a session's pictures whose cache copy was not made
A picture whose copy into its output's device caches the platform did not
make (no blit encoder for it, or a staging copy it refused) fails to land,
counted among a session's failures since the two commits before. It is now
also counted apart, as its own class: the session's end line says how many of
its failed pictures were such, so a report tells that class from a driver's
failure without a pixel read. The landing sets the class as its copy fails
(Stage's unmade, taken at each landing's failure) and the session counts it.

The two tests of those failures check the count:
a_copy_into_caches_the_platform_makes_no_blit_encoder_for_fails_the_landing and
a_staging_copy_into_caches_the_platform_refuses_fails_the_landing (job
m3-max-77893 at this content).
2026-12-02 06:09:59 -08:00
Anees Iqbal c86344623c 🐛 Fail a picture's landing where the platform refuses its copy
What the guest observes changes. Before, a staging copy of a picture into its
output's device caches that the platform refused recorded nothing and the
picture still counted as landed: metal2vulkan-runtime counts such a refusal
under rt-refused-<kind> and goes on, and the host's landing could not tell, so a
reader was handed the caches' earlier bytes, a new output's zeros, as the
picture. Now the copy answers an error, as a copy with no blit encoder does
since the commit before: its command buffer goes uncommitted, the picture fails
to land (its command buffer completes failed) and counts as a failure; an
encode's copy of its source out of the caches fails the frame. Its warn line
names itself a staging copy, so a log tells it from a guest blit's.

To tell, the platform's blit encoder answers whether it recorded each command:
BlitEncoder::encode returns Encoded, a type of its own in
core::platform::encoded, named for no encoder so another encoder's commands can
answer it later. The rt platform answers refused where it stopped the command
(Metal's refusal, an unbuilt piece, rt's own), the fake where its script answers
nil for it. Every caller takes the answer: Encoded is #[must_use] and the
workspace now denies unused_must_use, so an ignored one does not compile. The
guest's own blits and every other host copy keep today's behaviour exactly,
saying so with go_on(): a refused command is counted where it stopped and the
work goes on.

Red first: a_staging_copy_into_caches_the_platform_refuses_fails_the_landing
failed on the tree before (job m3-max-77886: the picture counted as landed) and
passes with this, with every video_host and graphics::decode test but the
own-queue seed test, red until its fix (job m3-max-77893, the last at this
content but for rustfmt).
2026-12-02 06:09:59 -08:00
Anees Iqbal cb9898918b 🐛 Fail a picture's landing where its cache copy has no encoder
What the guest observes changes. Before, where the host's video landing found
no blit encoder for its copy of a picture's staged planes into the output's
device caches, the copy was skipped and the picture counted as landed: its
value was signalled and the command buffer waiting for it completed as for any
landed picture, so a reader was handed the caches' earlier bytes, a new
output's zeros, as the picture, with no error to the guest. 7ca9d53fa4 made
that skip; this puts back the failure it replaced.

Now the copy answers an error, as an encode's copy out of the caches already
does: the landing fails through the path of any picture that did not land.
The planes owed zeros are cleared, the command buffer that waits for the
picture completes failed (Metal's internal error, which the guest's video
driver answers as a decode error), and it counts as a failure to land. The
warn line now says the picture does not land; the library's logger keeps it to
the process's first, the rest at debug, counted, as the docs say.

On metal2vulkan-runtime the case is not reached today: it refuses a blit
encoder only on a committed command buffer or one with another encoder open,
and this one is made the line before. The test changes with the behaviour:
a_copy_into_caches_the_platform_makes_no_blit_encoder_for_fails_the_landing
replaces ..._is_skipped.
2026-12-02 06:09:59 -08:00
Anees Iqbal fef583a53d 📝 Say that KWin maps no X11 window while every screen is off [ci skip]
The X11 route's proof on ms01 (m3-max-78242) showed no frame on the 3090 or
the Iris. The session was unlocked, but both screens were off (DPMS), and
KWin then keeps every new X11 window unmapped (_NET_WM_STATE_HIDDEN, no
WM_STATE): the library's, xmessage's and a bare SDL 3 window's alike.
SDL's X11_ShowWindow waits for MapNotify with no time limit, so the UI
thread stopped there before a swapchain was made. With the screens on, the
window showed a frame through X11 on both cards, at development and at
3731afd9b1 (m3-max-78332, m3-max-78336; um790's XTX and 780M, m3-max-78312).

The lesson that blamed the lock alone now names the screens, and the
desktop test's doc says its harness unlocks the session and turns the
screens on first. Nothing changes for the host.
2026-12-02 06:07:46 -08:00
Anees Iqbal 37af90950e 🐛 Leave the window system to SDL where the GPU presents to Wayland
09f166332e named Wayland to SDL wherever the window's GPU presents to the
compositor. That also covered compositors without fifo-v1 (cosmic-comp among
them), where SDL takes XWayland on its own. On those compositors it moved a
route that shows a window today, and it was never run on one.

The user's report needs a named window system only where SDL's own pick
cannot show a window: the GPU presents to the X server and not to the
compositor. Now X11 is named only there. Where the GPU presents to the
compositor, nothing is named and SDL picks as it did before 09f166332e:
Wayland, or XWayland where the compositor has no fifo-v1.

What changes for the host: on a Wayland compositor without fifo-v1, windows
open through XWayland again, as before 09f166332e, and the log's choice reads
"SDL's own pick". Nothing changes where the GPU does not present to the
compositor, or where the compositor has fifo-v1.

The window-system test's Wayland pairs now expect SDL's own pick. The register
entry and the C API doc say the same.
2026-12-02 05:41:22 -08:00
Anees Iqbal 60a927846d ⬆️ Build on metal2vulkan development d8735b75f0
The range from 0b0ac58eb0 is 22 commits, among them three pull requests
from users that main took:
- PR 22: a biased buffer offset carries into the high word of a GPU
  address. The translator makes a slot's direct base and address once where
  it dominates, and each access adds its carry alone. A shader that reads a
  buffer through an offset whose sum crosses a 32-bit word of the address
  now reaches the right bytes.
- PR 18: a shared uniform range inside a fixed array is covered whole.
- PR 23: render push constants go to the GPU as aligned deltas, and a
  render buffer's offset changes without its push data being built again.
The runtime also changes in two places. A command marks its writes to a
Managed buffer's texture overlay and takes their copies back in its own
segment, after its command buffer begins. Every acquire of a Direct3D 11
video plane, the first one included, names the general layout (Windows
hosts).
The last commit re-blesses the translator's golden tables at semantics 2310;
it is tests only.

What changes for the guest: a shader whose buffer offset crosses an address
word reads and writes the right bytes, where on some cards it reached the
wrong ones. Every guest kernel is translated again at its first use after
the update, since the translator's semantics moved to 2310.
2026-12-02 04:56:39 -08:00
Anees Iqbal 105a263b7d 🎨 Keep the mode bound out of the wire header; lint the mode work
The smaller-modes commits failed the batch's lint legs three ways:
- MODES_MAX became public, so cbindgen wrote it into reims_graphics_wire.h,
  which the guest's kexts and the option ROM compile. It is a host-side
  bound (the guest reads each display's count from the DISPLAYS answer), so
  it is marked cbindgen:ignore and the header stays as it was, with no ROM
  or kext set to rebuild;
- clippy's type_complexity on the window draw's route field, now the
  DrawRoute alias;
- rustfmt's layout of two test tables.

Nothing changes for the guest or the host.
2026-12-02 04:56:39 -08:00
Anees Iqbal 27fe783b8e 🔊 Name the display draw's route in a debug line on each change
The window's draw and the host's reads of the display copy a frame of its
place's size and sample one of another size. Nothing in a boot's log said
which route a draw took, so a boot could not show that a display's first
mode is still copied as before. A debug line under reims_vgpu::graphics now
names the route, the frame's size and the place's whenever one of them
changes. Diagnostics only: what the guest and the host see is unchanged.
2026-12-02 04:39:59 -08:00
Anees Iqbal 5de45f1353 🎨 Offer a display's smaller modes at a Mac's external-4K steps
A display's smaller modes now follow the steps 7/8, 47/60, 3/4, 2/3, 1/2 and
3/8 of its first mode's width, in place of 7/8, 3/4, 1/2, 15/32, 5/12 and 3/8.
The guest sees a different list in Displays: a 3840 x 2160 window offers
3360 x 1890, 3008 x 1692, 2880 x 1620, 2560 x 1440, 1920 x 1080 and
1440 x 810 below its own, which is the list a Mac gives an external 4K
screen. Before, it offered 1792 x 1008 and 1600 x 900, near twins of
1920 x 1080, and not 2560 x 1440.

7/8, 3/4, 1/2 and 3/8 were read on our Mac's built-in panel. 47/60 and 2/3
come from a user's report and from what is known of the external-screen
list; no Mac of ours was read for them, and the comment says so. The mode
tests, the window's fill examples, the device's DISPLAYS answers and the
wire-2 peer trace are recomputed for the new steps: a 1280 x 800 screen now
lists four modes, 992 x 620 among them.
2026-12-02 04:39:59 -08:00
Anees Iqbal aea838debe 🎨 State the mode count's bound as clippy asks
clippy's int_plus_one refuses `1 + n <= max` under -D warnings; `n < max` is the
same bound, and a comment keeps what it counts.
2026-12-02 04:39:58 -08:00
Anees Iqbal 9f19151665 📝 Describe a display's smaller modes in the docs [ci skip]
The design's display rule, the architecture's window and the README said a
display offers its guest one mode. They now say what it offers after the
window's pixels, where the steps come from, and that the window keeps its
size at a smaller mode and shows it scaled to fill it.
2026-12-02 04:39:58 -08:00
Anees Iqbal faedd8d254 📝 Register a smaller mode in the window's features
The reims-graphics window's register said its guest is offered one mode,
the window's pixels, and that the pass copies the guest's scanout or a
surface of the drawable's format. The display now offers the smaller modes
of the window's ratio after it, and at one the window keeps its size and
draws the guest's frame scaled to fill it; the pass copies only a frame the
size of its place.

The entries say so, on macOS and on Linux and Windows hosts, guarded by
the rule's tests, the layout's fill, the sink's sampled draw and its GPU
test, the first mode's unchanged draw, and a manual pick of a smaller mode
in the guest's Displays settings.

A Windows window's resize to the next size the guest is offered whole (the
entry before) runs only on the person's resize, and the window never
follows the guest's mode, so a smaller mode leaves it as it is: the two
entries stand together.
2026-12-02 04:39:58 -08:00
Anees Iqbal d6ba6fe21f 🆕 Fill the window with a mode under two rows off its ratio
The layout fitted every guest mode into the window between black bars. A
smaller mode the display offers is its first mode's ratio with the height
rounded down to even, so it is up to two rows short of the window's ratio,
and a fit left a row or two of black above and below it: 1680 x 944 in a
1920 x 1080 window, 1488 x 996 in a 1712 x 1148 one.

A guest mode whose height is less than two rows (MODE_HEIGHT_STEP) from
its width's at the area's ratio now fills the area, stretched by less than
those two rows. The pointer maps through the image as at any mode, and the
guest's cursor is drawn at its scale. Modes further from the ratio, a
16:10 mode in a 16:9 window or the first mode in a window a step wider,
are fitted between bars as before, and a mode within a step of the area's
pixels is still drawn a pixel to a pixel at its top left.

What the host observes: a smaller mode of the window's ratio fills the
window with no black beside it (geometry's new test, on windows whose
pixels are a mode's and on a borderless one a pixel past it).
2026-12-02 04:39:58 -08:00
Anees Iqbal fb3108a832 🆕 Scale a frame of another size than its place to fill it
A display now offers smaller modes, and its window keeps its size at them,
so the window's draw must fill the window with a frame smaller than it. The
draw copied the scanout, and a BGRA8 surface, a guest pixel to a pixel at
the image's top left, clipped: a smaller mode showed in a corner.

One rule now draws what the display shows: a copy where the frame (the
scanout, or a presented surface in the drawable's format) is the size of
its place, the layout's region, and otherwise a draw of the display's
present shaders that samples it over the whole place, filtering linearly.
The scanout is sampled through a texture over its pixels in its pages'
import, in place, made at its first such draw and kept with the import
(made again after a recovery); a refused one keeps the window's frame and
counts as the display's refused view (display-view-refused), as a refused
view of a surface does. The colour's draw follows the same rule. The
host's read of the display (QEMU's console and screendump) draws with it,
so it shows a smaller mode scaled to the display's first mode.

What the host observes: at a smaller mode the window, and the read, show
the guest's frame filling the image's place; while a resized window waits
for the guest's next mode, the old one is scaled to the new place rather
than clipped. At the display's first mode every draw is the one it was,
and makes nothing more: a test holds it for the scanout, a BGRA8 surface
and WindowServer's 10-bit one, and others hold the sampled draws and the
refused texture; a GPU test holds that a 2 x 2 scanout and surface fill an
8 x 8 drawable on the Vulkan platform. The read's tests held the old draw,
a small scanout at the read's top left and the rest black: they now read a
scanout of the mode's size pixel for pixel, a smaller scanout scaled over
the whole read with its corners at the read's corners, and a smaller
surface drawn through the display's view of it, not copied.
2026-12-02 04:39:58 -08:00
Anees Iqbal 934ce50043 🆕 Offer a display's smaller modes of its screen's ratio
A display offered its guest one mode, the window's size in pixels, so the
guest's Displays settings listed nothing else to pick. The owner asked for
more of the host's resolutions there.

GET_DISPLAYS now lists, after that first mode, which the guest still
prefers, the smaller modes of its ratio at a Mac's steps: 7/8, 3/4, 1/2,
15/32, 5/12 and 3/8 of its width, rounded down to a multiple of 16, each
with the first mode's ratio of that width rounded down to even. The steps
are those of the modes of its own ratio CoreGraphics lists below a MacBook
Pro 16-inch's 3072 x 1920 panel (2019, macOS 26.7.1, read on the oracle
2026-12-02): 2688 x 1680 down to 1152 x 720. None is below 800 x 600, the
smallest that Mac takes for its desktop (840 x 524 and 640 x 480 not), each
fits the display's scanout room, and there are at most eight modes. Every
mode carries the first one's refresh rate, so the guest runs at the host
screen's rate whichever it picks. A 3840 x 2160 window is offered 3360 x
1890, 2880 x 1620, 1920 x 1080, 1792 x 1008, 1600 x 900 and 1440 x 810.

What the guest observes: each display record's mode count is now the mode
records that follow it, one to eight of them, where it was always one; the
first record, its scale record and DISPLAY_CHANGED are as before. The
tests that held the one-mode answer, and the recorded wire-2 trace, change
with it; new tests hold the rule (a Mac panel's own list, odd sizes,
portrait, the floor, the room) and each display's count against the
records the guest's kext walks.
2026-12-02 04:39:58 -08:00
evanlau1798 2cb0352a4a fix: retain bounded VA-API decoders between Windows sessions
Keep compatible idle decoder contexts under a device-owned epoch with entry and pixel-charge bounds. Serialize creation reservations with teardown dispatch, roll back failed creation, and drain retained resources when the final owner ends. Cover reuse, failure ordering, late frames and terminal cleanup.
2026-12-02 20:08:07 +08:00
Anees Iqbal 41f0bba449 📝 Say a full disk pauses a VM on Windows hosts too
QEMU's move to the fork's tip took PR 22, whose file-win32 and win32-aio map
ERROR_DISK_FULL and ERROR_HANDLE_DISK_FULL to ENOSPC, where they gave EINVAL or
EIO before. A Windows host's full disk now pauses the VM as Linux's and macOS's
do, so the disk-full state's note says every host.
2026-12-02 03:25:10 -08:00
Anees Iqbal 9b2e3de865 🆕 Resume a paused VM with reims-ctl resume and the interface's R
A VM QEMU paused because the host's disk is full had no way back in
reims-ctl: its state told the user to send QMP's cont to its socket, and a
stop waited out its timeout on a guest that does not run, then powered it
off, losing the writes QEMU held for it.

reims-ctl resume NAME, and R in the interface's list and menu (shown while
the VM is paused that way), send QMP's cont to a VM that QEMU paused, for
whatever reason, and watch it for 2 s: QEMU runs the failed writes again as
the VM resumes, and pauses it again at once where the disk is still full.
The resume then fails, naming the file QEMU could not write and saying to
free space first; it never reports success. A VM that runs, or is not
running, is refused, saying so, with no cont sent. The disk-full state now
names the command in place of the QMP step, and a stop of a VM paused that
way says, before it powers the VM off, that this loses the writes QEMU
holds, with resume as the other way out; stop's timeouts are as they were.
README's day-to-day commands list resume.

On the fake QMP, now a FakeQemu whose cont runs the VM unless its disk is
still full: a_resume_resumes_a_vm_paused_on_a_full_disk,
a_resume_of_a_vm_not_paused_says_so,
a_resume_on_a_disk_still_full_says_it_paused_again and
a_stop_of_a_vm_paused_on_a_full_disk_says_what_powering_off_loses;
a_vm_paused_on_a_full_host_disk_says_so holds the state's new text, and
the menu test holds Resume in a paused VM's menu.
2026-12-02 03:19:56 -08:00
Anees Iqbal e61b85f09e ✅ Name the tests' fake-QMP VMs for themselves
Where a temporary directory's path is too long for a socket, as potluck's
TMPDIR is on Linux, a VM's QMP socket is named for the VM in the runtime
directory, so every test VM named "t" shares one socket there. The stop test
bound its fake QMP at t's, and the interface's restate test, whose VMs are
"t" and "u", now asks each running VM's socket whether QEMU paused it: on
homelab-um870-1 (job m3-max-77860) the stop test failed and the disk-full
test could not bind its socket. Each of the two tests that serve a fake QMP
now names its VM for itself and the process, as logs.rs's counts test does.
On the Mac with a TMPDIR as long, the stop test failed in 2 of 2 runs before
and every test passed in 3 of 3 after.
2026-12-02 03:19:56 -08:00
Anees Iqbal 256b1e7149 🆕 Say when QEMU paused a VM because the host's disk is full
A write to a VM's disk that finds the host's file system full pauses the VM:
the disk's AHCI or virtio device takes QEMU's default werror=enospc, and on
Linux and macOS hosts QEMU's file-posix reports a full file system as ENOSPC
(on Windows, vendor/qemu's file-win32 reports such a write as EINVAL or EIO,
which fails the guest's write and leaves the VM running). reims-ctl read only
QEMU's pid, so a paused VM showed as running, with nothing to say why its
guest stood still or what to do.

A running VM's state now asks its QMP socket: where query-status answers
io-error and query-block names a disk whose io-status is nospace, the VM is
paused, and its state says the host's disk is full, the file QEMU could not
write, and how to go on: free space on that disk, then QMP's cont on the VM's
socket, after which QEMU runs the failed writes again. reims-ctl has no resume
of its own. show and the interface's details give that line; list's STATE
column says paused, with the line below the table, and list --json gives it
as why; the interface's list says "paused: disk full". The interface asks on
a thread of its own, one ask per VM at a time, and a socket that does not
answer in 2 s, as while another client holds it, leaves the state as it was.

a_vm_paused_on_a_full_host_disk_says_so holds the line, on the fake QMP
answering as QEMU does for such a VM, and the state once QEMU runs again.
2026-12-02 03:19:56 -08:00
Anees Iqbal a28f1a221c ⬆️ Move QEMU to the fork's tip with PR 22's Windows disk fixes
The fork's integration for the 12-02 PR order: PRs 21, 23, 19 and 22, the
credit merges of 20 and 14, and the fix-forward of the WHPX TSC probe and
MMIO lines. PR 22 is taken whole, as benched: on reims-ctl's Windows disk
path it stops a failed read from coming back as zeros with success and
a truncate from racing the pool's requests, both reproduced on the base.
A full host disk now pauses the VM, as it already does on Linux.

qemu.md's rows name the fork's commits by hash now that they are final.
2026-12-02 03:08:28 -08:00
Anees Iqbal 963113f191 ✅ Write the mode test's zip as made on Unix on every host
reims-restore's a_members_unix_mode_is_kept failed on Windows (left 0o664,
right 0o755): zip 9.5.1's writer marks a member made on Windows as DOS's
unless the options name the system, and for a DOS member the reader makes
up 0o664. The reader is right for what it reads, since Apple's IPSWs are
made on Unix; the fixture depended on the host that wrote it. Name the
system as Unix in the test's options.
2026-12-02 02:51:42 -08:00
Anees Iqbal 6fa16606fe 📝 Record the HiDPI crossing on x86-64 11.7.11 and 15.8.2 [ci skip]
The cursor's reading of a HiDPI display's rectangle in points held on
x86-64 11.7.11 and 15.8.2 as on 26.7.2: six reads of six on the display
under the host's pointer on each (m3-max-77845, m3-max-77851).
2026-12-02 02:46:27 -08:00
Anees Iqbal a7d2230a33 📝 Record an x86-64 guest's video with no paravirtual service [ci skip]
The control boot of the host that lists an x86-64 guest no paravirtual
decoder: x86-64 macOS 26.7.2 on a Radeon 780M lists AppleGVA's H.264 and
HEVC decoders and encoders again, decodes and encodes both on the host and
decodes HEIC's tiles there, and has no AV1 or VP9 decoder (m3-max-77840).
2026-12-02 02:46:27 -08:00
Anees Iqbal 62a38a75b5 📝 Say the cursor reads a HiDPI display's rectangle in points [ci skip]
The design said each framebuffer's getBoundingRect is its display's
CGDisplayBounds, which holds at 1x alone. The kexts read the second of the
two rectangles it points to, the one IOHIDSystem keeps as the display's
desktop rectangle, and that one is in points on a HiDPI display too:
x86-64 26.7.2 with one HiDPI display and one at 1x moved the cursor to
the points under the host's pointer, six reads of six (m3-max-77828).
2026-12-02 02:46:27 -08:00
Anees Iqbal 42ba8b4ed8 📝 Say why an x86-64 guest gets no paravirtual video
The docs said x86-64 macOS 26 takes AV1 and VP9 from the host through
VideoToolbox's paravirtual path. The host now lists an x86-64 guest no
paravirtual decoder or encoder, and the docs say what the boots with the
service published measured: H.264 and HEVC sessions taken off AppleGVA,
AppleGVA's H.264 decoder and encoder gone with AV1 and VP9 alone listed,
and every paravirtual session failing -19092.

The run under WHPX that the service was offered on is cited as the
contribution's, not measured here. Safari's sandbox rule for the service
is described rather than quoted, and the docs say that reims-ctl's VMs
hide the VM from kern.hv_vmm_present, so Safari there would be denied the
service until reims-util#4. The user-facing known issue says what an Intel
Mac guest gets for VP9 and AV1.
2026-12-02 02:46:27 -08:00
Anees Iqbal 5aa632a32f 🐛 List an x86-64 guest no paravirtual decoder or encoder
The x86-64 kext publishes VideoToolbox's paravirtualization service where
the host lists a decoder, and x86-64 macOS 26.7.2's VideoToolbox then loses
more than it gains, on an RTX 3090 and a Radeon 780M:
- with every codec listed, H.264 and HEVC sessions, their encodes and HEIC's
  tiles left AppleGVA for the paravirtual host (m3-max-77800, -77801);
- with AV1 and VP9 alone listed, AppleGVA's H.264 decoder and encoder were
  gone: sessions requiring hardware H.264 failed -12906 and -12908, while
  HEVC stayed on AppleGVA (m3-max-77828);
- every paravirtual decode and encode failed each sample -19092, the
  guest's VTDecoderSessionEmitDecodedFrame failing the first emitted frame,
  so AV1 and VP9 decoded nowhere.

The host now lists an x86-64 guest no paravirtual decoder or encoder, so
its kext publishes no service and its hardware video is AppleGVA's, as
before the service: H.264 and HEVC decodes and encodes and HEIC's tiles on
the host, AV1 and VP9 in no hardware. An arm64 guest is listed every
decoder and encoder, as before.
2026-12-02 02:46:27 -08:00
Anees Iqbal 2d2a277048 📝 Say which guests' VideoToolbox runs the paravirtual sessions
The paravirt module's row in the video docs and the VideoToolbox backend's
module doc named an arm64 guest alone. An x86-64 guest's VideoToolbox runs
them too, for AV1 and VP9 decodes alone, as the host lists it.
2026-12-02 02:46:27 -08:00
Anees Iqbal 8ac978f8d7 🐛 List an x86-64 guest the paravirtual AV1 and VP9 decoders alone
With the x86-64 kext publishing VideoToolbox's paravirtualization service,
x86-64 macOS 26's VideoToolbox took the paravirtual decoder or encoder of a
codec over AppleGVA's: H.264 and HEVC sessions, H.264 and HEVC encodes and
HEIC's tiles all reached the paravirtual host on an RTX 3090 and a Radeon
780M (potluck jobs m3-max-77800 and m3-max-77801), where AppleGVA serves
them on the vendor driver's route.

The host now lists an x86-64 guest only the AV1 and VP9 decoders, which
AppleGVA does not give it, and no encoder, keyed on the guest architecture
the host's config carries. An arm64 guest is listed every decoder and
encoder, as before. For the x86-64 guest, H.264, HEVC, their encodes and
HEIC's tiles go back to AppleGVA, and a host that decodes neither AV1 nor
VP9 offers no VT_MESSAGES.
2026-12-02 02:46:27 -08:00
Anees Iqbal dfbbebc2d2 📦 Rebuild both sets for the batch's guest changes
Both guest sets rebuilt on the M3 (Xcode 27.2, make -C guest prebuilt and
prebuilt-arm64e, potluck job m3-max-77758, which also ran make -C guest test
and prebuilt-check, both passing) from the base's guest changes, whose
replays left the contributors' binaries out: PR 204's VideoToolbox service
in the x86-64 kext, PR 180's cursor rectangle at HiDPI, and our own
"AMD - " name prefix left off a host name that begins with AMD; and from
this branch's comment changes to those sources. What an x86-64 guest gets
from them: the VideoToolbox service on macOS 14 and later, the cursor's
crossings in WindowServer's virtual space, and the Metal name as the host
names an AMD GPU. Graft and the option ROM are unchanged.
2026-12-02 02:46:26 -08:00
Anees Iqbal f1d990e522 🐛 Fit a Windows window's resize without moving the edge not dragged
PR 172 fits a window the person resized on Windows to the next size the
guest is offered whole, with SDL_SetWindowSize, which keeps the top-left
corner: a drag of the left or top edge then moved the right or bottom edge
the person had not touched. It also narrowed a window Windows had snapped
to half or a quarter of the screen, and laid the window out and resized its
swapchain at the unfitted size before the fitted one.

What changes for the person at a Windows host: the edge they dragged gives
up the difference, so after a drag of the left or top edge the right or
bottom edge stays where it was (the window keeps its last place and size,
and a move that changes the size is an edge's, units::fitted_position); a
window Windows arranged (snapped to a side or a corner, or stretched to the
screen's height) keeps its size, as a maximized one does, told by user32's
IsWindowArranged, looked up at run time so a user32 without it still starts
the process (windows-sys's LibraryLoader feature; Cargo.lock is unchanged);
and the window is laid out once, at the fitted size. The module doc's
sentence that SDL's answer of a window's screen is unused is now scoped to
Wayland, as the fit uses it on Windows. features.md's entry says so, with
the new test and the manual drag and snap checks.
2026-12-02 02:46:26 -08:00
Anees Iqbal 0b9634a98d 📝 Source the cursor's reading of a framebuffer's second rectangle
PR 180 reads the second rectangle getBoundingRect answers as the display's
place in WindowServer's space, and said so with no source; it also dropped
the measured fact the pointer header carried. The comment now cites where
it is read from: Apple's published IOGraphics (530.14 to 600) keeps two
rectangles, the physical then the virtual, and getBoundingRect answers a
pointer to the first; IOHIDFamily registers the one past it with IOHIDSystem
as the display's desktop rectangle, where the cursor is placed. Every
published release keeps both, so reading the second never reads past them.
The pointer header again says what the code does, with ptrcross's 1x
measurement. Comments only; the sets are rebuilt in a later commit.
2026-12-02 02:46:16 -08:00
Anees Iqbal b924a85095 📝 Say the VideoToolbox service is the x86-64 kext's too
PR 204 put the VideoToolbox service in both kexts, but its headers still
called it the arm64e kext's, and the release gate's comment named only
arm64 releases. They now say the service is both kexts', that x86-64 macOS
26's VideoToolbox looks for it as arm64's does, and that the x86-64 kext,
which loads from macOS 11, publishes none on 11 to 13. Comments only; the
sets are rebuilt in a later commit.
2026-12-02 02:46:16 -08:00
Anees Iqbal 539e3630f2 📝 Record two traps of a window that never shows [ci skip]
A GPU's Vulkan driver can present to a session's X server and not to its
Wayland compositor, and a Wayland window never presented to never appears:
a user's NVIDIA laptop GPU under KWin showed only a task bar entry while the
start said its window was open. The lab's RTX 3090 presents to both, so the
lab could not make that state.

A window proof through X11 on a locked Plasma session cannot pass: KWin
holds every X11 window there unmapped, and SDL's X11 window waits for its
MapNotify inside SDL_ShowWindow, so the window's thread stops until the
desktop is unlocked. The next lane reading such a run should look at the
lock before the code.
2026-12-02 02:33:01 -08:00
Anees Iqbal ee4f6a3732 🐛 Say a VM's window is open only once it shows
A start said "its window is open" as soon as QEMU answered QMP, from the
VM's settings alone. A user whose GPU presented to X11 and not to Wayland
read it while no window ever appeared, its task bar entry alone showing.

Once QMP answers, a start whose VM shows its screen in reims-vgpu's own
window now waits, up to 20 s while QEMU runs, for the library's line in
QEMU's log saying whether the window shows: its first frame presented, or
why none shows (docs/api.md, "The window's lines"). The interface's line
says the window is open only after the first; otherwise that the VM runs
without a window, with the library's reason (for that user: this GPU cannot
show a window on this desktop, as it presents to neither its Wayland
compositor nor its X server), or that the window has not shown yet, each
with the key that shows the screen in the terminal. The command line's
start says the same after the pid, with `reims-ctl view`.
2026-12-02 02:33:01 -08:00
Anees Iqbal 09f166332e 🐛 Open the window through a window system its GPU presents to
A laptop's NVIDIA GPU beside the Intel GPU KWin composites on presented to
X11 and not to Wayland (a user's report: its Wayland surface was not
presented to, its XCB and Xlib surfaces were). SDL opened the window through
Wayland, the swapchain was refused, and the window never appeared: Wayland
maps a window only once a frame is presented to it, so its task bar entry
alone showed.

Before SDL's video starts, the GPU of the first window's sink is now asked,
with no window, whether it presents to the session's Wayland compositor,
and where it does not, to its X server: Vulkan's per-platform
presentation-support questions, over connections the window crate makes and
closes. The windows open through Wayland where it presents to the
compositor, else through X11 (XWayland under a Wayland compositor) where it
presents to the X server, and where it presents to neither, no window opens
and the guest runs headless. A named Wayland also holds where the
compositor has no fifo-v1 and SDL would take XWayland on its own.

Each window also tells QEMU's stderr once whether it shows: "reims-vgpu:
window shown: display N" at its first frame presented, or "reims-vgpu: no
window: <why>" where it stays empty, or where no window opens because the
GPU presents to neither window system. reims-ctl reads them to say whether
a VM's window is open.

The sink is attached before the host's screens are asked for, so the first
window's attach starts the UI thread with its GPU.
2026-12-02 02:33:01 -08:00
Anees Iqbal 700bd8bc36 ✅ Test the bytes a buffer-texture copy reaches
buffer_image_ranges says which bytes of a buffer a copy to or from a texture
reaches, and a blit syncs only those of a copy of host pages. Test its cases:
a 1D copy of height 0 is one row; a 3D copy reaches each row of each image
without the padding between rows and images; a compressed copy reaches whole
blocks at a level's edge; Depth16Unorm, Depth32Float and Stencil8 reach their
texel's bytes, Depth32Float_Stencil8 its depth's or its stencil's with the
option, and with no option names no aspect, so the copy is synced whole.
2026-12-02 02:32:58 -08:00
Anees Iqbal c883677f05 ✅ Count a 4 KiB blit's sync chunks without timing them
The test printed copy-in and merge-back timings to stderr from a 64 MiB copy,
192 MiB of test memory. What it holds is the number of 4 KiB chunks a whole
sync and a 4 KiB blit's ranged sync go through, which a 256 KiB copy shows as
well: keep that, drop the timings.
2026-12-02 02:32:58 -08:00
Anees Iqbal 42aa5dcd0a 📝 Say which bytes a copy's syncs go through [ci skip]
A blit syncs only the byte ranges of a copy it reads or writes, rounded out to
4 KiB chunks, up to MAX_RANGES (16) ranges a copy and command buffer, and every
other use syncs the whole copy. The module's docs now say so, with each case
that syncs the whole copy and why: a shader's binding or useResource:, whose
shader may reach any byte, an index, indirect or tessellation factor buffer, a
texture, heap or attachment over the copy, a synchronize, a combined depth and
stencil copy with no option, a 17th range, and an escaped copy. CopyUse's
fields, MAX_RANGES and Ranges get their docs back, and the texture blit test
its doc.
2026-12-02 02:32:58 -08:00
Anees Iqbal 343886f923 🐛 Copy a Managed buffer's named range into its copy as it is named
On a GPU with memory of its own, rt keeps a device copy of a Managed buffer
and fills it from the buffer's block, with the ranges didModifyRange: named,
at the next commit of any command buffer. Over a copy of host pages the block
is the copy, which only a commit that uses the copy synced: a command buffer
committed after the call that used no object over the copy took the copy's
stale bytes into the device copy, and a later read of the buffer on the GPU
saw them, the CPU's write lost. A blit that used any range of such a buffer
synced the whole copy to cover the pending ranges.

The range's chunks are now copied into the copy as it is named, before rt is
told, so whichever commit comes next takes the CPU's bytes, as on Metal. A
blit then syncs only the ranges it reaches for every buffer over a copy: a
Managed one with a device copy, one a heap placed over a copy and one made
over an existing copy's mapping too, whose offset in the block, rt's, is its
offset in the copy, which starts at the block's first byte. copied_alias and
aliases_copy go.

The review of PR 205 asked to try one form first: at each commit, sync the
blit's ranges plus the pending named ranges. Taking the pending ranges at our
commit races a range named between that and rt's capture at its own commit,
and still leaves a commit that uses no object over the copy reading stale
bytes, which this form fixes as well.
2026-12-02 02:32:58 -08:00
Anees Iqbal 945e53b294 ✅ Test that a buffer pinned in a copy syncs it
PR 205 made a buffer the guest pins in the block of an import made as a
copy of host pages hold that copy, where before it held none. What the guest
sees changed with it: a command buffer that uses such a buffer now writes the
CPU's bytes of the pages into the copy at its commit, so a blit out of the
buffer reads them where it read the copy's stale bytes before, and at its
completion writes the GPU's bytes back into the pages, which they never
reached before; over read-only pages the GPU's writes are dropped, as for the
copy's own buffer.

Test both on the GPU, over writable and read-only pages, and say it in the
module's docs, with a comment where the pinned buffer takes the copy.
2026-12-02 02:32:58 -08:00
Anees Iqbal f4003f3ddb 🐎 Batch vertex draws in processes that hold a copied buffer
PR 205 sent a run of vertex draws one command at a time in every encoder
of a process once any copy of host pages was live (copied::any(), process
state), so a guest whose app held one no-copy buffer over a copy lost the
batch everywhere. The batch now notes each buffer's copy as it binds, a
use that can write it, as a bind alone notes it, and takes every run it
can: the recorder (a tool path, off by default) and an encoder ended, with
no pipeline state or with its names gone still send them one at a time.

For the guest: nothing changes but speed; each run's binds and draws are
rt's calls in the order the commands alone make them.

The batch is its own method, batch_draws, which answers None where it
takes none, so draw_batches_sync_a_copied_vertex_buffer_on_vulkan now
asserts that its run was taken as a batch. draw_primitives' doc said it
checked for a pipeline state, which its caller does; it now says so. The
batch tests and their case enum have doc comments, and the module's docs
say what a run of draws is.
2026-12-02 02:32:58 -08:00
Anees Iqbal 9a14d0e8c6 📝 State the pool's host-memory form as GPU memory's one exception [ci skip]
"GPU memory is the runtime's" had no word of PR 178's form, where the
pool's blocks are memfds of the library's own that rt imports as dma-bufs,
under Linux's KVM on arm64 without KVM_CAP_ARM_CACHEABLE_PFNMAP_SUPPORTED.
conventions.md and architecture.md now state it as the rule's one
exception, rt's existing import with no new form, and its known gap: built
and unit-tested here, run only by its contributor, no lab host of its kind,
speed not measured by us. qemu.md's arm64 part says the same, and its
table names the fork's change by what it does rather than by a commit only
in the contributor's fork.
2026-12-02 02:32:58 -08:00
Anees Iqbal 736d0f3327 ✅ Expect the testkit's pool to take the host's word everywhere
a_pool_s_host_memory_blocks_are_the_host_s_ask expected
pool_host_memory 1 refused off Linux. The C API's unit tests run on the
testkit's platform, which gives no block source: its pool's blocks are the
process's own memory, host memory already, and the device takes the 1 on
every OS, so the test failed on the Mac and on Windows. It now expects
RVG_OK on every OS, and says that which blocks the word picks on the rt
platform is reims-vgpu's to test.
2026-12-02 02:32:48 -08:00
Anees Iqbal df67517752 🐛 Refuse a pool of host memory at the start where the GPU refuses it
PR 178's pool blocks of host memory were found refused only at the guest's
first take, logged once by a flag of its own and counted nowhere, and the
device's start said nothing of which form its pool's blocks took.

For the host: where pool_host_memory is 1 and the device has a pool, its
start imports one 64 KiB block of host memory and gives it back. Where the
GPU refuses it (NVIDIA's driver, by rt's rule for dma-bufs, or a Linux host
without udmabuf), rvg_graphics_device_create answers RVG_ERR_HOST_RESOURCES
with one warning, and never maps the GPU's own memory, which that
hypervisor refuses. The pool's start line now ends with its blocks' form
("its blocks are the GPU's own memory", or host memory the GPU imports, or
the process's own memory), so a log shows which form ran. A take refused
later is counted (pool-host-memory-refused), the first of each cause logged
by the logger's kind. The field's doc in the header states it as the host's
fact, found by asking the hypervisor alone; its name stays, as QEMU's fork
sets it by that name. A take past one dma-buf's bytes (udmabuf's
size_limit_mb, 64 MiB stock) needs rt's dma-buf granule, now said, and
tested with a take of 64 MiB and 64 KiB: several dma-bufs at the stock
limit, one where the host raised it.

Nothing changes where pool_host_memory is 0, every host but QEMU under
Linux's KVM on arm64: the_pool_s_blocks_are_the_gpu_s_memory_unless_the_
host_s_hypervisor_maps_none holds the default. The rt tests print and
return where the GPU imports no host memory, where the unwrap panicked.
docs/api.md's INVALID_ARGUMENT row names the 1 on macOS and Windows, which
make no such blocks, and its HOST_RESOURCES row the GPU's refusal.
platform/rt.rs keeps its OS cfgs to two whole items.
2026-12-02 02:32:48 -08:00
Anees Iqbal 6ed6547738 🐛 Read Linux hosts' memory below 4 GiB, down to 64 KiB
PR 191 gave Windows its own zero region end, and left Linux with macOS's:
4 GiB, arm64 macOS's __PAGEZERO. On a Linux host a mapping may lie
anywhere above vm.mmap_min_addr, 64 KiB on stock x86-64 distributions, so
an upload or a buffer's bytes at a host address below 4 GiB died there as
a near-NULL read, as Windows' did.

For the host: on Linux, a texture upload or a buffer made with bytes reads
host memory from 64 KiB up, where it died below 4 GiB. macOS keeps 4 GiB,
Windows 64 KiB. The constant's docs now say each host's fact, and Linux
gets copies_bytes_from_below_four_gib too: a page the test maps below
4 GiB, at 64 KiB where the host lets it, is read.
2026-12-02 02:32:48 -08:00
Anees Iqbal 4f9c03f6bf 🐛 Find a VM's GPU driver again at each start
A user's VM on Windows named its GPU, an Intel one, by its Vulkan driver's
manifest alone, by an absolute path into the DriverStore, whose directory
name carries a hash. An update of the GPU's driver put the manifest in a new
directory and removed the old one, and from then on every start ended with
"vkCreateInstance failed: Unable to find a Vulkan driver": the path was
checked when the settings were made and saved, never at a start, and QEMU's
loader was limited to a file that was gone. Settings get such a path from an
older reims-ctl's create, a pick by manifest, --gpu FILE.json, or a copy of
another VM's settings. Migrations 5 and 6 match such a GPU by its manifest's
whole path, and only once, at an update; they never saw this case.

A start now, before QEMU runs, asks the host's manifests again, as
`reims-ctl gpus` does (the registry on Windows, the loader's directories on
Linux), for a VM whose GPU is named by its manifest alone, and finds the GPU
of its stored name and device ID through a manifest of the stored one's file
name (gpu::refind). Where the stored manifest is gone or offers the GPU no
more and another does, the settings name that one, saved, and the start says
so in one line. Where none does, the start ends with one message that names
the GPU, says its driver is no longer installed, and gives the commands that
pick another; where the settings hold only a path the user gave and it is
gone, the message names the path. The same on every host; no setting.

For the user: such a VM starts after a driver update, saying where its driver
went, and one whose GPU is gone says so instead of the loader's error.
a_start_finds_its_gpus_moved_driver_and_saves_it (red without the step: QEMU
got the old path), a_start_whose_gpu_has_no_driver_now_says_so and
a_vm_finds_its_gpus_driver_again hold it.
2026-12-02 02:16:38 -08:00
Anees Iqbal 526bdf6633 ✅ Run reims-ctl's checks with one make target
Does what PR 130 asked for: one command for the checks of reims-ctl, whose
workspace cargo xtask check does not reach. PR 130 routed it through the
library's xtask, which builds in the library's workspace and so fetches
metal2vulkan, that reims-ctl's workspace is kept apart from, and it ran
neither reims-restore's workspace nor the Windows clippy, the one check on
the Mac or Linux that sees a break of their Windows build (docs/lessons.md).

`make check-ctl` runs, by each workspace's own manifest, in crates/reims-ctl
and in crates/reims-restore (a workspace of its own, with reims-apfs):
rustfmt, clippy, clippy for x86_64-pc-windows-gnullvm with MinGW's gcc and ar
for ring's C, and the tests, clippy with -D warnings and each with
--workspace; the cheapest first, stopping at the first failure. Where
x86_64-w64-mingw32-gcc or -ar is not on the PATH it says so and fails before
any step, never skipping the Windows clippy; on Windows itself the host's
clippy is that check, and it says so. The Makefile's header,
docs/development.md and AGENTS.md's reims-ctl row (now naming reims-restore
too) name the target, and the lesson on reims-ctl's Windows build says what
it catches.
2026-12-02 02:16:38 -08:00
Anees Iqbal 83aa17192d 🎨 Mark reims-restore's sparse files through windows-sys
PR 202 wrote its own extern block for kernel32's DeviceIoControl,
GetCompressedFileSizeW and GetLastError, with FSCTL_SET_SPARSE and
INVALID_FILE_SIZE as literals. windows-sys, which reims-restore already takes,
has each of them: its Win32_System_IO and Win32_System_Ioctl features are on
now, as reims-ctl's copy/windows.rs has them for the same FSCTL_SET_SPARSE,
and neither lock changes. GetCompressedFileSizeW's failure is told from a size
by the last error, read through std as everywhere else.

sys's allocated, whose one caller now passes the path too, folds into
allocated_at on both OSes, and sys.rs's doc names sparse files among what the
OSes differ in. Nothing changes for the user: the disk images on NTFS are as
sparse as PR 202 made them.
2026-12-02 02:16:38 -08:00
Anees Iqbal 643f330e37 📝 Say what usb-redir is in the Windows QEMU build for [ci skip]
PR 200 builds QEMU on Windows with its usb-redir device, from MSYS2's
usbredir, and docs/qemu.md said only what the device is. It now says why it
is there: so that a program on the host speaking the usbredir protocol can
give a VM a USB device of the host's on Windows, where reims-ctl passes none
through (its USB passthrough is for VMs on Linux hosts); that reims-ctl
attaches nothing through it yet, no VM it starts having the device; and that
the install stops where the QEMU it staged lists no usb-redir. install-ctl.sh's
comments on the Windows configure line and on its MSYS2 packages say the
same. Nothing changes for the user.
2026-12-02 02:16:38 -08:00
Anees Iqbal c2268ad9a0 📝 Say that arm64 VMs run emulated on Windows, and who ran one
PR 203 lets an x86-64 Windows PC run arm64 VMs, under TCG as on x86-64
Linux, and left README.md, docs/qemu.md, host.rs and install-ctl.sh saying
Windows runs none. They now say it runs them emulated, much slower than an
arm64 host, and that the one run so far is the PR's contributor's report:
macOS 27.2.1 (26B131) restored, finished and booted to its desktop on Windows
11, on an Intel Core i7-12700H with an RTX 3060 Laptop GPU. The lab has run
none there. README's Windows install time is marked as measured before the
install also built QEMU for arm64 VMs and reims-restore; docs/qemu.md's
Windows install lists both QEMU binaries and reims-restore; the vmapple RAM
backend on Windows gets q35's comments; and install-ctl.sh's refusal on
other hosts names Windows among the arm64 VMs' hosts.

install-ctl.sh now lists each host's QEMU targets in QEMU_TARGETS, one entry
per target, and derives the binaries and --target-list from it, so that the
arm64 VMs' aarch64-softmmu build, like the reims-restore step, can be built
apart from the x86-64 one: the configure line and binaries each host gets are
unchanged (compared on all four platforms).
2026-12-02 02:16:38 -08:00
Anees Iqbal 96d3974d21 🔥 Take REIMS_CTL_QEMU as the binary it names again
PR 203 had reims-ctl read REIMS_CTL_QEMU, a developer's override of the QEMU
binary, as a directory to look in or as the other architecture's binary to
find a sibling of, on every host. That changes the override for everyone and
has nothing to do with arm64 VMs on Windows, so it goes with its test: the
variable names the one QEMU binary reims-ctl runs, as before PR 203.
2026-12-02 02:16:38 -08:00
Anees Iqbal becf7fdfb7 🐛 Build reims-ctl's tests for Windows again after arm64 there
PR 203 has a reims-ctl for Windows carry the arm64 guest's set and Ambrosia's
module, and left two things that break its Windows build. Its #[cfg(windows)]
test a_reims_ctl_for_windows_carries_no_arm64_guest asserted that it carries
neither, and fails there now. And doctor's match gained an unguarded
Os::Windows arm under #[cfg(windows)], which made the later `| Os::Windows`
unreachable in a Windows build (unreachable_patterns, an error under clippy's
-D warnings).

the_module_is_built now runs on every host, Windows among them, and a new
the_arm64_set_is_carried asserts the embedded arm64 set is there; on Windows
nothing else read that static, which clippy refused as dead code. Doctor's
Windows arm is split by cfg: Windows' checks in a Windows build, nothing in
another. Nothing changes for the user.
2026-12-02 02:16:38 -08:00
Anees Iqbal 55fd4b876f 🐛 Start EACS's leftover-request count over with the restored disk
PR 197 counts, in eacs-again, the first boots that made the Data volume but
left EACS's request on Preboot. start_again, which puts the restore's disk
back after a first boot whose EACS failed, kept that count, so the boots that
left the request on a disk since replaced still counted against the new one:
finish-eacs could ask for a new restore after fewer than 3 such boots of the
restored disk. start_again now removes eacs-again with the disk it replaces,
and finishing_eacs_after_a_failed_first_boot_starts_the_vm_again holds it.

The texts that promised Setup Assistant at the next start after finish-eacs
now say it can ask for one more first boot first: reims-ctl create's step
left, its help, reims-restore's own help and closing line, README.md and
docs/qemu.md. For the user, create's line now begins "the VM's first boot is
left" in place of "one step is left".
2026-12-02 02:16:38 -08:00
Anees Iqbal 54b82f3b80 🎨 Take a new VM's random MAC from getrandom
PR 193 kept /dev/urandom and gave Windows, which has none, a fallback that
hashes the clock under std's RandomState. The getrandom crate reims-restore
already takes (0.4.3, in reims-ctl's lock through it) reads the OS's random
source on every host, ProcessPrng on Windows, so random_mac reads it directly
and the fallback goes. random_bytes fed only random_mac, a new VM's MAC; PR
193's message said it fed OpenCore's ROMs too, which it never did.

For the user: a new VM's MAC is as random as before on Linux and macOS, and on
Windows comes from the OS's random source in place of the hash.
2026-12-02 02:16:38 -08:00
Anees Iqbal d8eb793cef 🎨 Give a qcow2 disk a fixed L2 cache limit of 32 MiB
PR 193 sized an x86-64 VM's qcow2 L2 cache from the image's header, which
invocation() read from disk: an untested path (its tests named disks that do
not exist), with clippy hits and an assumption of 8-byte L2 entries. QEMU
already takes the smaller of l2-cache-size and what the image's size needs
(block/qcow2.c, read_cache_sizes), so a fixed l2-cache-size=32M gives the same
cache with no read: 16 MiB for a new 128 GiB disk of 64 KiB clusters, where
QEMU's own limit on Windows is 8 MiB (64 GiB of the disk). On Linux 32 MiB is
QEMU's limit already.

For the host: every qcow2 system disk now carries l2-cache-size=32M, whatever
its size, and a raw one none; a_qcow2_disk_has_an_l2_cache_of_up_to_32_mib
holds it on each controller, on Linux and Windows. The comment on the virtio
disk and docs/qemu.md now say what PR 193 gave it: NVMe's discard=unmap and an
iothread of its own, where the docs said it had neither; the one virtio boot
measured ran before both.
2026-12-02 02:16:38 -08:00
Anees Iqbal bdf5ea915f 📝 Record the fork's WHPX, fiber and pool commits from PRs [ci skip]
"What vendor/qemu carries" gains rows for the fork's commits from its PRs 21
and 23 and the lane's fixes on them: the TSC deadline probe on a partition
of its own with the guest's processor (the c3704402 row, which said the vCPU
was made for the question on the guest's partition), WHvResetPartition only
where Windows has it, nested virtualization's refusal survived, fibers that
commit 64 KiB of their stack at first, the MMIO store fast path and its
unit test, and the vCPU entry's and port reads' trims. The pool row names
its commits by subject, as the new rows do, until the fork's commits land
with their final hashes. "An AMD host" says where the probe now asks.
2026-12-02 02:12:45 -08:00
MonchiLin 6b568b338d Enable USB redirection in the Windows QEMU build
(cherry picked from commit 60837a8708cecfcec8423cc29d61fdf6d465a9a6; its Windows configure line and
package list are combined with PR 203's aarch64-softmmu, gnutls and dtc.)
2026-12-02 01:54:25 -08:00
MonchiLin e993fd6048 Merge pull request #200 from MonchiLin/windows-usbredir 2026-12-02 01:54:09 -08:00
Sabtain Ali 25461780ee Merge pull request #130 from sabtain05/sabtain05-improve-vgpu-contributor-checks 2026-12-02 01:48:05 -08:00
vintoware d0547561a0 🐛 Make the Shared pool host memory where KVM maps no cached GPU memory
On an M1 Pro under Fedora Asahi Remix 45, once Honeykrisp met the runtime's
floor, QEMU exited as the guest's driver took the Shared pool: Linux's KVM on
arm64 takes a cacheable VM_PFNMAP mapping as a memory slot only where the CPU
has stage-2 forced write-back and CACHE_DIC, every host mapping of a
Honeykrisp allocation is VM_PFNMAP, and KVM_SET_USER_MEMORY_REGION2 refused
the pool's first piece with EINVAL (#174).

For the host: RvgGraphicsDeviceConfig's sixth version adds pool_host_memory,
0 or 1, any other value refused. A host built before it reads as 0 and keeps
the pool of the GPU's own memory. QEMU sets it under KVM on an arm64 host
whose VM does not answer KVM_CAP_ARM_CACHEABLE_PFNMAP_SUPPORTED (vendor/qemu
c9f8890b). Each of the pool's blocks is then a memfd of the library's
(RegionMemory, as the device's region is), which rt imports as a dma-buf
(rt_platform::import_host_block, the no-copy buffers' dma-buf path) and the
device knows as it knows rt's blocks (pool::HostMemoryBlocks, the platform's
host_memory_block_source); pool_add hands QEMU the memfd's mapping, which KVM
maps cached, as it maps the guest's RAM. Host, guest and GPU then reach one
cached memory. A platform that makes no such blocks (macOS, Windows) refuses
the 1, where its pool's blocks would be the GPU's; the guest's Private blocks
keep the GPU's memory everywhere.

An uncached memory type of the GPU's would also pass KVM's check, and needs no
import, but the guest would reach the pages cached while the host zeroes each
take through an uncached mapping, a pair of views the architecture does not
keep coherent. The imports' cost on this kernel was measured first: a program
that imported 16 and 32 udmabufs of 16 MiB into Honeykrisp, a GPU fill into
each, then freed them and the device left Shmem as it was (7.3.4-401.asahi,
Mesa 26.2.7), where kernel 6.19 had been reported keeping such imports.

Tests: the C API's field (0 and a size before the field the GPU's memory, 2
refused, 1 taken on Linux and refused elsewhere); HostMemoryBlocks on the M1
Pro (Honeykrisp): a Shared block is imported host memory, zeros, at a GPU
address, known from take to release, Private refused. The C harness gives the
field 0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

(cherry picked from commit a8ad00aca33fb895bb4dd5f11cabef677851b32b; vendor/qemu is kept at the
fork's tip here, and moves to the fork's integrated commit, which carries
the fork's PR 19, in a later commit.)
2026-12-02 01:48:00 -08:00
vintoware ff1a270ac4 Merge pull request #178 from vintoware/steelbrain/kvm-pool-host-memory-blocks 2026-12-02 01:47:52 -08:00
Ricardo-Ray e0acb91124 reims-restore: support NTFS sparse disk images and writable sync_all on Windows
(cherry picked from commit e1f3b9e71b)
2026-12-02 01:47:52 -08:00
Ricardo-Ray 2ef1d5eeab Merge pull request #202 from kilbertert/win32-restore-sparse-ntfs 2026-12-02 01:47:52 -08:00
Ricardo-Ray ae2431d3be reims-ctl: enable vmapple-arm64 VMs on Windows x86-64 via TCG
(cherry picked from commit f51fffa500)
2026-12-02 01:47:52 -08:00
Ricardo-Ray 174bf1ace1 Merge pull request #203 from kilbertert/win32-arm64-tcg 2026-12-02 01:47:52 -08:00
Anees Iqbal 9e27647cd2 🐛 Leave "AMD - " off a host GPU name that begins with AMD
The owner's request: an AMD host's x86-64 guest read its GPU as "AMD - AMD
Radeon 780M Graphics (RADV PHOENIX)". The prefix now stays off where the
host's name, once "Intel" and "NVIDIA" are taken out, begins with the word
AMD in any case as a whole word (before the name's end or a byte that is no
ASCII letter or digit). Nothing else is read: no vendor or device id.

What an x86-64 guest sees: MTLDevice.name and the GPU's `model` (System
Information's Chipset Model) are the host's name as it is on such a host,
"AMD Radeon 780M Graphics (RADV PHOENIX)", "AMD Radeon RX 7900 XTX (RADV
NAVI31)". Every other name keeps the prefix as before: "AMD - GeForce RTX
3090", "AMD - Iris(R) Xe Graphics (RPL-P)", and a name with AMD later or
beginning a longer word, "AMD - Radeon (AMD) Graphics", "AMD - AMDGPU X".
vendorName stays "AMD", and apps that look for "AMD" in the name still
find it. arm64 guests are unchanged.

The prebuilt sets are rebuilt in a later commit with the other guest
changes of this batch.
2026-12-02 01:46:41 -08:00
Anees Iqbal 1bcaa0e252 ✅ Pass NVDEC's AV1 tests on a card without AV1 decode
The ignored NVIDIA tests asserted that NVDEC lists AV1 decode, so on a
Turing card (an RTX 2080, whose NVDEC has no AV1) three of them failed and
the leg read red for a card the product handles: the decoder refuses AV1
there as unsupported. They now say on stderr that the card decodes no AV1
and check nothing, and run on any NVIDIA GPU.
2026-12-02 01:46:41 -08:00
porcelain horse 38ecb7956c 🐛 Use virtual display bounds for x86 cursor crossings
IOFramebuffer exposes physical and virtual desktop rectangles. Passing
the physical rectangle to IOHIDSystem misplaced the cursor when a HiDPI
mode changed the desktop geometry without changing the scanout.

Use the virtual rectangle for pointer warps and DISPLAY_BOUNDS. Cover
mixed-scale crossings in both directions and bounds updates on a mode
switch.

Regenerate both guest prebuilt sets with Xcode 27.2 so the shipped
drivers and source records match this change.

(cherry picked from commit 4c6acb5e0421a61bcf247fa4c89368d6727a55c7; its rebuilt prebuilt sets are left
out: both sets are rebuilt on our Mac with the batch's other guest changes.)
2026-12-02 01:46:30 -08:00
porcelain horse f2af322b18 Merge pull request #180 from porcelainhorse/steelbrain/hidpi-cursor-upstream 2026-12-02 01:46:21 -08:00
Hongye Ji 4d73a4bfaf 🆕 Fit a Windows window to the guest's mode after a resize
A window the person resizes offers the guest its pixels rounded down to
a multiple of 16 wide and of 2 high, and draws that mode a guest pixel to
a pixel at its top left. On Windows that left up to 15 columns and a row
of black at the right and bottom after nearly every drag of an edge:
SDL takes no resize increments, where AppKit's keep a macOS window on
the modes' steps.

Once the person lets go, the window now takes the next smaller size
whose pixels the guest is offered whole, so the image fills it. The
person's drag runs in a loop of Windows' own and its size events reach
the UI thread when it is over, so the size is set once, after the drag.
The mode offered is the one the person's size already rounded to, so
the guest sees no second change. A maximized, full-screen or borderless
window keeps the size Windows gave it, and Wayland and X11 are as they
were.

Measured on Windows 11 with an RTX 4090 Laptop GPU and a macOS 26.7.2
guest: before, a window 1645 pixels wide showed a 1632-pixel mode
beside 13 black columns; after, a dragged window's client area and the
guest's mode were both 1712 x 1148.

(cherry picked from commit 92310eacd0)
2026-12-02 01:46:16 -08:00
Hongye Ji 223775b28f Merge pull request #172 from H0yeR404/steelbrain/windows-resize-fits-mode 2026-12-02 01:46:16 -08:00
棠渚听潮 08d14d2595 🐎 Limit copied buffer sync to blit ranges
(cherry picked from commit 346a4aee83)
2026-12-02 01:46:16 -08:00
棠渚听潮 646c30c538 🐎 Encode Vulkan vertex draws in batches
(cherry picked from commit e26f05db2d)
2026-12-02 01:46:16 -08:00
棠渚听潮 7cf2597a7b Merge pull request #205 from reiasu2/pr/vulkan-draw-batch-and-copied-ranges 2026-12-02 01:46:16 -08:00
Rudraksh Chatterjee 6e6323d40f 🆕 Serve VideoToolbox's paravirtual decoders to x86-64 guests
x86-64 macOS 26's VideoToolbox carries the same paravirtual support as arm64's
(VideoToolboxParavirtualizationSupport, which looks for AppleVideoToolboxParavirtualizationDriver),
so the x86-64 kext now publishes the VideoToolbox service the arm64e kext does: it carries
VT_MESSAGES and VT_RING, RgfxVtService is in both kexts' link, and a VT_MESSAGE's VT_STATUS
answers its waiter on both (before, every send of the x86-64 kext answered
kIOReturnUnsupported). The host needs no change: it offers VT_MESSAGES wherever its arm lists a
decoder.

Measured on x86-64 macOS 26.7.1 (iMac20,1) under WHPX, Intel Core Ultra 5 225H, vaon12:
VTIsHardwareDecodeSupported answers true for avc1, hvc1 and av01, and Safari plays YouTube's
1920x1080 AV1 on the host's GPU where it decoded VP9 in software. The features and lifecycle
answers tests follow both kexts; docs/video/devices.md and docs/known-issues.md say what an
x86-64 guest now gets, and what Safari's sandbox asks of it.

(cherry picked from commit 0a3aa3ada2)
2026-12-02 01:46:11 -08:00
Rudraksh Chatterjee ef9d1e1614 Merge pull request #204 from rudrakshchatterjee3-creator/x86-videotoolbox 2026-12-02 01:46:11 -08:00
Gnug ac03e90262 🐛 Ready another first boot when EACS leaves its request
An arm64 VM's first boot runs EACS from the request the restore leaves on
Preboot (<G>/var/db/.com.apple.eacs). On a 27.2.1 (26B131) VM under TCG on an
x86-64 Linux host, mobile_obliterator failed to delete Preboot/<G>/PreLoginData
("Operation not permitted"), stopped clearing that directory and left the
request, yet still made the Data volume and reset. finish-eacs then put the
LocalPolicy back and removed its copies, the next boot ran EACS again and
deleted that LocalPolicy, and the VM stopped at Ambrosia's "can't read the
boot objects" with nothing left to finish it from.

finish_eacs now reads the main container's Preboot for the request. Where a
boot left it, it puts the iBoot system container and the policy nonces back
as before, keeps the copies, counts the boot in eacs-again and asks for one
more first boot; the next finish completes once a boot removes the request,
and after 3 boots that leave it, it asks for a new restore. For the host this
changes what finish-eacs answers after such a boot: an error naming the next
step, where it answered success.

The EACS tests' main container is now a real one, a System volume and a
Preboot holding the request, which the restore's fixture leaves and the EACS
boot's removes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 283139bb83)
2026-12-02 01:46:11 -08:00
Gnug 1687d661cf Merge pull request #197 from G-Nug85/steelbrain/eacs-leftover-cookie 2026-12-02 01:46:11 -08:00
Fourgetu 98c50384e3 vulkan: accept valid low host addresses on Windows
(cherry picked from commit 0b6e89333e)
2026-12-02 01:46:11 -08:00
Fourgetu 951ded5dbd Merge pull request #191 from Fourgetu/windows-vulkan-low-host-addresses 2026-12-02 01:46:11 -08:00
棠渚听潮 346a4aee83 🐎 Limit copied buffer sync to blit ranges 2026-12-02 16:50:34 +08:00
棠渚听潮 e26f05db2d 🐎 Encode Vulkan vertex draws in batches 2026-12-02 16:50:33 +08:00
Rudraksh Chatterjee 0a3aa3ada2 🆕 Serve VideoToolbox's paravirtual decoders to x86-64 guests
x86-64 macOS 26's VideoToolbox carries the same paravirtual support as arm64's
(VideoToolboxParavirtualizationSupport, which looks for AppleVideoToolboxParavirtualizationDriver),
so the x86-64 kext now publishes the VideoToolbox service the arm64e kext does: it carries
VT_MESSAGES and VT_RING, RgfxVtService is in both kexts' link, and a VT_MESSAGE's VT_STATUS
answers its waiter on both (before, every send of the x86-64 kext answered
kIOReturnUnsupported). The host needs no change: it offers VT_MESSAGES wherever its arm lists a
decoder.

Measured on x86-64 macOS 26.7.1 (iMac20,1) under WHPX, Intel Core Ultra 5 225H, vaon12:
VTIsHardwareDecodeSupported answers true for avc1, hvc1 and av01, and Safari plays YouTube's
1920x1080 AV1 on the host's GPU where it decoded VP9 in software. The features and lifecycle
answers tests follow both kexts; docs/video/devices.md and docs/known-issues.md say what an
x86-64 guest now gets, and what Safari's sandbox asks of it.
2026-12-02 13:24:45 +05:30
Ricardo-Ray f51fffa500 reims-ctl: enable vmapple-arm64 VMs on Windows x86-64 via TCG 2026-12-02 15:31:04 +08:00
Ricardo-Ray e1f3b9e71b reims-restore: support NTFS sparse disk images and writable sync_all on Windows 2026-12-02 15:28:36 +08:00
evanlau1798 52f4879747 fix: keep large IOSurfaces in place within metadata bounds 2026-12-02 15:01:49 +08:00
MonchiLin 60837a8708 Enable USB redirection in the Windows QEMU build 2026-12-02 11:30:14 +08:00
Shroap bfea2dc988 feat(window): forward SDL3 text and URL drops to host bridge 2026-12-02 04:00:53 +08:00
Shroap 3fdde46abd feat(window): forward SDL3 file drops with normalized coords to host bridge 2026-12-02 03:56:21 +08:00
GnugandClaude Opus 5.5 283139bb83 🐛 Ready another first boot when EACS leaves its request
An arm64 VM's first boot runs EACS from the request the restore leaves on
Preboot (<G>/var/db/.com.apple.eacs). On a 27.2.1 (26B131) VM under TCG on an
x86-64 Linux host, mobile_obliterator failed to delete Preboot/<G>/PreLoginData
("Operation not permitted"), stopped clearing that directory and left the
request, yet still made the Data volume and reset. finish-eacs then put the
LocalPolicy back and removed its copies, the next boot ran EACS again and
deleted that LocalPolicy, and the VM stopped at Ambrosia's "can't read the
boot objects" with nothing left to finish it from.

finish_eacs now reads the main container's Preboot for the request. Where a
boot left it, it puts the iBoot system container and the policy nonces back
as before, keeps the copies, counts the boot in eacs-again and asks for one
more first boot; the next finish completes once a boot removes the request,
and after 3 boots that leave it, it asks for a new restore. For the host this
changes what finish-eacs answers after such a boot: an error naming the next
step, where it answered success.

The EACS tests' main container is now a real one, a System volume and a
Preboot holding the request, which the restore's fixture leaves and the EACS
boot's removes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 00:42:42 +11:00
千川白浪 db182a49a6 reims-ctl: size qcow2 l2-cache-size from image header (up to 32 MiB)
QEMU caps default qcow2 L2 cache at 8 MiB on non-Linux hosts (covering only 64 GiB at 64 KiB clusters). Read the 32-byte qcow2 header when present and pass l2-cache-size=<N>M (clamped to 32 MiB) when the image needs more than 8 MiB.
2026-11-30 00:04:32 -07:00
千川白浪 aa851e8cf9 reims-ctl: enable discard=unmap and dedicated iothread on VirtIO system disk
Pass guest TRIMs (discard=unmap) on DiskController::Virtio to match the NVMe branch and prevent qcow2 images from growing monotonically, and attach a dedicated iothread (-object iothread,id=io0) so block completions do not contend with QEMU's main event loop.
2026-11-30 00:04:32 -07:00
千川白浪 561907d613 reims-ctl: use RandomState fallback when /dev/urandom is unavailable
On Windows, /dev/urandom is absent and random_bytes() previously fell back to SystemTime nanos XOR (pid << 64), leaving very low entropy in the low bytes used for MAC addresses and OpenCore ROMs. Hash RandomState (OS-seeded via ProcessPrng on Windows) with the timestamp and PID instead, with zero new dependencies.
2026-11-30 00:04:32 -07:00
Fourgetu 0b6e89333e vulkan: accept valid low host addresses on Windows 2026-11-29 22:09:25 -08:00
vintowareandClaude Opus 5.5 a8ad00aca3 🐛 Make the Shared pool host memory where KVM maps no cached GPU memory
On an M1 Pro under Fedora Asahi Remix 45, once Honeykrisp met the runtime's
floor, QEMU exited as the guest's driver took the Shared pool: Linux's KVM on
arm64 takes a cacheable VM_PFNMAP mapping as a memory slot only where the CPU
has stage-2 forced write-back and CACHE_DIC, every host mapping of a
Honeykrisp allocation is VM_PFNMAP, and KVM_SET_USER_MEMORY_REGION2 refused
the pool's first piece with EINVAL (#174).

For the host: RvgGraphicsDeviceConfig's sixth version adds pool_host_memory,
0 or 1, any other value refused. A host built before it reads as 0 and keeps
the pool of the GPU's own memory. QEMU sets it under KVM on an arm64 host
whose VM does not answer KVM_CAP_ARM_CACHEABLE_PFNMAP_SUPPORTED (vendor/qemu
c9f8890b). Each of the pool's blocks is then a memfd of the library's
(RegionMemory, as the device's region is), which rt imports as a dma-buf
(rt_platform::import_host_block, the no-copy buffers' dma-buf path) and the
device knows as it knows rt's blocks (pool::HostMemoryBlocks, the platform's
host_memory_block_source); pool_add hands QEMU the memfd's mapping, which KVM
maps cached, as it maps the guest's RAM. Host, guest and GPU then reach one
cached memory. A platform that makes no such blocks (macOS, Windows) refuses
the 1, where its pool's blocks would be the GPU's; the guest's Private blocks
keep the GPU's memory everywhere.

An uncached memory type of the GPU's would also pass KVM's check, and needs no
import, but the guest would reach the pages cached while the host zeroes each
take through an uncached mapping, a pair of views the architecture does not
keep coherent. The imports' cost on this kernel was measured first: a program
that imported 16 and 32 udmabufs of 16 MiB into Honeykrisp, a GPU fill into
each, then freed them and the device left Shmem as it was (7.3.4-401.asahi,
Mesa 26.2.7), where kernel 6.19 had been reported keeping such imports.

Tests: the C API's field (0 and a size before the field the GPU's memory, 2
refused, 1 taken on Linux and refused elsewhere); HostMemoryBlocks on the M1
Pro (Honeykrisp): a Shared block is imported host memory, zeros, at a GPU
address, known from take to release, Private refused. The C harness gives the
field 0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 17:47:13 +00:00
porcelain horse 4c6acb5e04 🐛 Use virtual display bounds for x86 cursor crossings
IOFramebuffer exposes physical and virtual desktop rectangles. Passing
the physical rectangle to IOHIDSystem misplaced the cursor when a HiDPI
mode changed the desktop geometry without changing the scanout.

Use the virtual rectangle for pointer warps and DISPLAY_BOUNDS. Cover
mixed-scale crossings in both directions and bounds updates on a mode
switch.

Regenerate both guest prebuilt sets with Xcode 27.2 so the shipped
drivers and source records match this change.
2026-11-25 02:18:59 +03:00
Hongye Ji 92310eacd0 🆕 Fit a Windows window to the guest's mode after a resize
A window the person resizes offers the guest its pixels rounded down to
a multiple of 16 wide and of 2 high, and draws that mode a guest pixel to
a pixel at its top left. On Windows that left up to 15 columns and a row
of black at the right and bottom after nearly every drag of an edge:
SDL takes no resize increments, where AppKit's keep a macOS window on
the modes' steps.

Once the person lets go, the window now takes the next smaller size
whose pixels the guest is offered whole, so the image fills it. The
person's drag runs in a loop of Windows' own and its size events reach
the UI thread when it is over, so the size is set once, after the drag.
The mode offered is the one the person's size already rounded to, so
the guest sees no second change. A maximized, full-screen or borderless
window keeps the size Windows gave it, and Wayland and X11 are as they
were.

Measured on Windows 11 with an RTX 4090 Laptop GPU and a macOS 26.7.2
guest: before, a window 1645 pixels wide showed a 1632-pixel mode
beside 13 black columns; after, a dragged window's client area and the
guest's mode were both 1712 x 1148.
2026-11-24 22:50:13 +11:00
charlysound 1ba041345d 🆕 Add opt-in seamless input to Linux windows
Let the host pointer enter and leave the guest image without a release
shortcut when the seamless input switch is on. Forward the focus click
in that mode and keep button releases at the guest edge.

Keep click-to-capture as the default, including its handling of the
focus click. Cover the focus event ordering and drags outside the
image in the SDL input tests.
2026-11-20 22:27:27 +01:00
Sabtain Ali 129296db67 ✅ Add a check command for reims-ctl
reims-ctl lives in a separate workspace, so cargo xtask check cannot cover it. Provide an explicit check-ctl command and Makefile target that run the repository's required formatting, clippy, and test checks, and document the entry point for contributors.
2026-10-24 10:17:22 +05:00
628 changed files with 108627 additions and 11602 deletions

No files matched your search

+28 -1
View File
@@ -57,6 +57,14 @@ threads-required = "num-test-threads"
[test-groups]
vulkan-devices = { max-threads = 3 }
# The NVIDIA legs end a test that runs past five minutes, so a stuck test fails the leg by name
# instead of holding it to the job's limit. On an RTX 3090 (driver 620.70.06, 2026-12-02), seven
# GPU tests in flight stalled together after 2,033 had passed, and the leg was killed at its
# 10-minute limit with six processes that would not die (m3-max-80466). A test that stays inside the
# driver may still not die: the timeout bounds the leg, not the driver.
[profile.nvidia]
slow-timeout = { period = "60s", terminate-after = 5 }
# The measurements that run alone (above, the same list) stay out of the group, so that what they
# wait for is every test in flight rather than the group's three.
[[profile.nvidia.overrides]]
@@ -76,11 +84,30 @@ filter = '''
'''
test-group = "@global"
# The tests that make an rt device: the Vulkan crate's but core's, reims-vgpu's named on_vulkan or
# on_rt_, and the C API's. Each of them failed, and no other test did, in a run on Linux with no
# Vulkan driver (homelab-um870, 2026-12-03, potluck job m3-max-85816).
[[profile.nvidia.overrides]]
platform = 'cfg(target_os = "linux")'
filter = '''
(package(reims-vgpu-vulkan) & !(binary_id(reims-vgpu-vulkan) & test(/^core::/)))
| (package(reims-vgpu) & test(/on_vulkan/))
| (package(reims-vgpu) & (test(/on_vulkan/) | test(/(^|::)on_rt_/)))
| package(reims-vgpu-c)
'''
test-group = "vulkan-devices"
# GitHub CI's profile (.github/workflows/ci.yml, docs/development.md "CI"), whose runners have no
# GPU: every test but those that make an rt device. They are the tests the nvidia profile's
# `vulkan-devices` group holds (above), and reims-vgpu's tests named `on_rt_`, which make one too.
# Measured on Linux with no Vulkan driver (homelab-um870, 2026-12-03, at 5cb932953e): 218 of the
# 3,439 tests that are not ignored failed, each of them one of these. CI runs these with the
# profile's filter turned over (`--profile ci --ignore-default-filter -E 'not default()'`) on
# Mesa's lavapipe, in a job of its own.
[profile.ci]
default-filter = '''
not (
(package(reims-vgpu-vulkan) & !(binary_id(reims-vgpu-vulkan) & test(/^core::/)))
| (package(reims-vgpu) & (test(/on_vulkan/) | test(/(^|::)on_rt_/)))
| package(reims-vgpu-c)
)
'''
+16
View File
@@ -0,0 +1,16 @@
# The device tests that fail on lavapipe in CI's lavapipe job (.github/workflows/ci.yml), each
# under its reason: nextest's binary id and the test's full name, as nextest's FAIL lines print them,
# one test a line. The job runs every other device test, which must pass, then each test here alone,
# which must fail (.github/lavapipe-tests.sh): a test here that passes, or any other that fails,
# fails the job. A test that comes to pass on lavapipe leaves the list in the commit that makes it
# pass.
# A known limit of CPU devices: their device addresses are the host process's own, and lavapipe put
# a buffer of the host's in the process's mmap area, inside the contexts' range [2^46, 2^47), in each
# of three runs (docs/graphics-kext/design.md, "Contexts").
reims-vgpu graphics::decode::cmdbuf::tests::on_vulkan_the_host_s_own_ranges_lie_outside_every_unit
# The pass and the table one LSB apart in one byte of BGR10A2Unorm (format 94), [255, 255, 1, 255]
# against [255, 255, 0, 255], the same in each of three runs: likely lavapipe's rounding, not
# confirmed.
reims-vgpu graphics::sink::tests::on_vulkan_the_table_draws_what_the_pass_draws
+54
View File
@@ -0,0 +1,54 @@
#!/usr/bin/env bash
# The lavapipe job's device tests (.github/workflows/ci.yml), run in metal2vulkan's lavapipe image:
# the tests nextest's `ci` profile leaves out, every one but the expected failures the list names,
# which must pass, then each expected failure alone, which must fail.
#
# lavapipe-tests.sh ARCHIVE WORKSPACE LIST
#
# ARCHIVE is `cargo nextest archive`'s file, WORKSPACE the checkout it was built in, and LIST
# .github/lavapipe-expected-failures: lines of nextest's binary id and a test's full name, with `#`
# comments and blank lines. It fails if a test outside the list fails, if a test in the list passes
# or is not one device test, or if a line of the list is not a binary id and a test name.
set -uo pipefail
archive=$1 workspace=$2 list=$3
expected=()
while IFS= read -r line; do
case $line in '' | '#'*) continue ;; esac
read -r binary test rest <<< "$line"
if [ -z "${test:-}" ] || [ -n "${rest:-}" ]; then
echo "::error::$list: not a binary id and a test name: $line"
exit 1
fi
expected+=("binary_id(=$binary) & test(=$test)")
done < "$list"
run() {
cargo-nextest nextest run --archive-file "$archive" --workspace-remap "$workspace" \
--profile ci --ignore-default-filter --no-tests=fail "$@"
}
ulimit -c 0
status=0
others='not default()'
if [ ${#expected[@]} -gt 0 ]; then
any=$(printf ' | (%s)' "${expected[@]}")
others="not default() & not (${any# | })"
fi
run --no-fail-fast -E "$others" || status=1
# nextest exits 100 when a test failed and 4 when the filter took no test (--no-tests=fail).
for e in "${expected[@]}"; do
run -E "not default() & ($e)"
case $? in
100) echo "failed, as the list expects: $e" ;;
0)
echo "::error::passed, so it leaves the list: $e"
status=1
;;
*)
echo "::error::did not run to a test's failure: $e"
status=1
;;
esac
done
exit $status
+518
View File
@@ -0,0 +1,518 @@
# CI on GitHub's runners: the checks that need no GPU and no guest, on Linux, macOS and Windows
# (docs/development.md, "CI"). The lab's checks (AGENTS.md, "Checking a change") stay the gate for
# a merge; this is a check beside them.
#
# The runners have no GPU, so the tests run under nextest's `ci` profile (.config/nextest.toml):
# every test but those that make an rt device, which run in the lavapipe job, on Mesa's lavapipe,
# and nowhere else here. The tests `#[ignore]` keeps for a hardware host stay ignored.
#
# What a job reaches: GitHub (this repository, vendor/qemu's fork at its gitlink, metal2vulkan at
# the commit Cargo.toml pins, the actions below by commit, cargo-nextest's release, Homebrew's
# bottles), crates.io, Rust's toolchain server for the toolchain rust-toolchain.toml pins, and the
# distributions' packages each job names (Ubuntu's, MSYS2's, and in the lavapipe job, Arch Linux's
# of the date metal2vulkan's image pins). QEMU's build takes its three meson subprojects from
# QEMU's mirrors on GitHub, at the commits their wraps name.
name: CI
on:
push:
branches: [development, master]
pull_request:
workflow_dispatch:
permissions:
contents: read
# One run per ref at a time. A new run of a pull request (refs/pull/N/merge) or of any branch but
# development and master cancels that ref's run in progress; on those two it waits for the run in
# progress to end instead (GitHub keeps one waiting run a ref, the newest).
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: ${{ github.ref != 'refs/heads/development' && github.ref != 'refs/heads/master' }}
env:
# The tests a runner without a GPU runs, for `cargo xtask check` and every nextest run below.
NEXTEST_PROFILE: ci
# The features `cargo xtask check` tests with (xtask/src/main.rs, TESTED_FEATURES).
TESTED_FEATURES: reims-vgpu-vulkan/testkit,reims-vgpu/testkit,reims-vgpu/vulkan,reims-vgpu-c/vulkan
# The cargo-nextest the lab runs.
NEXTEST_VERSION: 0.9.151
# The cbindgen the committed header is made with (xtask/src/header.rs, CBINDGEN_VERSION).
CBINDGEN_VERSION: 0.29.4
# Ubuntu's packages a build of the library on Linux needs beyond the image's: SDL3's video, which
# the window crate builds from its source (CMake, and the X11, Wayland, xkbcommon and EGL
# headers), as scripts/install-ctl.sh installs them.
LIBRARY_APT: >-
cmake clang libx11-dev libxext-dev libxrandr-dev libxcursor-dev libxi-dev libxfixes-dev
libxss-dev libxtst-dev libxkbcommon-dev libwayland-dev libwayland-bin libdecor-0-dev libegl-dev
libgl-dev libdrm-dev libgbm-dev libdbus-1-dev libudev-dev
# The cache's bound: rust-cache saves on development alone, and a job whose target directories
# hold more than this saves cargo's home alone (the last step of each job).
CACHE_TARGET_MAX_GIB: 4
jobs:
linux-check:
name: Linux, cargo xtask check
runs-on: ubuntu-26.04
timeout-minutes: 120
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Install packages
run: |
read -ra packages <<< "$LIBRARY_APT"
sudo apt-get update
sudo apt-get install -y --no-install-recommends "${packages[@]}"
- name: Install Rust
run: rustup toolchain install
- uses: taiki-e/install-action@43dc658ea8a4fa76c68a84c0acd17c34169b6e2a # v2.90.12
with:
tool: cargo-nextest@${{ env.NEXTEST_VERSION }}
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
with:
save-if: ${{ github.ref == 'refs/heads/development' }}
- name: Install cbindgen
run: cargo install --locked cbindgen --version "$CBINDGEN_VERSION"
# The lab's check: the lints, the records of the prebuilt ROM and kext sets, rustfmt, clippy
# (Linux and x86_64-pc-windows-gnullvm), the hooks, the tests and the doc-tests. No core
# dumps: the death tests crash on purpose (AGENTS.md, "The video crates' checks").
- name: cargo xtask check
run: |
ulimit -c 0
cargo xtask check
- name: Bound the cache
if: ${{ !cancelled() }}
run: &bound |
kib=$({ du -sk target crates/*/target 2>/dev/null || true; } | awk '{s += $1} END {print s + 0}')
echo "target directories: $((kib / 1024)) MiB, bound ${CACHE_TARGET_MAX_GIB} GiB"
if [ "$GITHUB_REF" = refs/heads/development ] && [ "$kib" -gt $((CACHE_TARGET_MAX_GIB * 1024 * 1024)) ]; then
rm -rf target crates/*/target
echo "over the bound: the cache saves cargo's home alone"
fi
linux-ctl:
name: Linux, make check-ctl
runs-on: ubuntu-26.04
timeout-minutes: 120
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
# MinGW's gcc and ar, for the C ring's build script compiles in clippy for
# x86_64-pc-windows-gnullvm; clang, for the Ambrosia module reims-ctl's build makes.
- name: Install packages
run: |
sudo apt-get update
sudo apt-get install -y --no-install-recommends gcc-mingw-w64-x86-64 binutils-mingw-w64-x86-64 clang
- name: Install Rust
run: rustup toolchain install
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
with:
workspaces: |
crates/reims-ctl -> target
crates/reims-restore -> target
save-if: ${{ github.ref == 'refs/heads/development' }}
# rustfmt, clippy, clippy for x86_64-pc-windows-gnullvm and the tests, in each of reims-ctl's
# two workspaces.
- name: make check-ctl
run: make check-ctl
- name: Bound the cache
if: ${{ !cancelled() }}
run: *bound
linux-doc:
name: Linux, rustdoc
runs-on: ubuntu-26.04
timeout-minutes: 120
env:
RUSTDOCFLAGS: -D warnings
# `cargo xtask check`'s CROSS_CHECK_FEATURES: the tested features, with SDL's sources unbuilt.
DOC_FEATURES: reims-vgpu-vulkan/testkit,reims-vgpu/testkit,reims-vgpu/vulkan,reims-vgpu-c/vulkan,reims-vgpu-window/sdl-no-link
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Install Rust
run: rustup toolchain install
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
with:
save-if: ${{ github.ref == 'refs/heads/development' }}
# The workspace's docs with its private items, warnings denied, for Linux and for Windows.
- name: rustdoc for Linux
run: cargo doc --workspace --no-deps --document-private-items --keep-going --features "$DOC_FEATURES"
- name: rustdoc for x86_64-pc-windows-gnullvm
if: ${{ !cancelled() }}
run: cargo doc --workspace --no-deps --document-private-items --keep-going --target x86_64-pc-windows-gnullvm --features "$DOC_FEATURES"
- name: Bound the cache
if: ${{ !cancelled() }}
run: *bound
linux-qemu:
name: Linux, QEMU and its unit tests
runs-on: ubuntu-26.04
timeout-minutes: 120
env:
# The fork's tests the lab runs for it (forkunit): unit tests under tests/unit, and qtests
# under tests/qtest, which run against this build's qemu-system-x86_64.
FORK_TESTS: >-
unit/test-cutils unit/test-dsound-ring unit/test-audio-rate unit/test-whpx-mmio
unit/test-reims-pointer qtest/virtio-pci-caps-test qtest/usb-hcd-xhci-test
steps:
# vendor/qemu alone, at its gitlink, from the fork's public repository; none of QEMU's own
# submodules.
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
submodules: true
# QEMU's build tools and the libraries it links, as scripts/install-ctl.sh installs them.
- name: Install packages
run: |
read -ra packages <<< "$LIBRARY_APT"
sudo apt-get update
sudo apt-get install -y --no-install-recommends "${packages[@]}" \
build-essential pkg-config python3 python3-venv ninja-build flex bison bzip2 binutils \
libglib2.0-dev libpixman-1-dev libslirp-dev zlib1g-dev libfdt-dev libpipewire-0.3-dev \
libpulse-dev libasound2-dev libusb-1.0-0-dev libspice-server-dev libgnutls28-dev \
libgtk-3-dev
# configure fetches keycodemapdb, berkeley-softfloat-3 and berkeley-testfloat-3, at the
# commits their wraps name, from QEMU's mirrors on GitHub, which hold the same commits.
- name: Fetch QEMU's subprojects from GitHub
run: git config --global url.https://github.com/qemu/.insteadOf https://gitlab.com/qemu-project/
- name: Install Rust
run: rustup toolchain install
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
with:
save-if: ${{ github.ref == 'refs/heads/development' }}
# The library's dist tree, then qemu-system-x86_64 with reims-graphics-pci linked on it.
- name: make qemu
run: make qemu
- name: The fork's unit tests and qtests
run: |
ulimit -c 0
cd build/qemu
targets=()
for t in $FORK_TESTS; do targets+=("tests/$t"); done
ninja "${targets[@]}"
failed=()
for t in $FORK_TESTS; do
echo "::group::$t"
if [ "${t%%/*}" = qtest ]; then
QTEST_QEMU_BINARY=./qemu-system-x86_64 timeout 300 "./tests/$t" --tap -k || failed+=("$t")
else
timeout 300 "./tests/$t" --tap -k || failed+=("$t")
fi
echo "::endgroup::"
done
if [ ${#failed[@]} -gt 0 ]; then
echo "::error::failed: ${failed[*]}"
exit 1
fi
- name: Bound the cache
if: ${{ !cancelled() }}
run: *bound
# The device tests, the ones the `ci` profile leaves out, on Mesa's lavapipe in metal2vulkan's
# lavapipe image at the commit Cargo.toml pins (its scripts/lavapipe-image: Arch Linux's packages
# of one archive date, the bootstrap tarball checked against its sha256). The tests are built on
# the runner and run in the image, with no network. The tests .github/lavapipe-expected-failures
# names, each under its reason, must fail there, and every other must pass
# (.github/lavapipe-tests.sh).
linux-lavapipe:
name: Linux, device tests on lavapipe
runs-on: ubuntu-26.04
timeout-minutes: 150
env:
# What the job adds to metal2vulkan's image (the step after its build).
LAVAPIPE_EXTRAS: gcc git
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Install packages
run: |
read -ra packages <<< "$LIBRARY_APT"
sudo apt-get update
sudo apt-get install -y --no-install-recommends "${packages[@]}"
- name: Install Rust
run: rustup toolchain install
- uses: taiki-e/install-action@43dc658ea8a4fa76c68a84c0acd17c34169b6e2a # v2.90.12
with:
tool: cargo-nextest@${{ env.NEXTEST_VERSION }}
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
with:
save-if: ${{ github.ref == 'refs/heads/development' }}
# metal2vulkan's checkout at the pinned commit, as cargo fetched it.
- name: Find metal2vulkan's lavapipe image
id: image
run: |
manifest=$(cargo metadata --format-version 1 |
python3 -I -c 'import json, sys; print(next(p["manifest_path"] for p in json.load(sys.stdin)["packages"] if p["name"] == "metal2vulkan-runtime"))')
dir=$(dirname "$(dirname "$(dirname "$manifest")")")/scripts/lavapipe-image
[ -f "$dir/lavapipe-image" ] || { echo "::error::no lavapipe image in $dir"; exit 1; }
echo "dir=$dir" >> "$GITHUB_OUTPUT"
pin=$(sha256sum < "$dir/pin" | cut -c1-16)
echo "pin=$pin" >> "$GITHUB_OUTPUT"
echo "key=lavapipe-image-$pin-${LAVAPIPE_EXTRAS// /-}" >> "$GITHUB_OUTPUT"
# The image's downloads, with the packages the step after its build adds.
- name: Restore the image's downloads
id: downloads
uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: ~/.cache/m2v-lavapipe-image
key: ${{ steps.image.outputs.key }}
restore-keys: lavapipe-image-${{ steps.image.outputs.pin }}
- name: Build the image
timeout-minutes: 90
env:
IMAGE: ${{ steps.image.outputs.dir }}
run: bash "$IMAGE/lavapipe-image" ensure
# The C compiler the C API's harness tests run and the git the build stamp's test runs, which
# the image's pin names neither of: installed into the image the build made, from the pin's
# own archive date, through the build's pacman.conf, package cache and databases, and kept
# under the same tag, which the run below uses.
- name: Add cc and git to the image
env:
IMAGE: ${{ steps.image.outputs.dir }}
run: |
read -ra extras <<< "$LAVAPIPE_EXTRAS"
date=$(sed -n 's/^date=//p' "$IMAGE/pin")
cache=$HOME/.cache/m2v-lavapipe-image
image=$(docker images --format '{{.Repository}}:{{.Tag}}' | sed -n '/^m2v-lavapipe:/p')
[ -n "$image" ] && [ "$(wc -l <<< "$image")" = 1 ] || { echo "::error::not one lavapipe image: $image"; exit 1; }
# shellcheck disable=SC2016 # the container's bash expands them
docker run --name ci-lavapipe-extras \
-v "$cache/pkg:/var/cache/pacman/pkg" -v "$cache/sync-$date:/var/lib/pacman/sync" \
-v "$cache/pacman.conf:/etc/pacman.conf:ro" "$image" bash -euc '
owner=$1
shift
pacman -S --noconfirm --needed "$@"
yes | pacman -Sc >/dev/null
chown -R "$owner" /var/cache/pacman/pkg /var/lib/pacman/sync
' bash "$(id -u):$(id -g)" "${extras[@]}"
docker commit ci-lavapipe-extras "$image" >/dev/null
docker rm ci-lavapipe-extras >/dev/null
bash "$IMAGE/lavapipe-image" run -- bash -c 'cc --version | head -1 && git --version'
- name: Save the image's downloads
if: steps.downloads.outputs.cache-hit != 'true' && github.event_name == 'push'
uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: ~/.cache/m2v-lavapipe-image
key: ${{ steps.image.outputs.key }}
- name: Build the tests
run: cargo nextest archive --workspace --features "$TESTED_FEATURES" --archive-file "$RUNNER_TEMP/tests.tar.zst"
- name: Run the device tests on lavapipe
env:
IMAGE: ${{ steps.image.outputs.dir }}
run: |
bash "$IMAGE/lavapipe-image" run --read "$GITHUB_WORKSPACE" \
--read "$RUNNER_TEMP/tests.tar.zst" --env LP_NUM_THREADS=1 -- \
bash "$GITHUB_WORKSPACE/.github/lavapipe-tests.sh" "$RUNNER_TEMP/tests.tar.zst" \
"$GITHUB_WORKSPACE" "$GITHUB_WORKSPACE/.github/lavapipe-expected-failures"
- name: Bound the cache
if: ${{ !cancelled() }}
run: *bound
# `cargo xtask check` in two jobs, its lints and its tests (`--lints`, `--tests`): the whole
# check ran past an hour on the macos-26 runner.
macos-check:
name: macOS, cargo xtask check --lints
runs-on: macos-26
timeout-minutes: 120
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
# The image's Xcode carries its Metal toolchain, which the Vulkan crate's build compiles its
# metallibs with on a Mac; nothing of Apple's is fetched here.
- name: Xcode's Metal compiler
run: xcrun -sdk macosx metal --version
- name: Install Rust
run: rustup toolchain install
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
with:
save-if: ${{ github.ref == 'refs/heads/development' }}
- name: Install cbindgen
run: cargo install --locked cbindgen --version "$CBINDGEN_VERSION"
# The lab's check on a Mac but its tests: also clippy for Linux.
- name: cargo xtask check --lints
run: cargo xtask check --lints
- name: Bound the cache
if: ${{ !cancelled() }}
run: *bound
macos-test:
name: macOS, cargo xtask check --tests
runs-on: macos-26
timeout-minutes: 120
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Xcode's Metal compiler
run: xcrun -sdk macosx metal --version
# The threads a process and a user may have here: the tests start a few thousand at once.
- name: Thread limits
run: |
sysctl kern.num_taskthreads kern.maxprocperuid hw.ncpu hw.memsize
ulimit -u
- name: Install Rust
run: rustup toolchain install
- uses: taiki-e/install-action@43dc658ea8a4fa76c68a84c0acd17c34169b6e2a # v2.90.12
with:
tool: cargo-nextest@${{ env.NEXTEST_VERSION }}
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
with:
save-if: ${{ github.ref == 'refs/heads/development' }}
# The lab's tests on a Mac: also core's tests as x86_64-apple-darwin under Rosetta, which
# the image installs.
- name: cargo xtask check --tests
run: cargo xtask check --tests
- name: Bound the cache
if: ${{ !cancelled() }}
run: *bound
macos-ctl:
name: macOS, make check-ctl
runs-on: macos-26
timeout-minutes: 120
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
# MinGW's gcc and ar, for the C ring's build script compiles in clippy for
# x86_64-pc-windows-gnullvm.
- name: Install mingw-w64
run: brew install mingw-w64
- name: Install Rust
run: rustup toolchain install
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
with:
workspaces: |
crates/reims-ctl -> target
crates/reims-restore -> target
save-if: ${{ github.ref == 'refs/heads/development' }}
- name: make check-ctl
run: make check-ctl
- name: Bound the cache
if: ${{ !cancelled() }}
run: *bound
macos-doc:
name: macOS, rustdoc
runs-on: macos-26
timeout-minutes: 120
env:
RUSTDOCFLAGS: -D warnings
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Install Rust
run: rustup toolchain install
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
with:
save-if: ${{ github.ref == 'refs/heads/development' }}
- name: rustdoc
run: cargo doc --workspace --no-deps --all-features --document-private-items
- name: Bound the cache
if: ${{ !cancelled() }}
run: *bound
# The guest's kexts, loader and Metal bundle: their own tests, with Xcode and its Metal
# compiler, which the image carries. The bundle builds against the macOS 27 SDK (it names its
# Metal types, MTLTensorPlaneType among them), so the job runs on the Xcode 27 image, macOS 27,
# with Xcode 27.2, the lab's. Rebuilding the prebuilt kext sets stays in the lab.
macos-guest:
name: macOS, guest tests
runs-on: xcode-27
timeout-minutes: 120
env:
DEVELOPER_DIR: /Applications/Xcode_27.2.app/Contents/Developer
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Xcode's Metal compiler
run: xcrun -sdk macosx metal --version
- name: make -C guest test
run: make -C guest test
# Windows, in MSYS2's CLANG64 with the pinned nightly's x86_64-pc-windows-gnullvm host
# toolchain, as scripts/install-ctl.sh builds there.
windows:
name: Windows, clippy and tests
runs-on: windows-2025
timeout-minutes: 120
defaults:
run:
shell: msys2 {0}
env:
CC: clang
CXX: clang++
AR: llvm-ar
CC_x86_64_pc_windows_gnullvm: clang
CXX_x86_64_pc_windows_gnullvm: clang++
AR_x86_64_pc_windows_gnullvm: llvm-ar
CMAKE_GENERATOR: Ninja
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: msys2/setup-msys2@3c51bf698df1e37b2261f53cb67797b97761185c # v2.34.0
with:
msystem: CLANG64
path-type: inherit
install: >-
make diffutils mingw-w64-clang-x86_64-clang mingw-w64-clang-x86_64-lld
mingw-w64-clang-x86_64-cmake mingw-w64-clang-x86_64-ninja
- name: Install Rust
run: |
channel=$(sed -n 's/^channel *= *"\([^"]*\)".*/\1/p' rust-toolchain.toml)
echo "RUSTUP_TOOLCHAIN=$channel-x86_64-pc-windows-gnullvm" >> "$GITHUB_ENV"
rustup toolchain install --profile minimal --component clippy,rustfmt "$channel-x86_64-pc-windows-gnullvm"
- uses: taiki-e/install-action@43dc658ea8a4fa76c68a84c0acd17c34169b6e2a # v2.90.12
with:
tool: cargo-nextest@${{ env.NEXTEST_VERSION }}
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
with:
save-if: ${{ github.ref == 'refs/heads/development' }}
# The two clippy runs of `cargo xtask check` on a Windows host.
- name: clippy, every feature
run: cargo clippy --workspace --all-targets --all-features -- -D warnings
- name: clippy, the tested features
if: ${{ !cancelled() }}
run: cargo clippy --workspace --all-targets --no-default-features --features "$TESTED_FEATURES" -- -D warnings
# The library's crates and their tested features, as scripts/internal/windows-tests.sh runs
# them on the lab's Windows host.
- name: Tests
if: ${{ !cancelled() }}
run: |
cargo nextest run --target x86_64-pc-windows-gnullvm --no-fail-fast --features "$TESTED_FEATURES" \
-p reims-vgpu-graphics -p reims-vgpu-vulkan -p reims-vgpu-window -p reims-vgpu -p reims-vgpu-c
- name: Bound the cache
if: ${{ !cancelled() }}
shell: bash
run: *bound
windows-ctl:
name: Windows, make check-ctl
runs-on: windows-2025
timeout-minutes: 120
defaults:
run:
shell: msys2 {0}
env:
CC: clang
CXX: clang++
AR: llvm-ar
CC_x86_64_pc_windows_gnullvm: clang
CXX_x86_64_pc_windows_gnullvm: clang++
AR_x86_64_pc_windows_gnullvm: llvm-ar
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: msys2/setup-msys2@3c51bf698df1e37b2261f53cb67797b97761185c # v2.34.0
with:
msystem: CLANG64
path-type: inherit
install: >-
make diffutils mingw-w64-clang-x86_64-clang mingw-w64-clang-x86_64-lld
- name: Install Rust
run: |
channel=$(sed -n 's/^channel *= *"\([^"]*\)".*/\1/p' rust-toolchain.toml)
echo "RUSTUP_TOOLCHAIN=$channel-x86_64-pc-windows-gnullvm" >> "$GITHUB_ENV"
rustup toolchain install --profile minimal --component clippy,rustfmt "$channel-x86_64-pc-windows-gnullvm"
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
with:
workspaces: |
crates/reims-ctl -> target
crates/reims-restore -> target
save-if: ${{ github.ref == 'refs/heads/development' }}
# rustfmt, clippy (this host's, x86_64-pc-windows-gnullvm) and the tests, in each of
# reims-ctl's two workspaces.
- name: make check-ctl
run: make check-ctl
- name: Bound the cache
if: ${{ !cancelled() }}
shell: bash
run: *bound
+5 -5
View File
@@ -70,8 +70,8 @@ The Makefile's header lists every target. README.md lists the requirements.
| core: the platform traits, the runtime, raises and deaths, the guest's RAM, the testkit | `crates/reims-vgpu-vulkan/src/core.rs` and `core/`, the Vulkan crate's module `core`; the testkit is its `testkit` feature |
| the Vulkan platform's metallibs, which a build off a Mac copies | `crates/reims-vgpu-vulkan/metallibs`, written on a Mac by `cargo xtask metallibs` (README.md, Building) |
| a display's own window, and the register of what it does | `crates/reims-vgpu-window`, its `features.md` and its manual walk on macOS, `scripts/internal/walk_window_macos.sh`; the wiring is `crates/reims-vgpu/src/window.rs` |
| the reims-graphics device's video on the host, on NVDEC or VA-API | `crates/reims-vgpu-video`, in modules: `core` (what the arms share: their runtime, locks, a guest surface's memory and bounded waits), `codec` (the codecs above the hardware), and on Linux `vaapi` and `nvidia` and on Windows `vaapi` (the hardware's); its subcrate `conformance` is the test streams' readers and writers; the arms are reims-vgpu's `crates/reims-vgpu/src/graphics/{nvidia,vaapi,video_choice,video_host}.rs`, on the runtime in `crates/reims-vgpu/src/video/runtime.rs` |
| the video docs | [docs/video](docs/video): `devices.md` is what the device answers and what a decode does, `backends.md` the arms, the crate and the conformance suite (`crates/reims-vgpu-video/tools/h264-check.sh` and `hevc-check.sh`), `core.md`, `vaapi.md` and `nvidia.md` its modules, `bugs.md` what is wrong or put off |
| the reims-graphics device's video on the host, on NVDEC or VA-API, and on a Mac on VideoToolbox | `crates/reims-vgpu-video`, in modules: `core` (what the arms share: their runtime, locks, a guest surface's memory and bounded waits), `codec` (the codecs above the hardware), and on Linux `vaapi` and `nvidia`, on Windows `vaapi` and on macOS `videotoolbox` (the hardware's); its subcrate `conformance` is the test streams' readers and writers; the arms are reims-vgpu's `crates/reims-vgpu/src/graphics/{nvidia,vaapi,videotoolbox,video_choice,video_host}.rs`, on the runtime in `crates/reims-vgpu/src/video/runtime.rs` |
| the video docs | [docs/video](docs/video): `devices.md` is what the device answers and what a decode does, `backends.md` the arms, the crate and the conformance suite (`crates/reims-vgpu-video/tools/h264-check.sh` and `hevc-check.sh`), `core.md`, `vaapi.md` and `nvidia.md` its modules, `hand-overs.md` every point where one API writes a picture and another reads it, with its wait and test, `bugs.md` what is wrong or put off |
| the guest's kexts, loader and Metal bundle | `guest/`, the prebuilt set reims-ctl carries, `guest/prebuilt`, and the arm64e set Ambrosia's config bundle takes, `guest/prebuilt-arm64e` |
| the dist tree QEMU links | `xtask/src/dist.rs` (`cargo xtask dist`) |
| the option ROM reims-ctl gives the device | `firmware/`, and the prebuilt ROM, `firmware/prebuilt/ReimsGraphics.rom`, described in [docs/architecture.md](docs/architecture.md) section 11.4 |
@@ -136,11 +136,11 @@ passes run again alone.
| the library (`crates/`), the C API or its header | `cargo xtask check` |
| what the Vulkan platform ends the process on, or what device info, GPU families or feature queries answer | the library's checks, and a cold boot of each guest the change can reach before it merges ("A boot is the only check", below) |
| a `.metal` source of the Vulkan crate, `shaders.metal` among them | `cargo xtask metallibs` on a Mac, committing the metallibs it writes with the change; then the library's checks |
| the video crate (`crates/reims-vgpu-video`), or its arms in `reims-vgpu` | `cargo xtask check` on a Mac; the Linux tests on a VA-API host and on an NVIDIA host; and, where the `vaapi` module's decoders change, the conformance suite on a VA-API host ("The video crates' checks", below) |
| the video crate (`crates/reims-vgpu-video`), or its arms in `reims-vgpu` | `cargo xtask check` on a Mac; the Linux tests on a VA-API host and on an NVIDIA host; where the `vaapi` module's decoders change, the conformance suite on a VA-API host; and, where the `videotoolbox` module or its arm changes, `crates/reims-vgpu-video/tools/vt-check.sh` on a Mac, its hardware decoders against ffmpeg's MD5s ("The video crates' checks", below) |
| Windows-only code (`cfg(windows)` files) | `cargo xtask check` on the Mac or Linux, which clippy-checks the Windows target; and the crate's tests on homelab-mac-mini-2018, `scripts/internal/windows-tests.sh -p <crate>`: two potluck jobs there, the build, which starts from the mini's kept base build (`MINIBASE=0` builds from nothing), then the tests holding its UHD 630 (`--gpu 8086:3e9b`; the tests' job peaked at 14.7 to 20.7 GiB of commit charge, and reserves 26 GiB) |
| `xtask/` | `cargo test -p xtask`, rustfmt and clippy on it |
| `crates/reims-ctl` | `cargo test`, `cargo fmt --check`, `cargo clippy --all-targets`, and `cargo clippy --all-targets --target x86_64-pc-windows-gnullvm` on the Mac, in it (`cargo xtask check` does not reach it; the last is the one check that sees a break of its Windows build, and needs a MinGW C compiler for ring's build script: on the Mac, Homebrew's `mingw-w64`, with `CC_x86_64_pc_windows_gnullvm=x86_64-w64-mingw32-gcc` and `AR_x86_64_pc_windows_gnullvm=x86_64-w64-mingw32-ar`; a Linux host without that toolchain fails it); a change to the QEMU command it builds, or to `scripts/install-ctl.sh` or `scripts/install.ps1`, also needs an install and a VM boot on each host it touches |
| `guest/` (kext, bundle, rgfxgate, loader) | `make -C guest test` on a Mac; a change to a source the sets are built from also needs `make -C guest prebuilt` and `make -C guest prebuilt-arm64e`, committing `guest/prebuilt` and `guest/prebuilt-arm64e` with it (`make -C guest prebuilt-check`, which checks both, fails otherwise) |
| `crates/reims-ctl` or `crates/reims-restore` | `make check-ctl` on the Mac, which runs `cargo fmt --check`, `cargo clippy --all-targets`, `cargo clippy --all-targets --target x86_64-pc-windows-gnullvm` and `cargo test` in each of the two workspaces, `crates/reims-ctl` and `crates/reims-restore` (with reims-apfs), with `-D warnings` and `--workspace` (`cargo xtask check` reaches neither; the Windows clippy is the one check that sees a break of their Windows build, and needs a MinGW C compiler for ring's build script: on the Mac, Homebrew's `mingw-w64`, which the target gives as `CC_x86_64_pc_windows_gnullvm=x86_64-w64-mingw32-gcc` and `AR_x86_64_pc_windows_gnullvm=x86_64-w64-mingw32-ar`; where `x86_64-w64-mingw32-gcc` is not on the PATH, a Linux host's among them, the target says so and fails); a change to the QEMU command it builds, or to `scripts/install-ctl.sh` or `scripts/install.ps1`, also needs an install and a VM boot on each host it touches |
| `guest/` (kext, bundle, rgfxgate, loader) | `make -C guest test` on a Mac, which on Apple silicon also runs the bundle's checks a second time for arm64, natively, in `guest/bundle/build/arm64` (its x86_64 checks run under Rosetta there, and natively on an x86-64 Mac); a change to a source the sets are built from also needs `make -C guest prebuilt` and `make -C guest prebuilt-arm64e`, committing `guest/prebuilt` and `guest/prebuilt-arm64e` with it (`make -C guest prebuilt-check`, which checks both, fails otherwise) |
| `firmware/`, the option ROM | build it (`make -C firmware`); a change not meant to alter what the guest's firmware sees keeps the ROM's bytes; a change to what `ReimsGraphics.rom` is built from (its sources, the Makefile, `crates/reims-vgpu-graphics/include/reims_graphics_wire.h`) also runs `make -C firmware prebuilt` on a Mac, committing the ROM and record it writes |
| `firmware/ambrosia` | build it (`make -C firmware/ambrosia bundle`); a change to what it does with the device also needs an arm64 guest's boot on Ambrosia with the device and the module ([docs/qemu.md](docs/qemu.md), "arm64 guests") |
| `vendor/qemu` | build it (`make qemu`) and realize the device paused (`-S`); a change to `hw/display/reims-graphics-pci.c`, or to what QEMU calls, also needs a VM boot ([docs/lessons.md](docs/lessons.md), [docs/qemu.md](docs/qemu.md)) |
Generated
+4
View File
@@ -213,6 +213,7 @@ checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "metal2vulkan"
version = "0.2.0"
source = "git+https://github.com/reims-go/metal2vulkan?rev=1dd4e970c0562c73bd3eba12cd15999bb035e019#1dd4e970c0562c73bd3eba12cd15999bb035e019"
dependencies = [
"ash",
"metal2vulkan-air",
@@ -223,6 +224,7 @@ dependencies = [
[[package]]
name = "metal2vulkan-air"
version = "0.2.0"
source = "git+https://github.com/reims-go/metal2vulkan?rev=1dd4e970c0562c73bd3eba12cd15999bb035e019#1dd4e970c0562c73bd3eba12cd15999bb035e019"
dependencies = [
"sha2 0.11.1",
]
@@ -230,6 +232,7 @@ dependencies = [
[[package]]
name = "metal2vulkan-runtime"
version = "0.2.0"
source = "git+https://github.com/reims-go/metal2vulkan?rev=1dd4e970c0562c73bd3eba12cd15999bb035e019#1dd4e970c0562c73bd3eba12cd15999bb035e019"
dependencies = [
"ash",
"libc",
@@ -419,6 +422,7 @@ dependencies = [
"parking_lot",
"reims-vgpu-graphics",
"reims-vgpu-video",
"reims-vgpu-video-conformance",
"reims-vgpu-vulkan",
"reims-vgpu-window",
"sha2 0.10.9",
+5 -2
View File
@@ -33,11 +33,11 @@ reims-vgpu-graphics = { path = "crates/reims-vgpu-graphics" }
reims-vgpu-video = { path = "crates/reims-vgpu-video" }
# metal2vulkan's Metal types, for the Metal enums and descriptor values the runtime's calls take,
# from metal2vulkan's public repository at the commit both name.
metal2vulkan = { git = "https://github.com/steelbrain/metal2vulkan", rev = "0b0ac58eb0f69ed3b37007fbdf3b135a46f90699" }
metal2vulkan = { git = "https://github.com/reims-go/metal2vulkan", rev = "1dd4e970c0562c73bd3eba12cd15999bb035e019" }
# The Vulkan platform's runtime (architecture D1), metal2vulkan-runtime: a Metal-shaped API on
# Vulkan, one path for every device, under reims-vgpu-vulkan's `rt_platform` and `seam` and
# reims-vgpu's `pool::rt_blocks`.
metal2vulkan-runtime = { git = "https://github.com/steelbrain/metal2vulkan", rev = "0b0ac58eb0f69ed3b37007fbdf3b135a46f90699" }
metal2vulkan-runtime = { git = "https://github.com/reims-go/metal2vulkan", rev = "1dd4e970c0562c73bd3eba12cd15999bb035e019" }
# The hashes of the Vulkan platform's metallib sources (reims-vgpu-vulkan/build.rs).
sha2 = "0.10.9"
# A display window's swapchain on Linux (reims-vgpu-vulkan/src/swapchain.rs), at the runtime's
@@ -87,6 +87,9 @@ tikv-jemallocator = "0.7.0"
[workspace.lints.rust]
unsafe_op_in_unsafe_fn = "deny"
missing_docs = "warn"
# A result the caller must take is taken: an ignored `#[must_use]` value does not compile, as a
# blit command's `Encoded` (whether the platform recorded it) is one every caller answers.
unused_must_use = "deny"
# The workspace's docs are its developers', built with its private items (`cargo doc
# --document-private-items`), where a public item's links to the private items its docs name
+51 -1
View File
@@ -15,6 +15,12 @@
# Mesa's KosmicKrisp driver, which the library's rt platform
# loads from ../lib of a QEMU in build/qemu or in a directory
# beside it (make qemu makes them too); nothing elsewhere
# make check-ctl
# reims-ctl's checks (AGENTS.md, "Checking a change") in each
# of its two workspaces, crates/reims-ctl and crates/reims-restore
# (with reims-apfs), which cargo xtask check reaches neither of:
# rustfmt, clippy, clippy for x86-64 Windows and the tests; it
# stops where x86_64-w64-mingw32-gcc is not on the PATH
# make clean remove build/, QEMU's build included
#
# QEMU_CONFIGURE adds options to QEMU's configure and runs it again.
@@ -38,7 +44,7 @@ RUST_DIST := $(RUST_TARGET)/dist-vulkan
# (crates/reims-vgpu-vulkan/src/rt_platform/stage.rs).
HELPER := reims-vgpu-compile$(if $(filter Windows_NT,$(OS)),.exe)
.PHONY: all qemu vulkan-links clean
.PHONY: all qemu vulkan-links check-ctl clean
all:
CARGO_TARGET_DIR="$(RUST_TARGET)" cargo xtask dist
@@ -122,5 +128,49 @@ vulkan-links:
fi; \
done
# reims-ctl's checks, run in each of its workspaces by --manifest-path, never
# through the library's xtask: reims-ctl and reims-restore are workspaces of
# their own, so they build without the metal2vulkan the library's workspace
# fetches. The cheapest step first, and the first failure stops it. clippy for
# x86_64-pc-windows-gnullvm, the Windows build, is the one check on the Mac or
# Linux that sees a break of it (docs/lessons.md): its build scripts compile
# C for Windows (ring's, under ureq's rustls) with MinGW's gcc and ar, which
# a Mac has from Homebrew's mingw-w64. Where they are missing it says so and
# stops, before any step runs. On Windows, where reims-ctl builds for that
# target natively (MSYS2's CLANG64), the host's clippy is that check, and it
# says so in place of a second run.
CTL_WORKSPACES := crates/reims-ctl crates/reims-restore
CTL_WINDOWS := x86_64-pc-windows-gnullvm
CTL_MINGW := x86_64-w64-mingw32
check-ctl:
ifneq ($(OS),Windows_NT)
@for t in gcc ar; do command -v $(CTL_MINGW)-$$t >/dev/null || { \
echo "check-ctl: $(CTL_MINGW)-$$t is not on the PATH, and clippy for $(CTL_WINDOWS) needs it for the C its dependencies build (on a Mac: brew install mingw-w64)" >&2; \
exit 1; }; done
endif
@for w in $(CTL_WORKSPACES); do \
echo "check-ctl: rustfmt in $$w"; \
cargo fmt --manifest-path $$w/Cargo.toml --all --check || exit 1; \
done
@for w in $(CTL_WORKSPACES); do \
echo "check-ctl: clippy in $$w"; \
cargo clippy --manifest-path $$w/Cargo.toml --workspace --all-targets -- -D warnings || exit 1; \
done
ifeq ($(OS),Windows_NT)
@echo "check-ctl: clippy for $(CTL_WINDOWS): the clippy above, this host's"
else
@for w in $(CTL_WORKSPACES); do \
echo "check-ctl: clippy for $(CTL_WINDOWS) in $$w"; \
CC_x86_64_pc_windows_gnullvm=$(CTL_MINGW)-gcc AR_x86_64_pc_windows_gnullvm=$(CTL_MINGW)-ar \
cargo clippy --manifest-path $$w/Cargo.toml --workspace --all-targets --target $(CTL_WINDOWS) -- -D warnings || exit 1; \
done
endif
@for w in $(CTL_WORKSPACES); do \
echo "check-ctl: tests in $$w"; \
cargo test --manifest-path $$w/Cargo.toml --workspace || exit 1; \
done
@echo "check-ctl: ok"
clean:
rm -rf "$(BUILD_DIR)"
+55 -39
View File
@@ -36,9 +36,12 @@ GPU the wrong pages of the guest's memory, which can overwrite it. `reims-ctl` w
an older kernel, and `reims-ctl doctor` shows the kernel it found.
arm64 macOS 14 to 27 runs on QEMU too, with Ambrosia, our own arm64 firmware, and the same virtual
GPU. On an Apple silicon Mac it runs under HVF, macOS's hypervisor, and on arm64 Linux under KVM.
An x86-64 Linux host runs arm64 VMs as well, with QEMU emulating the CPU (TCG), which is much
slower; we've checked macOS 14, 15 and 26 that way. `reims-ctl` makes an arm64 VM by restoring
GPU. On an Apple silicon Mac it runs under HVF, macOS's hypervisor, and on arm64 Linux under KVM. An
x86-64 Linux host runs arm64 VMs as well, with QEMU emulating the CPU (TCG), which is much slower;
we've checked macOS 14, 15 and 26 that way. An x86-64 Windows PC runs them emulated the same way,
also much slower. On Windows we have only a contributor's report so far: macOS 27.2.1 restored and
booted to its desktop on Windows 11, on a laptop with a 12th-generation Intel Core i7 and an RTX
3060 Laptop GPU; we haven't run one there ourselves yet. `reims-ctl` makes an arm64 VM by restoring
macOS from an IPSW, Apple's restore image, onto a new disk, and boots it with Ambrosia, which adds
our drivers to the guest as it starts. [docs/qemu.md](docs/qemu.md), "arm64 guests", has the
details.
@@ -62,7 +65,10 @@ on Mesa's KosmicKrisp, from Homebrew's `mesa`) and QEMU on it, installs QEMU int
release, which `reims-ctl` checks against the hash it pins. `vendor/qemu` is
fetched from its public repository (`steelbrain/qemu-reims-vgpu`), at the commit this checkout
pins, and Cargo fetches metal2vulkan from its public repository, at the commit the workspace's
`Cargo.toml` names. `reims-ctl doctor` checks the host and the install.
`Cargo.toml` names. On Linux it also writes `~/.local/share/applications/reims-vgpu.desktop`, a
hidden app entry for the VMs' windows, so GNOME can remember your answer when it asks whether a
window may take its shortcuts; it leaves alone a file there it didn't write.
`reims-ctl doctor` checks the host and the install.
On Windows, open PowerShell and run:
@@ -78,7 +84,8 @@ restart once before your first VM), clones the repository into your user folder
clang, with the Rust toolchain that goes with it: it installs Rust if you don't have it, and adds
that toolchain beside yours if your Rust is set up for Visual Studio, so you don't need Visual
Studio. It installs `reims-ctl` into `%USERPROFILE%\.cargo\bin`. On an Intel Core i7-8700B a
first install took about 20 minutes, and running it again about a minute. From a clone,
first install took about 20 minutes, and running it again about a minute, measured before the
install also built QEMU for arm64 VMs and `reims-restore`. From a clone,
`powershell -ExecutionPolicy Bypass -File scripts\install.ps1` does the same. Windows support is
newer than Linux's. The guest's H.264 and HEVC video decodes on your GPU there through Mesa's VA-API
driver for Direct3D 12, which the install adds from MSYS2. Encoding doesn't use your GPU on Windows
@@ -130,7 +137,7 @@ yet, whichever GPU you have, so the guest encodes video in software there.
`--installer` takes an installer of your own.
An arm64 VM comes from an IPSW instead. On a Mac or arm64 Linux that's what `create` makes; on
x86-64 Linux, `--ipsw` asks for one:
x86-64 Linux and Windows, `--ipsw` asks for one:
```sh
reims-ctl create mac --ipsw latest --start # downloads the current macOS's IPSW, about 25 GB
@@ -139,19 +146,22 @@ yet, whichever GPU you have, so the guest encodes video in software there.
Apple offers only the current macOS to download, so an older one needs an IPSW you have. The
download is kept for your next VM. The VM's first boot makes macOS's Data volume and then
resets the VM, which won't start again until you finish it: stop it, run
`reims-restore finish-eacs` with the VM's folder, and the next start goes to Setup Assistant.
resets the VM, which won't start again until you finish it: stop it and run
`reims-restore finish-eacs` with the VM's folder. If it says the VM needs one more first boot,
start it, and after that boot stop it and finish again. Once it finishes, the next start goes
to Setup Assistant.
### Day to day
`reims-ctl` with no command opens its interactive interface: create a VM, start it (each of its
displays opens in a window), stop it (the guest shuts down, or is powered off after a timeout),
edit its CPUs, memory, displays (up to four), resolution, borderless windows, input capture,
GPU, audio and logs, change its installer, print the exact QEMU command it runs, and zip its
logs with the host's details into Downloads for a bug report.
edit its CPUs, memory, displays (up to four), resolution, borderless windows, GPU, audio and
logs, change its installer, print the exact QEMU command it runs, and zip its logs with the
host's details into Downloads for a bug report.
```sh
reims-ctl list # the VMs and whether they run
reims-ctl resume mac # free space first: a VM pauses when this host's disk fills up
reims-ctl set mac --memory 12G --resolution 1920x1080 # applies at the next start
reims-ctl command mac # the QEMU command it runs, as a shell script
reims-ctl report mac # logs, settings, the host's details and its vulkaninfo, zipped, for a bug report
@@ -162,31 +172,32 @@ reims-ctl update --channel development # switch to the development branch firs
`reims-ctl help` lists every command; every option takes `--name value` or `--name=value`. A running
VM keeps the QEMU it started with across an update.
### The window takes your keyboard shortcuts and your mouse
### The window takes your keyboard shortcuts
Each of the guest's displays opens in a window the library owns (`crates/reims-vgpu-window`). **Click into the
guest's picture to capture the keyboard and the mouse:** shortcuts and system keys then go to the
guest instead of the host, and the pointer stays inside the picture until you release it, so you
can throw it at the guest's corners and edges without landing on another window. Keys reach the
guest by position, so the guest's own layout applies, and the Super key (the Windows key on Windows)
is the guest's ⌘. While captured, the window grabs the whole keyboard (SDL3's window, on Wayland or
X11), so the compositor's shortcuts, Super and Alt+Tab among them, reach the guest; on Windows, the
Windows key and Alt+Tab do too. **Ctrl+Alt+Super** together (**Ctrl+Alt+Win** on Windows) releases
it.
Each of the guest's displays opens in a window the library owns (`crates/reims-vgpu-window`).
While the window has the keyboard, your shortcuts go to the guest instead of the host. On Linux
the window grabs the whole keyboard (SDL3's window, on Wayland or X11), so the compositor's
shortcuts, Super and Alt+Tab among them, reach the guest; on Windows the Windows key, Alt+Tab and
Alt+F4 do too. Keys reach the guest by position, so the guest's own layout applies, and the Super
key (the Windows key on Windows) is the guest's ⌘. There's nothing to click first, and the mouse
is never held: it moves in and out of the window freely, the window resizes as any other does,
and a click on another window or the taskbar takes you out. **Ctrl+Alt+Super** together
(**Ctrl+Alt+Win** on Windows) gives the host its shortcuts back until you next switch to the
window; the title names those keys while the window holds the keyboard.
The title says when input is captured and how to release it. Losing focus releases capture too,
and gives the host back its system keys and its pointer. Losing focus, releasing capture or closing the window sends a key-up for every key
still down, so nothing sticks. Closing a window first asks "Turn off the VM?": Turn Off powers the
VM off at once, as if its power were cut, and Cancel keeps it running.
On a Mac, every ⌘ shortcut goes to the guest while its window is in front, ⌘Q among them, so quit
the VM from the menu or by closing its window. Some keys never reach the guest, because the system
keeps them before any app sees them: Ctrl+Alt+Del and Win+L on Windows, and on a Mac ⌘Space, ⌘Tab,
Mission Control and the screenshot keys.
If you'd rather the window never capture anything, turn off **Capture input** in the VM's
settings (`e` in `reims-ctl`, or `reims-ctl set <vm> --capture false`; it applies at the VM's
next start). The title then ends "— input capture off". Clicks and keys still reach the guest
while its window is in front, but nothing is grabbed or held: the pointer moves out of the window
freely, and the host keeps its own shortcuts, such as Alt+Tab or ⌘Tab. On a Mac, other ⌘
shortcuts go to the guest, ⌘Q among them, so quit the VM from the menu or by closing its window.
A game that steers by the mouse's motion gets the plain pointer, which stops at the edge of the
guest's picture.
When a game hides the guest's cursor to steer by the mouse, the window holds the pointer still
and hands the guest the mouse's motion, while the window has the keyboard and the pointer is over
the picture. The title then names the keys that let the pointer go: Ctrl+Alt+Super, Ctrl+Alt+Win
on Windows, ⌃⌥⌘ on a Mac.
Losing focus, those keys or closing the window sends a key-up for every key still down, so
nothing sticks. Closing a window first asks "Turn off the VM?": Turn Off powers the VM off at
once, as if its power were cut, and Cancel keeps it running.
Fn/Globe does not reach the guest (QEMU's USB keyboard cannot carry it), and there is no HDR output.
[`crates/reims-vgpu-window/features.md`](crates/reims-vgpu-window/features.md) lists everything the
@@ -200,13 +211,16 @@ reads them once per process, and an unset or unparsable value is the default.
| Variable | Effect |
|---|---|
| `REIMS_VGPU_LOG=info` | the library's log lines to stderr, filtered by a level and `target=level` pairs (`warn,reims_vgpu_graphics=debug`); unset, nowhere. `reims-ctl set <vm> --log-level` sets it |
| `REIMS_VGPU_WINDOW=0` | QEMU stays headless under `-display none` (QEMU reads it, not the library) |
| `REIMS_VGPU_WINDOW=0` | QEMU stays headless under `-display none` (QEMU reads it, not the library). `reims-ctl start <vm> --headless` starts a VM so for that start alone, and `reims-ctl view <vm>` shows its screen |
| `REIMS_VGPU_WINDOW_BORDERLESS=1` | a borderless window that fills its screen |
| `REIMS_VGPU_STRICT=1` | end the process when the host runs out of memory, instead of answering the guest the way Metal does then |
The window opens at the size of QEMU's `reims-graphics-pci` property `resolution=` (1920x1080 by
default), which `reims-ctl`'s resolution setting sets, and the guest follows the window as you
resize it. [docs/api.md](docs/api.md) section 2 lists every setting and variable.
Each window opens at its size of QEMU's `reims-graphics-pci` property `resolution=` (1920x1080 by
default), which `reims-ctl`'s resolution setting sets: one size for every display, or one for each
display, comma-separated, so `reims-ctl set mac --resolution 2560x1440,1920x1080` gives a VM's two
displays a size each. The guest follows each window as you resize it. The guest's Displays settings also list a few smaller sizes of the window's shape: pick
one and the window keeps its size, showing the guest's picture scaled up to fill it.
[docs/api.md](docs/api.md) section 2 lists every setting and variable.
## What's here
@@ -237,7 +251,7 @@ library, which runs it on Vulkan through [`metal2vulkan`](https://github.com/ste
and draws the guest's display into a window of its own. On a Mac the library runs on Vulkan too,
on Mesa's KosmicKrisp driver rather than on Metal, and the guest's side is built there. x86-64 VMs
run on Linux and Windows hosts, and arm64 VMs under HVF on Apple silicon Macs, under KVM on arm64
Linux and under TCG on x86-64 Linux ([docs/qemu.md](docs/qemu.md), "arm64 guests").
Linux and under TCG on x86-64 Linux and Windows ([docs/qemu.md](docs/qemu.md), "arm64 guests").
The library's C API (`crates/reims-vgpu-c/include/reims_vgpu.h`, specified in
[docs/api.md](docs/api.md)) is its interface to QEMU: `cargo xtask dist` writes the library, the
@@ -251,7 +265,9 @@ it needs itself; working on the code needs the following.
TCG; on arm64, arm64 VMs under KVM; VMs on our GPU need Linux 7.2 or later), and an Apple silicon Mac for the metallibs and the guest's
kexts, where arm64 VMs run under HVF. Every Rust binary built on the Mac is arm64
(`aarch64-apple-darwin`): rustc's arm64e target has no pointer authentication, and its binaries
crash before `main` (`rust-toolchain.toml`).
crash before `main` (`rust-toolchain.toml`). An x86-64 Windows PC runs x86-64 VMs under WHPX
and arm64 VMs under TCG, with the library and QEMU built in MSYS2's CLANG64 shell
(`scripts/install.ps1`).
- The toolchain `rust-toolchain.toml` pins: nightly-2026-11-03 with rustfmt and clippy, for rustc's
parallel front end (`-Zthreads`, in `.cargo/config.toml`). rustup installs it on first use.
- `cargo-nextest`, which runs the tests in `cargo xtask check`
+18
View File
@@ -2013,6 +2013,7 @@ dependencies = [
"clap",
"crc32fast",
"flate2",
"getrandom 0.4.3",
"libc",
"plist",
"png",
@@ -2023,6 +2024,7 @@ dependencies = [
"sha2 0.11.1",
"shlex",
"toml",
"toml_edit",
"ureq",
"windows-sys 0.61.2",
"zip",
@@ -2619,6 +2621,19 @@ dependencies = [
"serde_core",
]
[[package]]
name = "toml_edit"
version = "0.25.17+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3641d5bbb5349a79e1020a242d251efbc546ad8048d133958323ce9c40a9c9c"
dependencies = [
"indexmap",
"toml_datetime",
"toml_parser",
"toml_writer",
"winnow",
]
[[package]]
name = "toml_parser"
version = "1.1.5+spec-1.1.0"
@@ -3045,6 +3060,9 @@ name = "winnow"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81"
dependencies = [
"memchr",
]
[[package]]
name = "wit-bindgen"
+6
View File
@@ -18,6 +18,8 @@ anyhow = "1.0.104"
clap = { version = "4.6.7", features = ["derive", "env", "wrap_help"] }
crc32fast = "1.5.2"
flate2 = "1.1.10"
# A new VM's random MAC (vm.rs), from the OS's random source, as reims-restore takes its nonces.
getrandom = "0.4.3"
# An x86-64 VM's OpenCore config.plist, for the Mac it presents (opencore.rs).
plist = "1.10.1"
# The viewer's frames for the kitty and iTerm2 image protocols (view/encode.rs).
@@ -32,6 +34,10 @@ serde_json = "1.0.153"
sha2 = "0.11.1"
shlex = "2.0.1"
toml = "1.1.2"
# Writes reims-ctl's TOML records (a VM's vm.toml, the registry, the install's and the migrations'
# records) over their files as they are, keeping what another build of reims-ctl wrote there in
# its place and form (record.rs).
toml_edit = "0.25.17"
# Downloads that release's zip from its release page (ambrosia.rs), with rustls, as reims-restore
# downloads from Apple.
ureq = "3.5.1"
+32 -17
View File
@@ -11,32 +11,26 @@
//! here as its Makefile builds `build/ReimsGraphics.elf`: with clang and the Makefile's
//! `CFLAGS`, and linked with the `LDFLAGS` by the toolchain's own lld (rust-lld, as GNU's
//! `ld.lld`), so the build needs clang and no lld of the host's. Where clang can't build it,
//! reims-ctl carries no module, says so as it builds, and refuses to start an arm64 VM.
//!
//! A reims-ctl for Windows, which runs no arm64 VM (src/host.rs), carries neither the arm64 set
//! nor the module.
//! reims-ctl carries no module, says so as it builds, and refuses to start an arm64 VM;
//! - reims-ctl's build stamp, the commit its checkout is at (`src/build_stamp.rs`).
use std::fmt::Write as _;
use std::path::{Path, PathBuf};
use std::process::Command;
#[path = "src/build_stamp.rs"]
mod build_stamp;
fn main() {
stamp();
let crate_dir = PathBuf::from(std::env::var_os("CARGO_MANIFEST_DIR").expect("cargo sets it"));
let out_dir = PathBuf::from(std::env::var_os("OUT_DIR").expect("cargo sets it"));
let out = out_dir.join("set.rs");
// A reims-ctl for Windows runs no arm64 VM (src/host.rs), and carries no arm64 guest.
let windows = std::env::var("CARGO_CFG_TARGET_OS").is_ok_and(|os| os == "windows");
let (set_arm64e, module) = if windows {
("None".to_string(), "None".to_string())
} else {
(
set_code(
&crate_dir.join("../../guest/prebuilt-arm64e"),
"guest/prebuilt-arm64e",
),
module_code(&crate_dir.join("../../firmware/ambrosia"), &out_dir),
)
};
let set_arm64e = set_code(
&crate_dir.join("../../guest/prebuilt-arm64e"),
"guest/prebuilt-arm64e",
);
let module = module_code(&crate_dir.join("../../firmware/ambrosia"), &out_dir);
let set = format!(
"/// guest/prebuilt/set.toml's set, in its order.\n\
pub static SET: Option<&[Kext]> = {};\n\
@@ -258,3 +252,24 @@ fn walk(root: &Path, dir: &Path, files: &mut Vec<(String, PathBuf)>) {
}
}
}
/// Stamps reims-ctl with the commit its checkout is at (`src/build_stamp.rs`), as
/// `REIMS_CTL_STAMP`, read again where the checkout's HEAD or index moves or reims-ctl's sources
/// change.
fn stamp() {
let crate_dir = PathBuf::from(std::env::var_os("CARGO_MANIFEST_DIR").unwrap_or_default());
let root = crate_dir.join("../..");
println!(
"cargo::rustc-env=REIMS_CTL_STAMP={}",
build_stamp::read(&root)
);
for file in build_stamp::git_files(&root) {
println!("cargo::rerun-if-changed={}", file.display());
}
for source in ["src", "Cargo.toml", "build.rs"] {
println!(
"cargo::rerun-if-changed={}",
crate_dir.join(source).display()
);
}
}
+2 -10
View File
@@ -105,19 +105,11 @@ fn image_from_zip(zip: &[u8]) -> Result<Vec<u8>> {
}
/// Writes `bytes` to `file` through a file beside it renamed into place, so a reader never sees
/// it half-written.
/// it half-written ([`crate::record::replace`]).
fn write(file: &Path, bytes: &[u8]) -> Result<()> {
let dir = file.parent().unwrap_or(Path::new("."));
std::fs::create_dir_all(dir).with_context(|| format!("create {}", dir.display()))?;
let mut tmp = file.as_os_str().to_os_string();
tmp.push(format!(".{}.tmp", std::process::id()));
let tmp = PathBuf::from(tmp);
let written = std::fs::write(&tmp, bytes).and_then(|()| std::fs::rename(&tmp, file));
if let Err(e) = written {
let _ = std::fs::remove_file(&tmp);
return Err(e).with_context(|| format!("write {}", file.display()));
}
Ok(())
crate::record::replace(file, bytes).with_context(|| format!("write {}", file.display()))
}
/// `bytes`' SHA-256, in lowercase hex.
+123
View File
@@ -0,0 +1,123 @@
//! reims-ctl's build stamp, which its build script reads at each build (`build.rs`), and
//! `reims-ctl --version` and a report's system.txt show (`REIMS_CTL_STAMP`; the crate compiles
//! this module for its tests alone): the commit the checkout is at, `git rev-parse HEAD`, with
//! `-dirty` where a tracked file of the tree differed from it or git could not say, and `unknown`
//! for a build outside a checkout (no git, or no commit), which never fails the build. Left aside as the tree is compared: submodules, and the workspace's `Cargo.lock`,
//! which is committed without metal2vulkan's git `source` lines and which every build of the
//! library writes them back into. The build script reads it again where the checkout's HEAD or
//! index moves, or reims-ctl's sources change. A diagnostic: nothing decides on it.
use std::path::{Path, PathBuf};
use std::process::Command;
/// The stamp of a tree whose `git rev-parse HEAD` answered `head` and whose status
/// ([`STATUS`]) answered `status`, each `None` where git failed (the module doc).
pub fn stamp(head: Option<&str>, status: Option<&str>) -> String {
let Some(head) = head.map(str::trim).filter(|h| !h.is_empty()) else {
return "unknown".to_owned();
};
match status {
Some(status) if status.trim().is_empty() => head.to_owned(),
_ => format!("{head}-dirty"),
}
}
/// The status the stamp reads: the tracked files that differ from HEAD, but those the module doc
/// leaves aside.
pub const STATUS: [&str; 7] = [
"status",
"--porcelain",
"--untracked-files=no",
"--ignore-submodules",
"--",
".",
":(exclude)Cargo.lock",
];
/// What `git -C <dir> <args>` writes on its stdout, where it runs and succeeds.
pub fn git(dir: &Path, args: &[&str]) -> Option<String> {
let out = Command::new("git")
.arg("-C")
.arg(dir)
.args(args)
.output()
.ok()?;
out.status
.success()
.then(|| String::from_utf8_lossy(&out.stdout).into_owned())
}
/// The stamp of the tree at `root`, read from git.
pub fn read(root: &Path) -> String {
let head = git(root, &["rev-parse", "HEAD"]);
let status = head.as_ref().and_then(|_| git(root, &STATUS));
stamp(head.as_deref(), status.as_deref())
}
/// The files of the checkout at `root` whose change moves HEAD or the index: its HEAD and index,
/// the branch's ref HEAD names, and the packed refs, those that exist (Cargo runs a build script
/// again at every build for a path that does not).
pub fn git_files(root: &Path) -> Vec<PathBuf> {
let dir = |args: &[&str]| git(root, args).map(|d| PathBuf::from(d.trim()));
let mut files = Vec::new();
if let Some(own) = dir(&["rev-parse", "--absolute-git-dir"]) {
files.push(own.join("HEAD"));
files.push(own.join("index"));
}
if let Some(common) = dir(&["rev-parse", "--path-format=absolute", "--git-common-dir"]) {
if let Some(branch) = git(root, &["symbolic-ref", "-q", "HEAD"]) {
files.push(common.join(branch.trim()));
}
files.push(common.join("packed-refs"));
}
files.retain(|f| f.exists());
files
}
#[cfg(test)]
mod tests {
use super::*;
const HEAD: &str = "41f0bba449c1e1f1b2e5d3c4a5b6c7d8e9f00112";
/// A clean tree's stamp is its commit.
#[test]
fn a_clean_tree_is_stamped_with_its_commit() {
assert_eq!(stamp(Some(&format!("{HEAD}\n")), Some("")), HEAD);
}
/// A tree with a tracked file changed, or whose status git could not give, is marked dirty.
#[test]
fn a_changed_tree_is_stamped_dirty() {
let dirty = format!("{HEAD}-dirty");
assert_eq!(
stamp(Some(HEAD), Some(" M crates/reims-ctl/src/logs.rs\n")),
dirty
);
assert_eq!(stamp(Some(HEAD), None), dirty);
}
/// A build outside a checkout, where git answers no commit, is stamped unknown.
#[test]
fn a_build_outside_a_checkout_is_unknown() {
assert_eq!(stamp(None, None), "unknown");
assert_eq!(stamp(Some("\n"), Some("")), "unknown");
let nowhere = std::env::temp_dir().join("reims-ctl-no-checkout-here");
assert_eq!(git(&nowhere, &["rev-parse", "HEAD"]), None);
assert_eq!(read(&nowhere), "unknown");
assert!(git_files(&nowhere).is_empty());
}
/// The build stamped reims-ctl with this checkout's commit, the one the tests run at.
#[test]
fn reims_ctl_carries_its_build_s_stamp() {
let built = env!("REIMS_CTL_STAMP");
// Read at run time, so the test names no worktree (docs/development.md).
let manifest = std::env::var_os("CARGO_MANIFEST_DIR").unwrap();
let root = Path::new(&manifest).join("../..");
match git(&root, &["rev-parse", "HEAD"]) {
Some(head) => assert!(built.starts_with(head.trim()), "{built} {head}"),
None => assert_eq!(built, "unknown"),
}
}
}
File diff suppressed because it is too large. Load diff
+177 -24
View File
@@ -17,6 +17,7 @@ use anyhow::{Context, Result};
use std::fs::File;
use std::io;
use std::path::Path;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
#[cfg(unix)]
@@ -34,6 +35,13 @@ use windows::{APART, UNSUPPORTED, clone, create, data_ranges, file_system};
/// without a word.
const LONG: u64 = 1_000_000_000;
/// The type of the file system the directory `dir` is on, as the host names it: Linux's mount
/// table (btrfs, ext4, vfat), macOS's statfs (apfs, exfat, msdos), Windows' volume (NTFS, ReFS,
/// FAT32). None where the host gives none, or `dir` does not exist.
pub fn file_system_of(dir: &Path) -> Option<String> {
file_system(dir)
}
/// Copies `src` to `dst`, a file that does not exist yet, with `src`'s permissions: a reflink or
/// clone where the file system makes one, else a full copy, which `progress` hears of first where
/// it is long, with its size and why it is no reflink, and then how far it is.
@@ -43,6 +51,18 @@ pub fn file(src: &Path, dst: &Path, progress: &mut dyn FnMut(&str)) -> Result<()
/// [`file()`], where a full copy of more than `long` bytes of data is told.
fn copy(src: &Path, dst: &Path, long: u64, progress: &mut dyn FnMut(&str)) -> Result<()> {
copy_with(src, dst, long, &clone, progress)
}
/// [`copy`], making the reflink or clone with `clone`. Any refusal of it falls back to the full
/// copy, whatever its error: the error only says why in what the copy tells.
fn copy_with(
src: &Path,
dst: &Path,
long: u64,
clone: &dyn Fn(&Path, &Path) -> io::Result<()>,
progress: &mut dyn FnMut(&str),
) -> Result<()> {
let fail = || format!("could not copy {} to {}", src.display(), dst.display());
let refused = match clone(src, dst) {
Ok(()) => return Ok(()),
@@ -54,47 +74,136 @@ fn copy(src: &Path, dst: &Path, long: u64, progress: &mut dyn FnMut(&str)) -> Re
let ranges = data_ranges(&from, len);
let total: u64 = ranges.iter().map(|(a, b)| b - a).sum();
if total <= long {
return full(&from, &to, &ranges, len, &mut |_| {}).with_context(fail);
return full(&from, &to, &ranges, len, &mut |_| {}, None).with_context(fail);
}
let why = Why::of(&refused, src, dst);
let name = src
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
progress(&format!(
"copying {name} in full, {}, not as a reflink: {}",
"copying {} in full, {}, not as a reflink: {}",
name_of(src),
size(total),
why.note(src, dst)
));
// Each whole percent, at most once a second but for the first and the last.
let short = why.short();
full_told(&from, &to, &ranges, len, &why.short(), src, progress, None).with_context(fail)
}
/// The file name of `p`, for what a copy says.
fn name_of(p: &Path) -> String {
p.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default()
}
/// [`full`], telling `progress` each whole percent of the data copied, at most once a second but
/// for the first and the last, with `short`, why it is no reflink.
#[allow(clippy::too_many_arguments)]
fn full_told(
from: &File,
to: &File,
ranges: &[(u64, u64)],
len: u64,
short: &str,
src: &Path,
progress: &mut dyn FnMut(&str),
cancel: Option<&AtomicBool>,
) -> io::Result<()> {
let total: u64 = ranges.iter().map(|(a, b)| b - a).sum();
let name = name_of(src);
let mut shown: Option<(u64, Instant)> = None;
full(&from, &to, &ranges, len, &mut |done| {
let pct = done.min(total) * 100 / total;
let due = match shown {
None => true,
Some((p, t)) => p != pct && (pct == 100 || t.elapsed() >= Duration::from_secs(1)),
};
if due {
shown = Some((pct, Instant::now()));
progress(&format!(
"copying {name} in full ({short}): {pct}% of {}",
size(total)
));
full(
from,
to,
ranges,
len,
&mut |done| {
let pct = (done.min(total) * 100).checked_div(total).unwrap_or(100);
let due = match shown {
None => true,
Some((p, t)) => p != pct && (pct == 100 || t.elapsed() >= Duration::from_secs(1)),
};
if due {
shown = Some((pct, Instant::now()));
progress(&format!(
"copying {name} in full ({short}): {pct}% of {}",
size(total)
));
}
},
cancel,
)
}
/// Makes `dst`, a file that does not exist yet, a reflink or clone of `src`; else why not, in a
/// few words ("ext4 makes no reflinks"), and no `dst` is left.
pub fn reflink(src: &Path, dst: &Path) -> std::result::Result<(), String> {
match clone(src, dst) {
Ok(()) => Ok(()),
Err(e) => {
let _ = std::fs::remove_file(dst);
Err(Why::of(&e, src, dst).short())
}
})
.with_context(fail)
}
}
/// Whether a file in the directory `from` can be made a reflink or clone in the directory `to`,
/// tried with a file of a few bytes made for it and removed; else why not, as [`reflink`] says.
pub fn reflinks_between(from: &Path, to: &Path) -> std::result::Result<(), String> {
let tag = format!(".reims-ctl-reflink-{}", std::process::id());
let (a, b) = (from.join(&tag), to.join(format!("{tag}.copy")));
std::fs::write(&a, b"reflink").map_err(|e| format!("could not write {}: {e}", a.display()))?;
let r = reflink(&a, &b);
let _ = std::fs::remove_file(&a);
let _ = std::fs::remove_file(&b);
r
}
/// The bytes of `src` a full copy reads and writes: those of its parts that hold data, its holes
/// left out.
pub fn data_bytes(src: &Path) -> Result<u64> {
let f = File::open(src).with_context(|| format!("open {}", src.display()))?;
let len = f.metadata()?.len();
Ok(data_ranges(&f, len).iter().map(|(a, b)| b - a).sum())
}
/// A full copy of `src` to `dst`, a file that does not exist yet, where no reflink is made, `why`
/// in a few words ([`reflink`]): only the parts of `src` that hold data are read and written, and
/// its holes, and blocks of zeros, stay holes in `dst`. `progress` hears how far it is, as
/// [`file()`]'s full copy tells it; it stops once `cancel` is set. A copy that fails or stops
/// leaves no `dst`.
pub fn full_copy(
src: &Path,
dst: &Path,
why: &str,
progress: &mut dyn FnMut(&str),
cancel: &AtomicBool,
) -> Result<()> {
let fail = || format!("could not copy {} to {}", src.display(), dst.display());
let from = File::open(src).with_context(fail)?;
let len = from.metadata().with_context(fail)?.len();
let to = create(&from, dst).with_context(fail)?;
let ranges = data_ranges(&from, len);
let r = full_told(&from, &to, &ranges, len, why, src, progress, Some(cancel))
.and_then(|()| to.sync_all());
drop(to);
if let Err(e) = r {
let _ = std::fs::remove_file(dst);
if e.kind() == io::ErrorKind::Interrupted {
anyhow::bail!("the copy of {} was stopped", name_of(src));
}
return Err(e).with_context(fail);
}
Ok(())
}
/// Copies `ranges` of `from` to `to`, then makes `to` `len` bytes long; `copied` hears how many
/// bytes of the ranges are copied, from 0. Blocks of zeros are left holes, as `cp --sparse=always`
/// leaves them.
/// leaves them. Once `cancel` is set, it stops with an error of kind `Interrupted`.
fn full(
from: &File,
to: &File,
ranges: &[(u64, u64)],
len: u64,
copied: &mut dyn FnMut(u64),
cancel: Option<&AtomicBool>,
) -> io::Result<()> {
const BLOCK: usize = 4096;
let mut buf = vec![0u8; 1 << 20];
@@ -103,6 +212,9 @@ fn full(
for &(start, end) in ranges {
let mut at = start;
while at < end {
if cancel.is_some_and(|c| c.load(Ordering::SeqCst)) {
return Err(io::Error::new(io::ErrorKind::Interrupted, "stopped"));
}
let n = ((end - at) as usize).min(buf.len());
from.read_exact_at(&mut buf[..n], at)?;
// Each run of blocks not all zeros, written at once.
@@ -293,6 +405,47 @@ mod tests {
assert_eq!(refused.short(), "btrfs refused a reflink");
}
/// A refused reflink falls back to a full copy, the source's bytes and holes, whatever the
/// refusal's error, on any file system: one that makes none (ext4's `EOPNOTSUPP`, here as
/// the host's own code), one whose error names no reason of the list, and one with no OS
/// error at all. The refusal leaves its empty file behind, as Linux's does, which the full
/// copy writes over.
#[test]
fn a_refused_reflink_falls_back_to_a_full_copy_whatever_its_error() {
let d = dir(&std::env::temp_dir(), "refused");
let bytes = sparse_file(&d.join("src"), 4 << 20);
#[cfg(unix)]
const OTHER: i32 = libc::EINVAL;
// ERROR_INVALID_PARAMETER.
#[cfg(windows)]
const OTHER: i32 = 87;
type Refusal = fn() -> io::Error;
let unsupported: Refusal = || io::Error::from_raw_os_error(UNSUPPORTED[0]);
let refusals: [(Refusal, &str); 3] = [
(unsupported, "makes none"),
(|| io::Error::from_raw_os_error(OTHER), "refused one"),
(|| io::Error::other("no reflink here"), "refused one"),
];
for (i, (error, says)) in refusals.into_iter().enumerate() {
let dst = d.join(format!("copy-{i}"));
let refuse = |_: &Path, to: &Path| -> io::Result<()> {
std::fs::write(to, b"")?;
Err(error())
};
let mut seen = Vec::new();
copy_with(&d.join("src"), &dst, 0, &refuse, &mut |s| {
seen.push(s.to_string())
})
.unwrap();
assert_eq!(std::fs::read(&dst).unwrap(), bytes, "{i}");
let said = seen.first().map(String::as_str).unwrap_or("");
assert!(said.starts_with("copying src in full, "), "{i}: {seen:?}");
assert!(said.contains(says), "{i}: {said}");
assert!(seen.last().unwrap().contains("100% of"), "{i}: {seen:?}");
}
std::fs::remove_dir_all(&d).unwrap();
}
/// A path's file system is the last mount on the longest mount point above it, whose escapes
/// are undone.
#[test]
@@ -324,7 +477,7 @@ mod tests {
let to = create(&from, &d.join("dst")).unwrap();
let ranges = data_ranges(&from, len);
let mut seen = Vec::new();
full(&from, &to, &ranges, len, &mut |n| seen.push(n)).unwrap();
full(&from, &to, &ranges, len, &mut |n| seen.push(n), None).unwrap();
assert_eq!(std::fs::read(d.join("dst")).unwrap(), bytes);
#[cfg(unix)]
{
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -149,7 +149,7 @@ pub fn host_disks() -> Vec<HostDisk> {
/// link in `by_id`, with what `used` says the host uses it for. Left out: optical drives
/// (`sr`), floppies, read-only and empty devices, the kernel's own (zram, device-mapper, md,
/// RAM disks, which have no `device`), and loop devices without a file.
fn read_disks(sys: &Path, by_id: &Path, used: &HostUse) -> Vec<HostDisk> {
pub(crate) fn read_disks(sys: &Path, by_id: &Path, used: &HostUse) -> Vec<HostDisk> {
let Ok(dir) = std::fs::read_dir(sys.join("block")) else {
return Vec::new();
};
+42 -13
View File
@@ -10,7 +10,6 @@
use crate::ipsw;
use crate::paths;
use crate::vm::{Registry, Vm};
use anyhow::{Context, Result, bail};
use reims_restore::catalog;
use std::path::{Path, PathBuf};
@@ -111,7 +110,7 @@ pub fn delete(name: &str) -> Result<String> {
.into_iter()
.find(|i| i.name() == name)
.with_context(|| format!("no download is named {name}: reims-ctl downloads lists them"))?;
if let Some(vm) = used_by(&item.path) {
if let Some(vm) = used_by(&item.path, name)? {
bail!("{vm} boots from {name}: take it out first (reims-ctl eject {vm}), or delete {vm}");
}
if being_downloaded(&item.path) {
@@ -122,17 +121,17 @@ pub fn delete(name: &str) -> Result<String> {
Ok(format!("deleted {name}, freeing {}", size(item.bytes)))
}
/// The VM that boots from `path`, its installer, if any.
fn used_by(path: &Path) -> Option<String> {
/// The VM that boots from `path`, the download named `name`, its installer, if any; an error
/// where that can't be told ([`crate::runtime::other_using`]).
fn used_by(path: &Path, name: &str) -> Result<Option<String>> {
let same = |p: &Path| match (p.canonicalize(), path.canonicalize()) {
(Ok(a), Ok(b)) => a == b,
_ => p == path,
};
let reg = Registry::load().ok()?;
reg.vms.iter().find_map(|e| {
let vm = Vm::load(&e.dir).ok()?;
let installer = vm.config.q35.as_ref()?.installer.as_deref()?;
same(&vm.path(installer)).then(|| e.name.clone())
let whether = format!("a VM boots from {name}");
crate::runtime::other_using(None, &whether, |vm| {
let installer = vm.config.q35.as_ref().and_then(|q| q.installer.as_deref());
installer.is_some_and(|i| same(&vm.path(i)))
})
}
@@ -153,14 +152,15 @@ fn being_downloaded(path: &Path) -> bool {
let Ok(f) = std::fs::OpenOptions::new().read(true).open(&lock) else {
return false;
};
// flock(LOCK_EX | LOCK_NB) on Unix, LockFileEx on Windows, on a file this function holds:
// closing it lets go.
f.try_lock().is_err()
// On a file this function holds, which closing lets go of; a download that just ended holds
// its lock on for as long as a child its process forked does (try_lock_let_go).
!matches!(reims_restore::download::try_lock_let_go(&f), Ok(true))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::vm::{Registry, Vm};
#[test]
fn each_download_says_what_it_is() {
@@ -185,6 +185,27 @@ mod tests {
assert_eq!(size(950_000_000), "950 MB");
}
/// A download isn't deleted where the list of VMs can't be read, since it may name a VM that
/// boots from it: the refusal names the list's error.
#[test]
fn a_download_is_kept_where_the_list_of_vms_can_t_be_read() {
let _env = crate::testenv::Env::new("downloads-unread");
let [inst, _] = dirs();
std::fs::create_dir_all(&inst).unwrap();
let offline = "macOS-Tahoe-26.6.2-25G83-offline-installer.img";
std::fs::write(inst.join(offline), b"o").unwrap();
let list = paths::registry_file();
std::fs::create_dir_all(list.parent().unwrap()).unwrap();
std::fs::write(&list, b"[[vm]\n").unwrap();
let e = format!("{:#}", delete(offline).unwrap_err());
let said = format!(
"can't tell whether a VM boots from {offline}: the list of VMs can't be read (parse {}",
list.display()
);
assert!(e.starts_with(&said), "{e}");
assert!(inst.join(offline).exists());
}
/// The list holds both directories' files, but no hidden one; delete removes one, but not
/// one a VM boots from or one being downloaded.
#[test]
@@ -240,9 +261,17 @@ mod tests {
held.try_lock().unwrap();
let e = delete(part).unwrap_err().to_string();
assert!(e.contains("is being downloaded now"), "{e}");
// The download ends while a child its process forked holds the lock on, until it execs.
let child = held.try_clone().unwrap();
drop(held);
let exec = std::thread::spawn(move || {
std::thread::sleep(std::time::Duration::from_millis(100));
drop(child);
});
let deleted = delete(part);
exec.join().unwrap();
assert!(
delete(part)
deleted
.unwrap()
.starts_with(&format!("deleted {part}, freeing"))
);
+238 -11
View File
@@ -31,6 +31,18 @@
//! - a manifest given by its path (`--gpu FILE.json`), which may be a driver outside the
//! loader's search paths, or a second driver for a GPU the loader reaches by its own.
//!
//! **Two GPUs of the same IDs.** Two cards of one model have the same vendor and device IDs and
//! one driver's manifest, so those name neither. The probe reads each GPU's PCI address where its
//! driver lists `VK_EXT_pci_bus_info` ([`GpuInfo::pci`]), the list keeps each address apart
//! ([`from_probes`]), and such a GPU ([`GpuInfo::twin`]) is picked by its address: `DRI_PRIME=
//! pci-0000_02_00_0`, which Mesa's device-select layer reads (Mesa's documentation of
//! `DRI_PRIME`), and so does the library itself, on every OS (reims-vgpu-vulkan's
//! `device_choice`), with `VK_LOADER_DEVICE_SELECT` for its IDs and no `MESA_VK_DEVICE_SELECT`,
//! which the library reads before `DRI_PRIME` and whose IDs name the first of the two in the
//! loader's order ([`crate::vm::Gpu::pci`]).
//! **Seen** in a user's report: a host with two cards of one model listed one GPU, and its VM
//! could be given the second only through a variable of the user's own.
//!
//! **A probe past its manifest.** A manifest names one driver, so a probe that finds GPUs of
//! several drivers (by `VkPhysicalDeviceDriverProperties::driverID`, else by vendor) shows a
//! loader that did not keep to it, nor would keep a VM's process to it: its GPUs are named by
@@ -42,6 +54,22 @@
//! `MESA_VK_DEVICE_SELECT` itself (reims-vgpu-vulkan's `device_choice`), so IDs name the pick
//! wherever the loader runs. A VM an older reims-ctl gave a GPU so, under a manifest whose probe
//! now goes past it, is named by that GPU's IDs once ([`crate::migrate`], migration 6).
//!
//! **A VM's driver at its start.** The manifest a VM's settings name is a remembered answer, not
//! the host's: a driver update can move it. On Windows a GPU driver's manifest is in the
//! DriverStore, in a directory whose name carries a hash, which an update replaces, removing the
//! old one: a user's VM named Intel's manifest there by its path, and after an update of the
//! GPU's driver every start ended with "vkCreateInstance failed: Unable to find a Vulkan driver".
//! A VM's settings get such a path from a reims-ctl before migration 5's, a pick
//! by manifest (a CPU implementation, a GPU two drivers reach), `--gpu FILE.json`, or a copy of
//! another VM's settings. So each start of a VM whose GPU is named by its manifest alone asks the
//! host's manifests again, as the list does, before QEMU runs, and finds the GPU of its name and
//! device ID through a manifest of the stored one's file name ([`refind`]): where the stored one
//! is gone or offers it no more, the settings name the one that does, saved, and the start says
//! so; where none does, the start ends there, naming the GPU and how to pick another
//! ([`crate::runtime`], `refind_gpu`). A manifest given by its path and nothing else has nothing
//! to find again by: a start ends where the file is gone. Migrations 5 and 6 match a manifest by
//! its whole path, once, at an update; they do not see a path that moved.
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
@@ -77,6 +105,14 @@ pub struct GpuInfo {
pub driver_name: String,
#[serde(default)]
pub driver_info: String,
/// Its PCI address, `0000:02:00.0`, where the driver lists `VK_EXT_pci_bus_info`: none where
/// it does not.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub pci: Option<String>,
/// Whether another GPU of the list has its vendor and device IDs at another PCI address, so
/// that only its address names it (the module doc, "Two GPUs of the same IDs").
#[serde(default)]
pub twin: bool,
}
impl GpuInfo {
@@ -89,18 +125,23 @@ impl GpuInfo {
.file_name()
.map(|f| f.to_string_lossy().into_owned())
.unwrap_or_default();
format!("{} ({}, {file})", self.name, self.kind)
match (self.twin, &self.pci) {
(true, Some(pci)) => format!("{} ({}, {file}, at {pci})", self.name, self.kind),
_ => format!("{} ({}, {file})", self.name, self.kind),
}
}
/// The VM's settings for this GPU: named by its IDs, unless it is a CPU implementation or
/// another manifest reaches a GPU of the same IDs, which its driver's manifest names alone;
/// by its IDs wherever its probe went past its manifest (the module doc).
/// by its IDs wherever its probe went past its manifest (the module doc); and by its PCI
/// address too where another GPU of the list has its IDs.
pub fn to_config(&self) -> crate::vm::Gpu {
let by_ids = self.past_manifest || (self.kind != "cpu" && !self.shares_ids);
crate::vm::Gpu {
driver_file: Some(self.driver_file.clone()),
device_id: self.shares_driver.then_some(self.device_id),
select: by_ids.then(|| format!("{:04x}:{:04x}", self.vendor_id, self.device_id)),
pci: self.pci.clone().filter(|_| self.twin),
name: Some(self.name.clone()),
}
}
@@ -210,13 +251,15 @@ pub fn from_probes(probes: Vec<Vec<GpuInfo>>) -> Vec<GpuInfo> {
}
// Those found through their own manifest first. One GPU can be reached through two manifests
// (a 32-bit and a 64-bit one, say): keep the first. One found past its manifest is kept only
// where none kept has its IDs, which alone name it.
// where none kept has its IDs, which alone name it. A GPU at another PCI address than one
// kept is another GPU, whatever its IDs, name and manifest: two cards of one model.
found.sort_by_key(|g| g.past_manifest);
let mut gpus: Vec<GpuInfo> = Vec::new();
for g in found {
let ids = (g.vendor_id, g.device_id);
let seen = gpus.iter().any(|k| {
(k.vendor_id, k.device_id) == ids
&& !apart(k, &g)
&& (g.past_manifest
|| (k.name == g.name && k.driver_file.file_name() == g.driver_file.file_name()))
});
@@ -236,25 +279,32 @@ pub fn from_probes(probes: Vec<Vec<GpuInfo>>) -> Vec<GpuInfo> {
gpus
}
/// Marks each of `gpus` that shares its driver with another ([`GpuInfo::shares_driver`]), and each
/// whose IDs another manifest reaches too ([`GpuInfo::shares_ids`]).
/// Whether `a` and `b` are at two PCI addresses, so two GPUs, where both drivers give one.
fn apart(a: &GpuInfo, b: &GpuInfo) -> bool {
matches!((&a.pci, &b.pci), (Some(x), Some(y)) if x != y)
}
/// Marks each of `gpus` that shares its driver with another ([`GpuInfo::shares_driver`]), each
/// whose IDs another manifest reaches too ([`GpuInfo::shares_ids`]), and each whose IDs another
/// GPU at another PCI address has ([`GpuInfo::twin`]).
fn mark_shared(gpus: &mut [GpuInfo]) {
let shared: Vec<(bool, bool)> = gpus
let shared: Vec<(bool, bool, bool)> = gpus
.iter()
.map(|g| {
let others = || gpus.iter().filter(|o| !std::ptr::eq(*o, g));
let ids = (g.vendor_id, g.device_id);
let same_ids = |o: &GpuInfo| (o.vendor_id, o.device_id) == ids;
(
others().any(|o| o.driver_file == g.driver_file),
others().any(|o| {
o.driver_file != g.driver_file
&& (o.vendor_id, o.device_id) == (g.vendor_id, g.device_id)
}),
others().any(|o| o.driver_file != g.driver_file && same_ids(o) && !apart(o, g)),
others().any(|o| same_ids(o) && apart(o, g)),
)
})
.collect();
for (g, (driver, ids)) in gpus.iter_mut().zip(shared) {
for (g, (driver, ids, twin)) in gpus.iter_mut().zip(shared) {
g.shares_driver = driver;
g.shares_ids = ids;
g.twin = twin;
}
}
@@ -299,6 +349,55 @@ fn probe(exe: &std::path::Path, file: &std::path::Path) -> Vec<GpuInfo> {
.collect()
}
/// Where the driver of a VM's GPU named by its manifest alone ([`crate::vm::Gpu::select`] none)
/// is now, by [`refind`].
#[derive(Debug, PartialEq)]
pub enum Driver {
/// The stored manifest still offers the GPU.
Kept,
/// The stored manifest is gone or offers the GPU no more, and another of the same file name
/// offers it: as after a driver update on Windows, which puts the driver in a new directory
/// of the DriverStore, whose name carries a hash, and removes the old one.
Moved(PathBuf),
/// No manifest offers it.
Gone,
}
/// Where the driver of `g`, a VM's GPU named by its manifest ([`crate::vm::Gpu::driver_file`])
/// and name with no IDs, is in what the host's manifests' `probes` found now (in the loader's
/// order, [`probes`]): a GPU of `g`'s name and device ID (where it keeps one), through a manifest
/// of the stored one's file name, the stored one first. The stored path is a remembered answer:
/// the host's list says where the driver is (the module doc, "A VM's driver at its start").
pub fn refind(g: &crate::vm::Gpu, probes: &[Vec<GpuInfo>]) -> Driver {
let (Some(file), Some(name)) = (&g.driver_file, &g.name) else {
return Driver::Kept;
};
// Windows' paths are the same file whatever their case and separators.
let fold = |p: &std::path::Path| {
let s = p.to_string_lossy();
if cfg!(windows) {
s.replace('/', "\\").to_lowercase()
} else {
s.into_owned()
}
};
let file_name = |p: &std::path::Path| p.file_name().map(|n| fold(std::path::Path::new(n)));
let offering: Vec<&GpuInfo> = (probes.iter().flatten())
.filter(|f| {
&f.name == name
&& g.device_id.is_none_or(|id| id == f.device_id)
&& file_name(&f.driver_file) == file_name(file)
})
.collect();
if offering.iter().any(|f| fold(&f.driver_file) == fold(file)) {
return Driver::Kept;
}
match offering.first() {
Some(f) => Driver::Moved(f.driver_file.clone()),
None => Driver::Gone,
}
}
/// `reims-ctl __vulkan-probe`: one JSON line per physical device the loader finds.
#[cfg(any(target_os = "linux", windows))]
pub fn probe_main() -> i32 {
@@ -356,6 +455,8 @@ pub fn probe_main() -> i32 {
driver_version: p.driver_version,
driver_name,
driver_info,
pci: pci_address(&instance, pd),
twin: false,
};
println!("{}", serde_json::to_string(&info).unwrap());
}
@@ -365,6 +466,31 @@ pub fn probe_main() -> i32 {
0
}
/// `pd`'s PCI address, `0000:02:00.0`, where its driver lists `VK_EXT_pci_bus_info`.
#[cfg(any(target_os = "linux", windows))]
fn pci_address(instance: &ash::Instance, pd: ash::vk::PhysicalDevice) -> Option<String> {
use ash::vk;
// SAFETY: `pd` is the instance's; the structures live across each call.
unsafe {
let name = ash::ext::pci_bus_info::NAME;
let lists = instance
.enumerate_device_extension_properties(pd)
.ok()?
.iter()
.any(|e| e.extension_name_as_c_str() == Ok(name));
if !lists {
return None;
}
let mut bus = vk::PhysicalDevicePCIBusInfoPropertiesEXT::default();
let mut p2 = vk::PhysicalDeviceProperties2::default().push_next(&mut bus);
instance.get_physical_device_properties2(pd, &mut p2);
Some(format!(
"{:04x}:{:02x}:{:02x}.{:x}",
bus.pci_domain, bus.pci_bus, bus.pci_device, bus.pci_function
))
}
}
#[cfg(not(any(target_os = "linux", windows)))]
pub fn probe_main() -> i32 {
1
@@ -388,9 +514,59 @@ mod tests {
driver_version: 0,
driver_name: String::new(),
driver_info: String::new(),
pci: None,
twin: false,
}
}
/// A VM's GPU named by its manifest alone finds its driver again by its name, device ID and
/// manifest's file name: where it is, kept; in another directory, as a driver update on
/// Windows moves it, moved; nowhere, gone. Another GPU of the manifest, or another manifest
/// for the same GPU, is not it.
#[test]
fn a_vm_finds_its_gpus_driver_again() {
let (old, new) = (
"/ds/iigd_dch.inf_amd64_0a1b/igvk64.json",
"/ds/iigd_dch.inf_amd64_9f8e/igvk64.json",
);
let uhd = "Intel(R) UHD Graphics 630";
let vm = crate::vm::Gpu {
driver_file: Some(old.into()),
device_id: None,
select: None,
pci: None,
name: Some(uhd.into()),
};
let nv = gpu(
"GTX 1650 Ti",
(0x10de, 0x1f95),
"discrete",
"/nv/nv-vk64.json",
);
let at = |file: &str| vec![gpu(uhd, (0x8086, 0x3e9b), "integrated", file)];
assert_eq!(refind(&vm, &[vec![nv.clone()], at(old)]), Driver::Kept);
assert_eq!(
refind(&vm, &[vec![nv.clone()], at(new)]),
Driver::Moved(new.into())
);
assert_eq!(refind(&vm, &[at(new), at(old)]), Driver::Kept);
assert_eq!(refind(&vm, &[vec![nv.clone()]]), Driver::Gone);
assert_eq!(refind(&vm, &[]), Driver::Gone);
// Another manifest's file name, or another device ID, is another driver or GPU.
assert_eq!(refind(&vm, &[at("/ds/x/igvk32.json")]), Driver::Gone);
let with_id = crate::vm::Gpu {
device_id: Some(0x3e92),
..vm.clone()
};
assert_eq!(refind(&with_id, &[at(new)]), Driver::Gone);
// Nothing to find it by: as it is.
let typed = crate::vm::Gpu {
name: None,
..vm.clone()
};
assert_eq!(refind(&typed, &[]), Driver::Kept);
}
/// RADV drives two GPUs, and AMDVLK reaches one of them too; NVIDIA's driver and lavapipe
/// one each.
#[test]
@@ -451,6 +627,7 @@ mod tests {
driver_file: Some("/icd/nvidia.json".into()),
device_id: None,
select: Some("10de:2204".into()),
pci: None,
name: Some("NVIDIA GeForce RTX 3090".into()),
}
);
@@ -470,6 +647,56 @@ mod tests {
assert_eq!(small.to_config().selected().unwrap(), Some((0x1af4, 0x50)));
}
/// Two cards of one model, the same IDs, name and manifest at two PCI addresses, are two
/// GPUs of the list, each picked by its address and labelled with it; a probe that found
/// them again past its manifest, at their addresses, adds neither again; and where the
/// driver gives no address, the two are one entry, as before addresses were read. Seen on a
/// host with two FirePro D700s (1002:6798), which the list gave as one.
#[test]
fn two_cards_of_one_model_are_listed_and_picked_by_their_addresses() {
let d700 = |file: &str, pci: Option<&str>| GpuInfo {
pci: pci.map(String::from),
..gpu(
"AMD Radeon R9 200 / HD 7900 Series (RADV TAHITI)",
(0x1002, 0x6798),
"discrete",
file,
)
};
let (radv, lvp) = ("/icd/radeon_icd.x86_64.json", "/icd/lvp_icd.x86_64.json");
let (a, b) = ("0000:02:00.0", "0000:06:00.0");
let list = from_probes(vec![
vec![d700(radv, Some(a)), d700(radv, Some(b))],
vec![
gpu("llvmpipe", (0x10005, 0), "cpu", lvp),
d700(lvp, Some(a)),
d700(lvp, Some(b)),
],
]);
assert_eq!(list.len(), 3, "{list:?}");
assert_eq!(list[2].name, "llvmpipe");
for g in &list[..2] {
assert!(g.twin, "{g:?}");
assert_eq!(g.driver_file.to_str(), Some(radv));
}
let (label, want) = (list[1].label(), format!("x86_64.json, at {b})"));
assert!(label.ends_with(&want), "{label}");
let pick = list[1].to_config();
assert_eq!(pick.pci.as_deref(), Some(b));
assert_eq!(pick.select.as_deref(), Some("1002:6798"));
let prime = pick.dri_prime().unwrap();
assert_eq!(prime.as_deref(), Some("pci-0000_06_00_0"));
assert_eq!(list[0].to_config().pci.as_deref(), Some(a));
// One card alone keeps no address in its settings: its IDs name it.
let one = from_probes(vec![vec![d700(radv, Some(a))]]);
assert!(!one[0].twin);
assert_eq!(one[0].to_config().pci, None);
// No address from the driver: the two are one entry, named by their IDs.
let blind = from_probes(vec![vec![d700(radv, None), d700(radv, None)]]);
assert_eq!(blind.len(), 1);
assert_eq!(blind[0].to_config().pci, None);
}
/// A probe that found several drivers' GPUs went past its manifest: its GPUs are named by
/// their IDs, and one a probe of its own manifest found is listed from that probe. Seen on a
/// Windows host, where the probe of Intel's manifest found the GTX too and saved it under
+484 -21
View File
@@ -5,15 +5,16 @@
//! - Linux and Windows on x86-64: [`Profile::Q35X86_64`], `q35` booted through OpenCore, with
//! reims-vgpu's own GPU device, on KVM on Linux and on the Windows Hypervisor Platform (WHPX)
//! on Windows;
//! - an arm64 Mac, arm64 Linux and Linux on x86-64: [`Profile::VmappleArm64`], QEMU's `vmapple`
//! booted by Ambrosia (ambrosia.rs), with reims-vgpu's own GPU device, whose VMs reims-ctl
//! makes by restoring macOS from an IPSW (restore.rs): on Hypervisor.framework (HVF) on a Mac,
//! on KVM on arm64 Linux, and emulated by QEMU's TCG on x86-64, where an arm64 guest runs
//! several times slower than on an arm64 host. On Linux on x86-64 it is the second profile, an
//! IPSW's, and q35 the default.
//! - an arm64 Mac, arm64 Linux, and Linux and Windows on x86-64: [`Profile::VmappleArm64`],
//! QEMU's `vmapple` booted by Ambrosia (ambrosia.rs), with reims-vgpu's own GPU device, whose
//! VMs reims-ctl makes by restoring macOS from an IPSW (restore.rs): on Hypervisor.framework
//! (HVF) on a Mac, on KVM on arm64 Linux, and emulated by QEMU's TCG on x86-64, where an arm64
//! guest runs several times slower than on an arm64 host. On x86-64 it is the second profile,
//! an IPSW's, and q35 the default. Of Windows we have only a contributor's report (PR 203):
//! macOS 27.2.1 booted to its desktop on Windows 11, on an Intel Core i7-12700H with an RTX
//! 3060 Laptop GPU; the lab has run none there (docs/qemu.md, "arm64 guests").
//!
//! Any other host runs none ([`UNSUPPORTED`]). Windows on x86-64 runs no arm64 VM: its QEMU is
//! built for x86-64 guests alone (scripts/install-ctl.sh).
//! Any other host runs none ([`UNSUPPORTED`]).
//!
//! Another host or guest architecture is another profile (x86-64 guests on an Intel Mac would be
//! `q35` on HVF, without the memfd RAM only Linux has): add it here and in `qemu.rs`.
@@ -24,7 +25,7 @@ use std::fmt;
/// What reims-ctl tells a host it runs no VMs on, for a create or a start there.
pub const UNSUPPORTED: &str = "reims-ctl runs x86-64 VMs on Linux and Windows x86-64 hosts, \
and arm64 VMs on arm64 Macs, arm64 Linux and Linux on x86-64";
and arm64 VMs on arm64 Macs, arm64 Linux, and x86-64 Linux and Windows";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Os {
@@ -105,10 +106,268 @@ pub fn avx512_xstate_offsets() -> Option<[u32; 3]> {
None
}
/// The first macOS whose x86-64 guests need AVX2 of the host's CPU, which a KVM or WHPX guest's
/// CPU has only where the host's has: QEMU drops a feature the host lacks from any CPU model.
/// **Measured** 2026-12-03 under KVM on a Core i9-13900H, with AVX2 hidden from the guest
/// (potluck jobs m3-max-86342 and m3-max-86386): macOS 13.7.8, 14.8.9, 15.8.2 and 26.7.2 on
/// reims-ctl's Skylake-Client-noTSX-IBRS line with `-avx2`, and 26.7.2 also on that line with
/// what an Ivy Bridge lacks hidden too (FMA, BMI1, BMI2, MOVBE, LZCNT, RDSEED, ADX, SMAP,
/// INVPCID, XSAVEC and PCID) and on IvyBridge-IBRS. In every boot the kernel starts and mounts
/// the system, then launchd cannot load `/usr/lib/libSystem.B.dylib` ("no dyld cache": the
/// system's shared cache is built for CPUs with AVX2 alone), the kernel panics ("initproc failed
/// to start") and the VM restarts, over and over. A user's report of macOS 26.7.3 on a Xeon E5
/// v2 (Ivy Bridge-EP, no AVX2) stopping at OpenCore's handoff did not reproduce. No macOS before
/// 13 was booted without AVX2 here, so none is refused: the bound moves only on evidence. A
/// create refuses such a VM, and doctor names the CPU; a start refuses nothing, since a user's
/// own CPU arguments and kexts run such a macOS on such a CPU, so a VM of it made elsewhere
/// still restarts at its first process with no word of ours.
pub const AVX2_FROM_MACOS: u32 = 13;
/// Whether the host's CPU runs AVX2 code, as CPUID and the OS's saved state say
/// (`is_x86_feature_detected!`); None on a host other than x86-64, whose x86-64 VMs reims-ctl
/// does not make.
pub fn has_avx2() -> Option<bool> {
#[cfg(test)]
if let Some(avx2) = tests::AVX2.with(|a| *a.borrow()) {
return avx2;
}
cpu_has_avx2()
}
#[cfg(target_arch = "x86_64")]
fn cpu_has_avx2() -> Option<bool> {
Some(std::arch::is_x86_feature_detected!("avx2"))
}
#[cfg(not(target_arch = "x86_64"))]
fn cpu_has_avx2() -> Option<bool> {
None
}
/// The CPU model an x86-64 guest's `-cpu` names in place of reims-ctl's own
/// (`vm::default_cpu_model`, Skylake-Client-noTSX-IBRS) on a host whose CPU lacks AVX2
/// ([`model_without_avx2`]).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct HostModel {
/// QEMU's model: the newest of [`model_without_avx2`]'s whose features the host's CPU has.
pub name: &'static str,
/// `+feature`, by QEMU's name, for each feature of reims-ctl's own model that `name` lacks
/// and the host's CPU has, in [`model_without_avx2`]'s order.
pub flags: Vec<String>,
/// The `+feature`s of reims-ctl's own flags (`vm::default_cpu_flags`) whose feature the
/// host's CPU lacks: the line leaves them out of the VM's flags.
pub drop: Vec<String>,
}
/// What an x86-64 guest's CPU line names on a host whose CPU has the features `has` answers yes for
/// (QEMU's names), where reims-ctl's own model, Skylake-Client-noTSX-IBRS, would name a CPU the
/// host is not: None where the host has AVX2, and the VM's model stays. Otherwise a line that names
/// no model the host's CPU is not and no feature it lacks: the newest of IvyBridge, SandyBridge,
/// Westmere and Nehalem whose features the host has (`-IBRS`, its IBRS variant, where the host has
/// IBRS), then `+` each feature of Skylake-Client-noTSX-IBRS that the model lacks and the host has,
/// and reims-ctl's own flags without those whose feature the host lacks ([`HostModel::drop`]). The
/// guest's feature bits are then what Skylake-Client-noTSX-IBRS gave it on that host, where QEMU
/// dropped what the host lacks with `check`'s warning, but for KVM's own x2APIC, TSC deadline timer
/// and ARAT on a CPU whose CPUID lacks them. Nehalem is the floor: an older CPU gets its name. An
/// AMD CPU gets the Intel model whose features it has, since no Mac has an AMD CPU. The guest's
/// family and model are OpenCore's leaf 1 spoof in an image reims-util makes (docs/qemu.md, "x86-64
/// macOS guests: the CPU model"); macOS 13 and later on such a host still stop at their first
/// process ([`AVX2_FROM_MACOS`]).
pub fn model_without_avx2(has: &dyn Fn(&str) -> bool) -> Option<HostModel> {
if has("avx2") {
return None;
}
// Newest first: each model, its IBRS variant, and the features it has beyond the next; a
// host has a model where it has those of the model and of every one after it.
const MODELS: [(&str, &str, &[&str]); 4] = [
(
"IvyBridge",
"IvyBridge-IBRS",
&["f16c", "rdrand", "fsgsbase", "smep", "erms"],
),
(
"SandyBridge",
"SandyBridge-IBRS",
&[
"avx",
"xsave",
"xsaveopt",
"rdtscp",
"x2apic",
"tsc-deadline",
],
),
("Westmere", "Westmere-IBRS", &["aes", "pclmulqdq", "arat"]),
("Nehalem", "Nehalem-IBRS", &[]),
];
// Skylake-Client-noTSX-IBRS's features beyond IvyBridge's, but for AVX2, which the host
// lacks, and TSX, which the model leaves out.
const SKYLAKES: [&str; 13] = [
"pcid",
"fma",
"movbe",
"bmi1",
"bmi2",
"abm",
"3dnowprefetch",
"invpcid",
"rdseed",
"adx",
"smap",
"xsavec",
"xgetbv1",
];
let i = (0..MODELS.len()).find(|&i| {
MODELS[i..]
.iter()
.all(|(_, _, needs)| needs.iter().all(|f| has(f)))
})?;
let (plain, ibrs, _) = MODELS[i];
let lacks = SKYLAKES
.iter()
.chain(MODELS[..i].iter().flat_map(|(_, _, needs)| needs.iter()));
let flags = lacks.filter(|f| has(f)).map(|f| format!("+{f}")).collect();
let drop = crate::vm::default_cpu_flags()
.split(',')
.filter(|f| f.strip_prefix('+').is_some_and(|f| !has(f)))
.map(String::from)
.collect();
Some(HostModel {
name: if has("spec-ctrl") { ibrs } else { plain },
flags,
drop,
})
}
/// [`model_without_avx2`] of this host's CPU, by [`has_avx2`] and CPUID: None on a CPU with
/// AVX2, and on a host other than x86-64.
pub fn host_model_without_avx2() -> Option<HostModel> {
if has_avx2() != Some(false) {
return None;
}
model_without_avx2(&|f| f != "avx2" && cpuid_has(f))
}
/// Whether CPUID gives this host's CPU `feature`, by QEMU's name: one of those
/// [`model_without_avx2`] asks of a host; false for another.
#[cfg(target_arch = "x86_64")]
fn cpuid_has(feature: &str) -> bool {
use std::arch::x86_64::{__cpuid, __cpuid_count};
// The leaf, its subleaf, the register (EAX 0, EBX 1, ECX 2, EDX 3) and the bit.
let (leaf, sub, reg, bit): (u32, u32, usize, u32) = match feature {
"pclmulqdq" => (1, 0, 2, 1),
"ssse3" => (1, 0, 2, 9),
"fma" => (1, 0, 2, 12),
"pcid" => (1, 0, 2, 17),
"sse4.2" => (1, 0, 2, 20),
"x2apic" => (1, 0, 2, 21),
"movbe" => (1, 0, 2, 22),
"popcnt" => (1, 0, 2, 23),
"tsc-deadline" => (1, 0, 2, 24),
"aes" => (1, 0, 2, 25),
"xsave" => (1, 0, 2, 26),
"avx" => (1, 0, 2, 28),
"f16c" => (1, 0, 2, 29),
"rdrand" => (1, 0, 2, 30),
"fsgsbase" => (7, 0, 1, 0),
"bmi1" => (7, 0, 1, 3),
"smep" => (7, 0, 1, 7),
"bmi2" => (7, 0, 1, 8),
"erms" => (7, 0, 1, 9),
"invpcid" => (7, 0, 1, 10),
"rdseed" => (7, 0, 1, 18),
"adx" => (7, 0, 1, 19),
"smap" => (7, 0, 1, 20),
"spec-ctrl" => (7, 0, 3, 26),
"arat" => (6, 0, 0, 2),
"xsaveopt" => (0xd, 1, 0, 0),
"xsavec" => (0xd, 1, 0, 1),
"xgetbv1" => (0xd, 1, 0, 2),
"abm" => (0x8000_0001, 0, 2, 5),
"3dnowprefetch" => (0x8000_0001, 0, 2, 8),
"rdtscp" => (0x8000_0001, 0, 3, 27),
_ => return false,
};
if __cpuid(leaf & 0x8000_0000).eax < leaf {
return false;
}
let r = __cpuid_count(leaf, sub);
([r.eax, r.ebx, r.ecx, r.edx][reg] >> bit) & 1 == 1
}
#[cfg(not(target_arch = "x86_64"))]
fn cpuid_has(_feature: &str) -> bool {
false
}
/// Why an x86-64 VM of macOS `major` does not run on this host, where that macOS needs AVX2
/// ([`AVX2_FROM_MACOS`]) and the host's CPU has none; None where it runs.
pub fn without_avx2(major: u32) -> Option<String> {
if major < AVX2_FROM_MACOS {
return None;
}
no_avx2(&format!("x86-64 macOS {major} needs"))
}
/// Why no x86-64 macOS from [`AVX2_FROM_MACOS`] on runs on this host, whose CPU has no AVX2:
/// doctor's cpu line. None where they run.
pub fn without_avx2_from() -> Option<String> {
no_avx2(&format!("x86-64 macOS {AVX2_FROM_MACOS} and later need"))
}
/// The reason [`without_avx2`] and [`without_avx2_from`] give, after `needs` ("x86-64 macOS 13
/// needs"), where the host's CPU has no AVX2.
fn no_avx2(needs: &str) -> Option<String> {
if has_avx2() != Some(false) {
return None;
}
let cpu = cpu_brand().map(|b| format!(", {b},")).unwrap_or_default();
Some(format!(
"{needs} a CPU with AVX2, and this host's CPU{cpu} has none: the system libraries are \
built for CPUs with AVX2 alone, so the first process cannot start, and the VM restarts \
over and over"
))
}
/// The host CPU's brand string, as CPUID's leaves 0x80000002 to 0x80000004 give it, without the
/// spaces and NULs around it: "13th Gen Intel(R) Core(TM) i9-13900H", "AMD Ryzen 7 7840HS w/
/// Radeon 780M Graphics". None on a host other than x86-64, or a CPU without the leaves.
pub fn cpu_brand() -> Option<String> {
#[cfg(test)]
if let Some(brand) = tests::BRAND.with(|b| b.borrow().clone()) {
return brand;
}
cpuid_brand()
}
#[cfg(target_arch = "x86_64")]
fn cpuid_brand() -> Option<String> {
use std::arch::x86_64::__cpuid;
if __cpuid(0x8000_0000).eax < 0x8000_0004 {
return None;
}
let bytes: Vec<u8> = (0x8000_0002..=0x8000_0004)
.flat_map(|leaf| {
let r = __cpuid(leaf);
[r.eax, r.ebx, r.ecx, r.edx]
.into_iter()
.flat_map(u32::to_le_bytes)
})
.collect();
let brand = String::from_utf8_lossy(&bytes);
let brand = brand.trim_matches(|c: char| c == '\0' || c.is_whitespace());
(!brand.is_empty()).then(|| brand.to_string())
}
#[cfg(not(target_arch = "x86_64"))]
fn cpuid_brand() -> Option<String> {
None
}
/// Whether a window can open for a QEMU run with `env` over this process's environment: it names
/// a Wayland compositor or an X server. Without one, QEMU's GTK window ends QEMU as it starts,
/// where the library's runs headless.
#[cfg(unix)]
#[cfg(all(unix, not(target_os = "macos")))]
pub fn has_screen(env: &BTreeMap<String, String>) -> bool {
["WAYLAND_DISPLAY", "DISPLAY"]
.iter()
@@ -118,6 +377,15 @@ pub fn has_screen(env: &BTreeMap<String, String>) -> bool {
})
}
/// Whether a window can open for a QEMU run: on a Mac, this process's security session reaches
/// the window server, as a signed-in user's does and an SSH login's does not
/// ([`crate::os::session_has_graphics`]). A VM's variables name no screen there: AppKit reads
/// neither X's nor Wayland's.
#[cfg(target_os = "macos")]
pub fn has_screen(_env: &BTreeMap<String, String>) -> bool {
crate::os::session_has_graphics()
}
/// Whether a window can open for a QEMU run: on Windows, this process's window station is the
/// one a signed-in user's desktop shows, as it is not for a service's or an SSH login's.
#[cfg(windows)]
@@ -155,8 +423,7 @@ pub enum Profile {
impl Profile {
pub fn supported_on(host: Host) -> &'static [Profile] {
match (host.os, host.arch) {
(Os::Linux, Arch::X86_64) => &[Profile::Q35X86_64, Profile::VmappleArm64],
(Os::Windows, Arch::X86_64) => &[Profile::Q35X86_64],
(Os::Linux | Os::Windows, Arch::X86_64) => &[Profile::Q35X86_64, Profile::VmappleArm64],
(Os::Mac | Os::Linux, Arch::Aarch64) => &[Profile::VmappleArm64],
_ => &[],
}
@@ -187,6 +454,7 @@ impl Profile {
match self {
Profile::Q35X86_64 if cfg!(windows) => "qemu-system-x86_64.exe",
Profile::Q35X86_64 => "qemu-system-x86_64",
Profile::VmappleArm64 if cfg!(windows) => "qemu-system-aarch64.exe",
Profile::VmappleArm64 => "qemu-system-aarch64",
}
}
@@ -230,10 +498,10 @@ impl Profile {
/// Whether QEMU takes all of the guest's RAM from the host as it starts, so a host short of
/// memory ends a start: the x86-64 machine's memfd is allocated whole on Linux (`prealloc`,
/// [`crate::qemu`]'s module doc), and its section committed whole on Windows. The arm64
/// machine's memfd is allocated as the guest touches it.
/// [`crate::qemu`]'s module doc), and either machine's section committed whole on Windows.
/// The arm64 machine's memfd is allocated as the guest touches it.
pub fn ram_whole_at_start(self, host: Host) -> bool {
self == Profile::Q35X86_64 && (self.memfd_ram(host) || self.section_ram(host))
self.section_ram(host) || (self == Profile::Q35X86_64 && self.memfd_ram(host))
}
/// Whether a Vulkan GPU can be chosen: the library runs on the host's Vulkan GPUs on Linux
@@ -250,9 +518,172 @@ impl fmt::Display for Profile {
}
#[cfg(test)]
mod tests {
pub(crate) mod tests {
use super::*;
thread_local! {
/// What [`cpu_brand`] answers on this test's thread, where set: [`with_cpu_brand`].
pub(crate) static BRAND: std::cell::RefCell<Option<Option<String>>> =
const { std::cell::RefCell::new(None) };
}
thread_local! {
/// What [`has_avx2`] answers on this test's thread, where set: [`with_avx2`].
pub(crate) static AVX2: std::cell::RefCell<Option<Option<bool>>> =
const { std::cell::RefCell::new(None) };
}
/// Runs `f` with [`has_avx2`] answering `avx2` on this thread: a fake of the CPU's features.
pub(crate) fn with_avx2<T>(avx2: Option<bool>, f: impl FnOnce() -> T) -> T {
let old = AVX2.with(|a| a.replace(Some(avx2)));
let out = f();
AVX2.with(|a| *a.borrow_mut() = old);
out
}
/// An x86-64 VM of macOS 13 or later is refused on a CPU without AVX2, naming AVX2, the CPU
/// and what needs it, the system libraries; macOS 12, a CPU with AVX2 and a host other than
/// x86-64 are not. Doctor's reason names every macOS from 13.
#[test]
fn macos_13_and_later_is_refused_on_a_cpu_without_avx2() {
let ivy = "Intel(R) Xeon(R) CPU E5-2697 v2 @ 2.70GHz";
for major in [13, 14, 15, 26] {
let why = with_cpu_brand(Some(ivy), || with_avx2(Some(false), || without_avx2(major)));
let why = why.expect("refused");
assert!(
why.starts_with(&format!("x86-64 macOS {major} needs a CPU with AVX2")),
"{why}"
);
assert!(
why.contains("system libraries are built for CPUs with AVX2 alone"),
"{why}"
);
let cpu = format!("this host's CPU, {ivy}, has none");
assert!(why.contains(&cpu), "{why}");
}
assert_eq!(with_avx2(Some(false), || without_avx2(12)), None);
assert_eq!(with_avx2(Some(true), || without_avx2(13)), None);
assert_eq!(with_avx2(None, || without_avx2(26)), None);
let unnamed = with_cpu_brand(None, || with_avx2(Some(false), || without_avx2(26)));
assert!(unnamed.unwrap().contains("this host's CPU has none"));
let from = with_avx2(Some(false), without_avx2_from).expect("refused");
assert!(
from.starts_with("x86-64 macOS 13 and later need a CPU with AVX2"),
"{from}"
);
assert_eq!(with_avx2(Some(true), without_avx2_from), None);
}
/// On a host whose CPU lacks AVX2 the guest's CPU names the newest model the host's CPU has
/// every feature of, its IBRS variant where the host has IBRS, adds each feature of
/// reims-ctl's own model that the host has and that model lacks, and leaves out reims-ctl's
/// own flags whose feature the host lacks: nothing on the line is a feature the host lacks.
/// A host with AVX2 keeps reims-ctl's model. The hosts are CPUs without AVX2, their features
/// from Intel's and AMD's lists: an Ivy Bridge-EP Xeon, a Sandy Bridge-EP Xeon, an AMD FX
/// (Piledriver, with no x2APIC, TSC deadline timer or IBRS), a Pentium Gold of the Coffee
/// Lake generation, which has no AVX, and a Core i7 of the Nehalem generation.
#[test]
fn a_host_without_avx2_gets_the_newest_model_it_is() {
let model = |has: &[&str]| model_without_avx2(&|f| has.contains(&f)).unwrap();
let flags = |m: &HostModel| m.flags.join(",");
let drop = |m: &HostModel| m.drop.join(",");
let nehalem = ["ssse3", "sse4.2", "popcnt", "rdtscp"];
let westmere = [&nehalem[..], &["aes", "pclmulqdq", "arat", "spec-ctrl"]].concat();
let sandy = [
&westmere[..],
&["avx", "xsave", "xsaveopt", "x2apic", "tsc-deadline", "pcid"],
]
.concat();
let ivy_ep = [&sandy[..], &["f16c", "rdrand", "fsgsbase", "smep", "erms"]].concat();
let ivy = model(&ivy_ep);
assert_eq!(ivy.name, "IvyBridge-IBRS");
assert_eq!(flags(&ivy), "+pcid");
assert_eq!(drop(&ivy), "");
let sandy = model(&sandy);
assert_eq!(sandy.name, "SandyBridge-IBRS");
assert_eq!(flags(&sandy), "+pcid");
assert_eq!(drop(&sandy), "");
let fx = [
&nehalem[..],
&[
"aes",
"pclmulqdq",
"arat",
"avx",
"xsave",
"xsaveopt",
"f16c",
],
&["fma", "bmi1", "abm", "3dnowprefetch"],
]
.concat();
let fx = model(&fx);
assert_eq!(fx.name, "Westmere");
assert_eq!(
flags(&fx),
"+fma,+bmi1,+abm,+3dnowprefetch,+f16c,+avx,+xsave,+xsaveopt,+rdtscp"
);
assert_eq!(drop(&fx), "");
let pentium = [
&westmere[..],
&[
"x2apic",
"tsc-deadline",
"pcid",
"movbe",
"rdrand",
"rdseed",
],
&[
"fsgsbase",
"smep",
"smap",
"erms",
"invpcid",
"adx",
"3dnowprefetch",
],
&["xsave", "xsaveopt", "xsavec", "xgetbv1"],
]
.concat();
let pentium = model(&pentium);
assert_eq!(pentium.name, "Westmere-IBRS");
assert_eq!(
flags(&pentium),
"+pcid,+movbe,+3dnowprefetch,+invpcid,+rdseed,+adx,+smap,+xsavec,+xgetbv1,\
+rdrand,+fsgsbase,+smep,+erms,+xsave,+xsaveopt,+rdtscp,+x2apic,+tsc-deadline"
);
assert_eq!(drop(&pentium), "+avx");
let nehalem = model(&nehalem);
assert_eq!(nehalem.name, "Nehalem");
assert_eq!(flags(&nehalem), "+rdtscp");
assert_eq!(drop(&nehalem), "+avx,+aes,+xsave,+xsaveopt");
let haswell = [&ivy_ep[..], &["avx2", "fma", "bmi1", "bmi2", "movbe"]].concat();
assert_eq!(model_without_avx2(&|f| haswell.contains(&f)), None);
}
/// Runs `f` with [`cpu_brand`] answering `brand` on this thread.
pub(crate) fn with_cpu_brand<T>(brand: Option<&str>, f: impl FnOnce() -> T) -> T {
let old = BRAND.with(|b| b.replace(Some(brand.map(String::from))));
let out = f();
BRAND.with(|b| *b.borrow_mut() = old);
out
}
/// The brand string is CPUID's, with the padding Intel's older CPUs put before it gone; a
/// host other than x86-64 has none.
#[test]
fn the_cpu_brand_is_cpuids_trimmed() {
let brand = cpuid_brand();
if cfg!(target_arch = "x86_64") {
let b = brand.expect("an x86-64 CPU names itself");
assert_eq!(b, b.trim(), "{b:?}");
assert!(!b.contains('\0'), "{b:?}");
} else {
assert_eq!(brand, None);
}
}
/// Linux on x86-64 runs x86-64 guests on KVM in memfd RAM, and arm64 guests on vmapple under
/// TCG; an arm64 Mac and arm64 Linux run arm64 guests on vmapple, under HVF and KVM; an Intel
/// Mac, Windows on arm64 and any other host run none.
@@ -307,7 +738,14 @@ mod tests {
assert_eq!(arm.accel_arg(arm_linux), "kvm");
assert!(arm.memfd_ram(arm_linux) && arm.gpu_choice(arm_linux));
assert!(arm.describe(arm_linux).ends_with("KVM)"));
assert_eq!(arm.qemu_binary(), "qemu-system-aarch64");
assert_eq!(
arm.qemu_binary(),
if cfg!(windows) {
"qemu-system-aarch64.exe"
} else {
"qemu-system-aarch64"
}
);
for (os, arch) in [
(Os::Mac, Arch::X86_64),
(Os::Windows, Arch::Aarch64),
@@ -317,8 +755,8 @@ mod tests {
}
}
/// Windows on x86-64 runs x86-64 guests on WHPX, in RAM of a shared section rather than a
/// memfd, with a Vulkan GPU to choose.
/// Windows on x86-64 runs x86-64 guests on WHPX and arm64 guests under TCG, each in RAM of a
/// shared section rather than a memfd, with a Vulkan GPU to choose.
#[test]
fn windows_on_x86_64_runs_vms_on_whpx() {
let windows = Host {
@@ -326,16 +764,24 @@ mod tests {
arch: Arch::X86_64,
};
let q35 = Profile::Q35X86_64;
assert_eq!(Profile::supported_on(windows), [q35]);
let arm = Profile::VmappleArm64;
assert_eq!(Profile::supported_on(windows), [q35, arm]);
assert_eq!(windows.default_profile(), Some(q35));
assert_eq!(q35.accel(windows), "whpx");
assert!(q35.section_ram(windows) && !q35.memfd_ram(windows));
assert!(q35.ram_whole_at_start(windows));
assert!(q35.gpu_choice(windows));
assert!(q35.describe(windows).ends_with("WHPX)"));
assert_eq!(arm.accel(windows), "tcg");
assert_eq!(arm.accel_arg(windows), "tcg,thread=multi");
assert!(arm.section_ram(windows) && !arm.memfd_ram(windows));
assert!(arm.ram_whole_at_start(windows));
assert!(arm.gpu_choice(windows));
assert!(arm.describe(windows).ends_with("emulated by TCG)"));
assert_eq!(windows.to_string(), "Windows on x86-64");
}
#[cfg(unix)]
#[cfg(all(unix, not(target_os = "macos")))]
#[test]
fn a_vms_environment_decides_its_screen_over_this_process() {
let env = |v: &str| {
@@ -344,4 +790,21 @@ mod tests {
assert!(has_screen(&env(":0")));
assert!(!has_screen(&env("")));
}
/// On a Mac a window opens on the window server of this process's security session, which a
/// signed-in user's session reaches and an SSH login's does not: X's and Wayland's variables,
/// which AppKit reads none of, decide nothing there.
#[cfg(target_os = "macos")]
#[test]
fn a_mac_has_a_screen_by_its_session_not_by_x_or_wayland() {
let env = |v: &str| {
BTreeMap::from(["WAYLAND_DISPLAY", "DISPLAY"].map(|k| (k.to_string(), v.to_string())))
};
assert_eq!(has_screen(&env(":0")), has_screen(&env("")));
assert_eq!(has_screen(&env("")), has_screen(&BTreeMap::new()));
assert_eq!(
has_screen(&BTreeMap::new()),
crate::os::session_has_graphics()
);
}
}
+327 -37
View File
@@ -31,7 +31,7 @@ pub const INSTALL_SCRIPT: &str = if cfg!(windows) {
"scripts/install-ctl.sh"
};
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Install {
/// The reims-vgpu checkout the install built from, which `update` pulls.
pub repo: PathBuf,
@@ -54,21 +54,37 @@ fn is_empty(p: &Path) -> bool {
}
impl Install {
/// The data directory's record, else an earlier reims-ctl's in the config directory.
pub fn load() -> Option<Install> {
let text = std::fs::read_to_string(paths::install_file())
.or_else(|_| std::fs::read_to_string(paths::config_install_file()))
.ok()?;
toml::from_str(&text).ok()
/// The data directory's record, else, where it has none, an earlier reims-ctl's in the config
/// directory; `None` where neither is there. An error where one is there that this build
/// can't read, or can't read as the record: taken for none, the data directory's would give
/// the config directory's, an earlier install's, in its place, or no install at all.
pub fn load() -> Result<Option<Install>> {
for file in [paths::install_file(), paths::config_install_file()] {
match std::fs::read_to_string(&file) {
Ok(text) => {
let read = toml::from_str(&text).map(Some);
return read.with_context(|| format!("parse {}", file.display()));
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(e).with_context(|| format!("read {}", file.display())),
}
}
Ok(None)
}
/// Writes the record into the data directory, and removes an earlier reims-ctl's record in
/// Writes the record into the data directory, over its file as it is, keeping what another
/// build of reims-ctl wrote there in its place and form ([`crate::record::text_over`]), and
/// refused, with the file left as it is, where this build can't read it or keep what it holds
/// ([`crate::record::Refused`]). The text goes into a file beside it, renamed over it, so a
/// write cut short leaves the record whole. Then it removes an earlier reims-ctl's record in
/// the config directory where that one named a QEMU build of this data directory: the same
/// install's, which this replaces. One of another data directory's install stays.
pub fn save(&self) -> Result<()> {
let file = paths::install_file();
std::fs::create_dir_all(file.parent().unwrap())?;
std::fs::write(&file, toml::to_string_pretty(self)?)
let old = crate::record::old_text(&file)?;
let text = crate::record::text_over(self, &file, old.as_deref(), &[])?;
crate::record::replace(&file, text.as_bytes())
.with_context(|| format!("write {}", file.display()))?;
let old = paths::config_install_file();
if let Ok(text) = std::fs::read_to_string(&old)
@@ -222,26 +238,44 @@ fn lists_property(out: &str, name: &str) -> bool {
})
}
/// What `qemu -smbios type=17,memory_type=26 -version` answered, by binary and its modification
/// time.
type SmbiosProbes = HashMap<(PathBuf, Option<std::time::SystemTime>), bool>;
/// What `qemu -smbios OPTION -version` answered, by binary, its modification time and the option.
type SmbiosProbes = HashMap<(PathBuf, Option<std::time::SystemTime>, &'static str), bool>;
/// Whether `qemu` takes `-smbios type=17`'s `memory_type`, the memory devices' SMBIOS Memory
/// Type, which reims-vgpu's QEMU has since vendor/qemu's `0c91b471`. A QEMU without it, upstream's
/// or one built from an older tree (`REIMS_CTL_QEMU` names any), ends at its start on the option.
/// QEMU takes its options in order, so it checks `-smbios` and exits with an error before
/// `-version` prints and exits with 0. Cached per binary, by its path and modification time; false
/// where QEMU does not run.
/// Type, which reims-vgpu's QEMU has since vendor/qemu's `0c91b471` ([`smbios_takes`]).
pub fn smbios_takes_memory_type(qemu: &Path) -> bool {
smbios_takes(qemu, "type=17,memory_type=26")
}
/// Whether `qemu` takes `-smbios type=16`'s `error_correction`, the memory array's SMBIOS Memory
/// Error Correction, which reims-vgpu's QEMU has since vendor/qemu's `d72b4ac3`
/// ([`smbios_takes`]).
pub fn smbios_takes_error_correction(qemu: &Path) -> bool {
smbios_takes(qemu, "type=16,error_correction=3")
}
/// Whether `qemu` takes `-smbios type=17`'s `slots` and `form_factor`, the memory array's empty
/// slots and its devices' SMBIOS Form Factor, which reims-vgpu's QEMU has since vendor/qemu's
/// `445170b5` ([`smbios_takes`]).
pub fn smbios_takes_memory_slots(qemu: &Path) -> bool {
smbios_takes(qemu, "type=17,slots=4,form_factor=13")
}
/// Whether `qemu` takes `-smbios option`. A QEMU without it, upstream's or one built from an
/// older tree (`REIMS_CTL_QEMU` names any), ends at its start on the option. QEMU takes its
/// options in order, so it checks `-smbios` and exits with an error before `-version` prints and
/// exits with 0. Cached per binary and option, by the binary's path and modification time; false
/// where QEMU does not run.
fn smbios_takes(qemu: &Path, option: &'static str) -> bool {
static CACHE: OnceLock<Mutex<SmbiosProbes>> = OnceLock::new();
let cache = CACHE.get_or_init(Default::default);
let mtime = std::fs::metadata(qemu).and_then(|m| m.modified()).ok();
let key = (qemu.to_path_buf(), mtime);
let key = (qemu.to_path_buf(), mtime, option);
if let Some(v) = cache.lock().unwrap().get(&key) {
return *v;
}
let takes = std::process::Command::new(qemu)
.args(["-smbios", "type=17,memory_type=26", "-version"])
.args(["-smbios", option, "-version"])
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
@@ -289,6 +323,22 @@ mod tests {
script[start..start + len].to_string()
}
/// bash, as a shell finds it on PATH: on Windows MSYS2's, which the installer runs in. A
/// `Command::new("bash")` there looks in System32 before PATH, and takes WSL's launcher where
/// WSL is installed: it ran none of these tests on GitHub's Windows runners, which have WSL
/// and no distribution for it (2026-12-03).
fn bash() -> std::process::Command {
#[cfg(windows)]
let program = (std::env::var_os("PATH").iter())
.flat_map(std::env::split_paths)
.map(|dir| dir.join("bash.exe"))
.find(|exe| exe.is_file())
.unwrap_or_else(|| "bash".into());
#[cfg(not(windows))]
let program = "bash";
std::process::Command::new(program)
}
/// What the prune test runs as a QEMU: this test binary, copied into a build, idling here.
#[test]
fn idle_as_a_qemu() {
@@ -314,19 +364,25 @@ mod tests {
assert!(!lists_property(none, "x-avx512-xstate"));
}
/// A QEMU that does not run, or that refuses the probe's options, takes no `memory_type`:
/// this test binary stands for one that refuses them, as libtest ends on an option it does
/// not know.
/// A QEMU that does not run, or that refuses the probe's options, takes neither `memory_type`
/// nor `error_correction`: this test binary stands for one that refuses them, as libtest ends
/// on an option it does not know.
#[test]
fn a_qemu_that_refuses_the_probe_takes_no_memory_type() {
let missing = std::env::temp_dir().join("reims-ctl-no-such-qemu");
assert!(!smbios_takes_memory_type(&missing));
assert!(!smbios_takes_error_correction(&missing));
let refuses = std::env::current_exe().unwrap();
assert!(!smbios_takes_memory_type(&refuses));
assert!(!smbios_takes_error_correction(&refuses));
assert!(!smbios_takes_memory_slots(&missing));
assert!(!smbios_takes_memory_slots(&refuses));
}
/// A QEMU that takes the probe's options takes `memory_type`: a stand-in that ends with 0
/// only when it is asked for `type=17,memory_type=26`, as reims-vgpu's QEMU does.
/// only when it is asked for `type=17,memory_type=26`, as reims-vgpu's QEMU does. It refuses
/// `type=16,error_correction=3`, as a QEMU built between the two options does, and is said
/// not to take that one.
#[test]
fn a_qemu_that_takes_the_probe_takes_the_memory_type() {
let d = std::env::temp_dir().join(format!("reims-ctl-smbios-{}", std::process::id()));
@@ -335,9 +391,46 @@ mod tests {
&d.join("qemu"),
"#!/bin/sh\ncase \" $* \" in *\" -smbios type=17,memory_type=26 \"*) exit 0 ;; esac\nexit 1\n",
);
let answer = smbios_takes_memory_type(&takes);
let answers = (
smbios_takes_memory_type(&takes),
smbios_takes_error_correction(&takes),
);
let _ = std::fs::remove_dir_all(&d);
assert!(answer, "a QEMU that takes memory_type is said not to");
assert_eq!(answers, (true, false), "(memory_type, error_correction)");
}
/// A QEMU that takes `type=16,error_correction=3` takes the memory array's error correction:
/// a stand-in that ends with 0 only when asked for it.
#[test]
fn a_qemu_that_takes_the_probe_takes_the_error_correction() {
let d = std::env::temp_dir().join(format!("reims-ctl-smbios16-{}", std::process::id()));
std::fs::create_dir_all(&d).unwrap();
let takes = crate::testenv::program(
&d.join("qemu"),
"#!/bin/sh\ncase \" $* \" in *\" -smbios type=16,error_correction=3 \"*) exit 0 ;; esac\nexit 1\n",
);
let answer = smbios_takes_error_correction(&takes);
let _ = std::fs::remove_dir_all(&d);
assert!(answer, "a QEMU that takes error_correction is said not to");
}
/// A QEMU that takes `type=17,slots=4,form_factor=13` takes the memory array's slots: a
/// stand-in that ends with 0 only when asked for them. It refuses `memory_type`, as no QEMU
/// does, and is said not to take that one: each option is asked of QEMU on its own.
#[test]
fn a_qemu_that_takes_the_probe_takes_the_memory_slots() {
let d = std::env::temp_dir().join(format!("reims-ctl-smbios17-{}", std::process::id()));
std::fs::create_dir_all(&d).unwrap();
let takes = crate::testenv::program(
&d.join("qemu"),
"#!/bin/sh\ncase \" $* \" in *\" -smbios type=17,slots=4,form_factor=13 \"*) exit 0 ;; esac\nexit 1\n",
);
let answers = (
smbios_takes_memory_slots(&takes),
smbios_takes_memory_type(&takes),
);
let _ = std::fs::remove_dir_all(&d);
assert_eq!(answers, (true, false), "(slots, memory_type)");
}
/// The installer's prune keeps a build older than the newest three while a QEMU runs from
@@ -403,7 +496,7 @@ mod tests {
}
};
link(builds[4]);
let pruned = std::process::Command::new("bash")
let pruned = bash()
.arg("-c")
.arg(format!("set -euo pipefail\n{functions}prune_qemu \"$1\""))
.arg("prune")
@@ -474,7 +567,7 @@ mod tests {
.unwrap();
link(builds[4]);
let prune = || {
std::process::Command::new("bash")
bash()
.arg("-c")
.arg(format!(
"set -euo pipefail\nWINDOWS=1\n{functions}prune_qemu \"$(cygpath -u \"$1\")\""
@@ -520,7 +613,7 @@ mod tests {
let line = text[at..].lines().nth(1).expect("the configure line");
assert!(line.contains("\"${CONFIGURE[@]}\""), "{line}");
let configure = |shell: Option<&str>| {
let mut bash = std::process::Command::new("bash");
let mut bash = bash();
bash.arg("-c")
.arg(format!(
"set -euo pipefail\nBUILD=.\nPC=/dist/lib/pkgconfig\n\
@@ -595,7 +688,7 @@ mod tests {
"for n in {}; do printf '%s=%s\\n' \"$n\" \"${{!n-}}\"; done\n",
names.join(" ")
);
let mut bash = std::process::Command::new("bash");
let mut bash = bash();
bash.arg("-c")
.arg(format!("set -euo pipefail\n{exports}{print}"))
.env("MSYSTEM", "CLANG64")
@@ -632,7 +725,7 @@ mod tests {
.iter()
.map(|f| script_function(&text, f))
.collect();
let out = std::process::Command::new("bash")
let out = bash()
.arg("-c")
.arg(format!("set -euo pipefail\n{functions}{body}"))
.current_dir(dir)
@@ -761,7 +854,7 @@ mod tests {
let root = std::env::temp_dir().join(format!("reims-ctl-skip-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(&root).unwrap();
let out = std::process::Command::new("bash")
let out = bash()
.arg(&script)
.arg("--skip-qemu")
.env("XDG_DATA_HOME", root.join("data"))
@@ -836,7 +929,7 @@ mod tests {
commit("crates/reims-ctl/src/main.rs");
commit("docs/qemu.md");
let kept = |build: &str| {
let mut bash = std::process::Command::new("bash");
let mut bash = bash();
for v in crate::update::GIT_REPOSITORY_ENV {
bash.env_remove(v);
}
@@ -871,6 +964,128 @@ mod tests {
);
}
/// What the installer says last (its `check_note`): how to check the host with the
/// reims-ctl it installed and, where the user's shell won't run that one as reims-ctl, what
/// puts the directory it installed into first on PATH, naming that directory. Cargo's home's
/// bin is put first by rustup's env file there (`$HOME/.cargo/env`, or CARGO_HOME's);
/// CARGO_INSTALL_ROOT's bin by nothing of rustup's, where the installer named the default
/// env file all the same. Where the shell runs it first, nothing. On Windows, a new window
/// has no CARGO_INSTALL_ROOT's bin on its PATH, so the check runs reims-ctl by its full path.
#[test]
fn the_installers_path_advice_names_the_directory_it_installed_into() {
let dir = std::env::var_os("CARGO_MANIFEST_DIR")
.expect("CARGO_MANIFEST_DIR: run the tests with cargo");
let text =
std::fs::read_to_string(Path::new(&dir).join("../../scripts/install-ctl.sh")).unwrap();
let functions: String = ["shown", "check_note"]
.iter()
.map(|f| script_function(&text, f))
.collect();
// check_note for `bin` in a shell whose PATH was `start`, with `env` and the script's
// WINDOWS; what it writes to its standard output and error. Its cygpath writes /c/x/y as
// Windows writes it, C:\x\y.
let note = |windows: bool, env: &[(&str, &str)], bin: &str, start: &str| {
// The script goes to bash on its standard input, not as a `-c` argument: on Windows
// an argument passes through the command line's quoting, which MSYS2's bash reads
// back otherwise for the quotes in the installer's text.
let script = format!(
"set -euo pipefail\nwarn() {{ printf 'warning: %s\\n' \"$*\" >&2; }}\n\
cygpath() {{ local p=\"${{2#/c}}\"; printf 'C:%s' \"${{p//\\//\\\\}}\"; }}\n\
{functions}WINDOWS={} START_PATH=\"$1\"\ncheck_note \"$2\"\n",
u8::from(windows)
);
let mut bash = bash();
bash.arg("-s")
.arg(start)
.arg(bin)
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.env("HOME", "/home/u")
.env_remove("CARGO_HOME")
.env_remove("CARGO_INSTALL_ROOT")
// On Windows, MSYS2's bash, as the installer runs in.
.env("MSYSTEM", "CLANG64")
.env("CHERE_INVOKING", "1");
for (k, v) in env {
bash.env(k, v);
}
let mut child = bash.spawn().unwrap();
std::io::Write::write_all(&mut child.stdin.take().unwrap(), script.as_bytes()).unwrap();
let out = child.wait_with_output().unwrap();
let err = String::from_utf8(out.stderr).unwrap();
assert!(out.status.success(), "{err}");
(String::from_utf8(out.stdout).unwrap(), err)
};
let checked = |bin: &str| format!("Check this host:\n {bin} doctor\n");
let start = "/usr/bin:/bin";
let bin = "/opt/ctl/bin/reims-ctl";
assert_eq!(
note(false, &[("CARGO_INSTALL_ROOT", "/opt/ctl")], bin, start),
(
checked(bin) + "\n",
"warning: /opt/ctl/bin, CARGO_INSTALL_ROOT's bin, is not first on your PATH, and \
a new terminal won't put it there: add it in your shell's profile, as with: \
export PATH=\"/opt/ctl/bin:$PATH\"\n"
.to_string()
)
);
let bin = "/home/u/.cargo/bin/reims-ctl";
assert_eq!(
note(false, &[], bin, start),
(
checked(bin) + "\n",
"warning: /home/u/.cargo/bin is not first on your PATH: open a new terminal, or \
run: . \"$HOME/.cargo/env\"\n"
.to_string()
)
);
let bin = "/opt/cargo/bin/reims-ctl";
assert_eq!(
note(false, &[("CARGO_HOME", "/opt/cargo")], bin, start),
(
checked(bin) + "\n",
"warning: /opt/cargo/bin is not first on your PATH: open a new terminal, or run: \
. \"/opt/cargo/env\"\n"
.to_string()
)
);
#[cfg(unix)]
{
let root = std::env::temp_dir().join(format!("reims-ctl-path-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(root.join("bin")).unwrap();
let ctl = crate::testenv::program(&root.join("bin/reims-ctl"), "#!/bin/sh\n");
let (root_s, ctl_s) = (root.to_str().unwrap(), ctl.to_str().unwrap());
let first = format!("{root_s}/bin:{start}");
let said = note(false, &[("CARGO_INSTALL_ROOT", root_s)], ctl_s, &first);
let _ = std::fs::remove_dir_all(&root);
assert_eq!(said, (checked(ctl_s), String::new()));
}
let window = "Check this host, in a new PowerShell or Windows Terminal window:\n";
assert_eq!(
note(
true,
&[("CARGO_INSTALL_ROOT", "C:\\ctl")],
"/c/ctl/bin/reims-ctl.exe",
start
),
(
format!("{window} & 'C:\\ctl\\bin\\reims-ctl.exe' doctor\n\n"),
"warning: C:\\ctl\\bin, CARGO_INSTALL_ROOT's bin, is on no PATH rustup set: add \
it to your PATH (Windows' \"Edit environment variables for your account\") to \
run reims-ctl by its name\n"
.to_string()
)
);
assert_eq!(
note(true, &[], "/c/Users/u/.cargo/bin/reims-ctl.exe", start),
(format!("{window} reims-ctl doctor\n"), String::new())
);
}
/// The install's record is in the data directory, beside the QEMU builds it names: an
/// install into a scratch data directory records itself there, and the user's record stays
/// as it was, an earlier reims-ctl's in the config directory too, which the user's own
@@ -890,23 +1105,98 @@ mod tests {
std::fs::create_dir_all(old.parent().unwrap()).unwrap();
std::fs::write(&old, toml::to_string_pretty(&record("aaaaaaa")).unwrap()).unwrap();
let old_text = std::fs::read(&old).unwrap();
assert_eq!(Install::load().unwrap().commit, "aaaaaaa");
assert_eq!(Install::load().unwrap().unwrap().commit, "aaaaaaa");
let scratch = env.root.join("scratch");
env.set("REIMS_CTL_DATA_DIR", &scratch);
record("bbbbbbb").save().unwrap();
assert!(scratch.join("install.toml").is_file());
assert_eq!(Install::load().unwrap().commit, "bbbbbbb");
assert_eq!(Install::load().unwrap().unwrap().commit, "bbbbbbb");
assert_eq!(std::fs::read(&old).unwrap(), old_text);
env.set("REIMS_CTL_DATA_DIR", &own);
assert_eq!(Install::load().unwrap().commit, "aaaaaaa");
assert_eq!(Install::load().unwrap().unwrap().commit, "aaaaaaa");
record("ccccccc").save().unwrap();
assert!(!old.exists());
assert!(own.join("install.toml").is_file());
assert_eq!(Install::load().unwrap().commit, "ccccccc");
assert_eq!(Install::load().unwrap().unwrap().commit, "ccccccc");
env.set("REIMS_CTL_DATA_DIR", &scratch);
assert_eq!(Install::load().unwrap().commit, "bbbbbbb");
assert_eq!(Install::load().unwrap().unwrap().commit, "bbbbbbb");
}
/// The install's save over a record this build can't read, as one that isn't UTF-8 or that its
/// mode keeps from the user, is refused, naming the file, and leaves the file byte for byte.
#[test]
fn the_install_s_save_over_a_record_this_build_cannot_read_leaves_it() {
let env = crate::testenv::Env::new("unreadable-install-record");
let record = Install {
repo: env.root.join("repo"),
commit: "aaaaaaa".into(),
qemu: paths::qemu_root().join("20261118-000000-aaaaaaa"),
installed_at: String::new(),
shell: PathBuf::new(),
};
crate::record::assert_unreadable_refused(&paths::install_file(), &|| record.save());
}
/// An install's record this build can't read, one that isn't UTF-8 or that isn't the record,
/// is not taken for none: its load is an error naming the file, not an earlier reims-ctl's
/// record in the config directory nor no install, and the file is left byte for byte.
#[test]
fn an_install_record_this_build_cannot_read_is_not_taken_for_none() {
let env = crate::testenv::Env::new("unreadable-install-load");
let record = Install {
repo: env.root.join("repo"),
commit: "aaaaaaa".into(),
qemu: paths::qemu_root().join("20261118-000000-aaaaaaa"),
installed_at: String::new(),
shell: PathBuf::new(),
};
let old = paths::config_install_file();
std::fs::create_dir_all(old.parent().unwrap()).unwrap();
std::fs::write(&old, toml::to_string_pretty(&record).unwrap()).unwrap();
let file = paths::install_file();
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
let held: [&[u8]; 2] = [b"commit = \"\xff\"\n", b"commit = 7\n"];
for held in held {
std::fs::write(&file, held).unwrap();
let e = format!("{:#}", Install::load().unwrap_err());
assert!(e.contains(&file.display().to_string()), "{e}");
assert_eq!(std::fs::read(&file).unwrap(), held);
}
std::fs::remove_file(&file).unwrap();
assert_eq!(Install::load().unwrap(), Some(record));
}
/// The install's record keeps what a newer reims-ctl wrote into it: a key of its own and a
/// table of its own stay as written, byte for byte, as an install records another commit,
/// whose line is all that changes.
#[test]
fn the_install_record_keeps_what_a_newer_build_wrote() {
let env = crate::testenv::Env::new("newer-install-record");
let record = Install {
repo: env.root.join("repo"),
commit: "aaaaaaa".into(),
qemu: paths::qemu_root().join("20261118-000000-aaaaaaa"),
installed_at: "2026-12-03 10:00:00 -0800".into(),
shell: PathBuf::new(),
};
record.save().unwrap();
let file = paths::install_file();
let ours = std::fs::read_to_string(&file).unwrap();
let line = "commit = \"aaaaaaa\"\n";
let newer = ours.replacen(line, &format!("{line}channel = \"development\"\n"), 1)
+ "\n[library]\nmetal2vulkan = \"0123abc\"\n";
assert!(newer.contains("channel = "), "{newer}");
std::fs::write(&file, &newer).unwrap();
let mut i = Install::load().unwrap().unwrap();
assert_eq!(i, record);
i.commit = "bbbbbbb".into();
i.save().unwrap();
assert_eq!(
std::fs::read_to_string(&file).unwrap(),
newer.replacen(line, "commit = \"bbbbbbb\"\n", 1)
);
}
#[test]
+4 -1
View File
@@ -32,7 +32,10 @@ pub fn on_disk() -> Vec<OnDisk> {
/// Whether a create's `--ipsw` names a file rather than a release: a path, or a name that is
/// there.
pub fn is_path(s: &str) -> bool {
s.contains('/') || s.ends_with(".ipsw") || Path::new(s).exists()
s.contains('/')
|| (cfg!(windows) && s.contains('\\'))
|| s.ends_with(".ipsw")
|| Path::new(s).exists()
}
/// The IPSW a create named.
+360 -22
View File
@@ -1,7 +1,13 @@
//! Bug reports: a zip of a VM's logs, its settings, the exact QEMU command, what the host is
//! and vulkaninfo's whole report of it, in the downloads folder, for someone to attach to a
//! report. A running VM's library is asked first for its degradation counts as they are then
//! ([`ask_counts`]), so its QEMU log in the zip ends with them.
//! report. A running VM's library is asked first for its degradation counts as they are then,
//! twice, [`PACING_SPAN`] apart, before anything else of the report runs on the host
//! ([`ask_pacing`]), so its QEMU log in the zip ends with them, its build, and its pacing line over
//! those 10 s: what limits a slow app (docs/conventions.md, "The pacing line"). A stopped VM's
//! state.txt says why it stopped, and whether the counts its log holds are as of the run's end
//! ([`stopped_state`]): a QEMU killed or crashed wrote none at its end. system.txt's head
//! names reims-ctl's build, the library's as the VM's QEMU log names it, and the install's, and
//! says so where they differ ([`builds`]).
use crate::gpu::GpuInfo;
use crate::host::{Host, Os};
@@ -35,7 +41,8 @@ const ADAPTERS_QUERY: &str = "$ProgressPreference = 'SilentlyContinue'; \
'{0} [{1}] driver {2}' -f $_.Name, $_.PNPDeviceID, $_.DriverVersion }";
/// How long the ask for a running VM's counts waits for QMP's greeting and its answer: QMP takes
/// one client at a time, so the ask waits while another holds it (reims-ctl's viewer).
/// one client at a time, so the ask waits while another holds it (reims-ctl's viewer holds it
/// for one exchange at a time, a frame or a batch of input).
const COUNTS_WAIT: Duration = Duration::from_secs(3);
/// The QOM path of a VM's display device, which qemu.rs names `gfx`.
@@ -45,13 +52,34 @@ const DISPLAY_PATH: &str = "/machine/peripheral/gfx";
/// counts into QEMU's log before QMP answers (vendor/qemu hw/display/reims-graphics-pci.c).
const COUNTS_PROPERTY: &str = "x-write-counts";
/// How far apart the report's two asks for the counts are: the span the library's pacing line
/// covers, which it writes at the second.
pub const PACING_SPAN: Duration = Duration::from_secs(10);
pub fn bundle(vm: &Vm, host: Host) -> Result<PathBuf> {
let stamp = runtime::now_stamp("%Y%m%d-%H%M%S");
let out = crate::paths::downloads_dir().join(format!("reims-ctl-{}-{stamp}.zip", vm.name()));
let mut zip = Zip::create(&out)?;
let prefix = format!("reims-ctl-{}-{stamp}", vm.name());
// First, before vulkaninfo loads the host's GPU, and so before the logs are read: the
// counts, the build and the pacing line of the 10 s between the two asks.
let state = match runtime::pid(vm) {
Some(p) => format!(
"running, pid {p}\n{}\n",
ask_pacing(&vm.qmp_socket(), PACING_SPAN)
),
None => stopped_state(&runtime::tail(&vm.qemu_log(), usize::MAX)),
};
let vulkaninfo = run_limited(Command::new("vulkaninfo"), VULKANINFO_LIMIT);
let system = system_info(host, &runtime::warnings(vm, host), &vulkaninfo.end);
let library = read_tail(&vm.qemu_log(), LOG_CAP)
.ok()
.and_then(|log| library_build(&String::from_utf8_lossy(&log)));
let system = system_info(
host,
&runtime::warnings(vm, host),
&vulkaninfo.end,
library.as_ref(),
);
zip.add(&format!("{prefix}/system.txt"), system.as_bytes())?;
zip.add(
&format!("{prefix}/vulkaninfo.txt"),
@@ -67,11 +95,6 @@ pub fn bundle(vm: &Vm, host: Host) -> Result<PathBuf> {
.as_bytes(),
)?;
}
// Before the logs are read, so that QEMU's ends with the counts as of the report.
let state = match runtime::pid(vm) {
Some(p) => format!("running, pid {p}\n{}\n", ask_counts(&vm.qmp_socket())),
None => "stopped\n".to_string(),
};
zip.add(&format!("{prefix}/state.txt"), state.as_bytes())?;
if let Ok(rd) = std::fs::read_dir(vm.logs_dir()) {
let mut files: Vec<PathBuf> = rd
@@ -93,21 +116,157 @@ pub fn bundle(vm: &Vm, host: Host) -> Result<PathBuf> {
}
/// Asks the VM on QMP's `socket` to write its library's degradation counts into its QEMU log now
/// (reims-graphics-pci's [`COUNTS_PROPERTY`]): state.txt's line that says whether it did. A VM
/// on VMware SVGA has no such property, and QMP says so.
/// (reims-graphics-pci's [`COUNTS_PROPERTY`]), with its build and, at an ask 2 to 60 s after
/// another, its pacing line. A VM on VMware SVGA has no such property, and QMP says so.
fn ask(socket: &Path) -> Result<()> {
let mut qmp = crate::qmp::Qmp::connect(socket, COUNTS_WAIT)?;
let set = json!({ "path": DISPLAY_PATH, "property": COUNTS_PROPERTY, "value": true });
qmp.execute("qom-set", Some(set)).map(drop)
}
/// [`ask`]s once: state.txt's line that says whether the library wrote its counts.
fn ask_counts(socket: &Path) -> String {
let asked = crate::qmp::Qmp::connect(socket, COUNTS_WAIT).and_then(|mut qmp| {
let set = json!({ "path": DISPLAY_PATH, "property": COUNTS_PROPERTY, "value": true });
qmp.execute("qom-set", Some(set))
});
match asked {
Ok(_) => "degradation counts: the library wrote them into logs/qemu.log for this report, \
where it had counted any"
match ask(socket) {
Ok(()) => "degradation counts: the library wrote them into logs/qemu.log for this report, \
where it had counted any"
.to_string(),
Err(e) => format!("degradation counts: not written for this report: {e:#}"),
}
}
/// [`ask`]s twice, `apart` apart, so the library writes its pacing line over the span between
/// the two at the second: state.txt's lines that say whether it did. Where the first ask fails,
/// the second is not made.
fn ask_pacing(socket: &Path, apart: Duration) -> String {
let first = Instant::now();
if let Err(e) = ask(socket) {
return format!("degradation counts: not written for this report: {e:#}");
}
std::thread::sleep(apart.saturating_sub(first.elapsed()));
let counts = ask_counts(socket);
let pacing = if counts.contains("not written") {
"pacing: not written for this report".to_string()
} else {
format!(
"pacing: the library wrote its line over the {} s between two asks into \
logs/qemu.log, where its build writes one",
apart.as_secs()
)
};
format!("{counts}\n{pacing}")
}
/// state.txt's lines for a VM that is not running, whose QEMU log ends with `log`: why it
/// stopped ([`runtime::stopped`]), and whether the library's degradation counts in the log are as
/// of the run's end, which they are where QEMU exited, as the library writes them at the
/// process's exit; where it was killed, crashed or a fatal error ended it, the log's last are
/// from earlier in the run, or there are none. Only "stopped" for a run whose end its log does
/// not tell (an earlier reims-ctl's start).
fn stopped_state(log: &str) -> String {
let Some(s) = runtime::stopped(log) else {
return "stopped\n".to_string();
};
let counted = runtime::last_run_has(log, COUNTS_LINE);
let counts = match (s.exited, counted) {
(true, _) => {
"degradation counts: as of the run's end: the library writes them into logs/qemu.log \
as QEMU exits, where it had counted any"
}
(false, true) => {
"degradation counts: not as of the run's end, which wrote none: logs/qemu.log's last \
are from earlier in the run"
}
(false, false) => {
"degradation counts: none in logs/qemu.log from this run, whose end wrote none"
}
};
format!("stopped: {}\n{counts}\n", s.why)
}
/// How the library's line of its degradation counts starts (docs/conventions.md).
const COUNTS_LINE: &str = "reims-vgpu: degradation counts: ";
/// The library's build as a VM's QEMU log names it ([`library_build`]): the commit it was built
/// from and the metal2vulkan commit it was built on.
#[derive(Debug, Clone, PartialEq, Eq)]
struct LibraryBuild {
commit: String,
pin: String,
/// Whether a report's ask wrote it, rather than the device's start.
asked: bool,
}
/// The library's build as a VM's QEMU log `log` names it last: from the line a report's ask writes
/// (`reims-vgpu: build <commit> on metal2vulkan <pin>`) or the one its device writes as it starts
/// (`reims-vgpu <commit> on metal2vulkan <pin>; …`), whichever is later.
fn library_build(log: &str) -> Option<LibraryBuild> {
log.lines().rev().find_map(|line| {
let (before, after) = line.split_once(" on metal2vulkan ")?;
let (lead, commit) = before.rsplit_once(' ')?;
let asked = lead.ends_with("reims-vgpu: build");
if !asked && !lead.ends_with("reims-vgpu") {
return None;
}
let pin = after.split([';', ' ']).next()?.trim();
(!commit.is_empty() && !pin.is_empty()).then(|| LibraryBuild {
commit: commit.to_string(),
pin: pin.to_string(),
asked,
})
})
}
/// The commit a build stamp names (`build_stamp.rs`), without its dirty mark; `None` for
/// `unknown`.
fn commit_of(stamp: &str) -> Option<&str> {
let commit = stamp.trim();
let commit = commit.strip_suffix("-dirty").unwrap_or(commit);
(!commit.is_empty() && commit != "unknown").then_some(commit)
}
/// The head of system.txt's reims-ctl section: reims-ctl's build `ctl` (its stamp, `-dirty`
/// where its checkout had local changes, `unknown` outside one), the VM's library's `library` as
/// its QEMU log names it, with the metal2vulkan commit it was built on, and the commit of the
/// install record, `install`, where there is one. Where the commits of those known differ (a
/// short commit matching a long one it begins), a first line says so: a reims-ctl or a QEMU from
/// another build than the install's is itself the answer to many reports.
fn builds(ctl: &str, library: Option<&LibraryBuild>, install: Option<&str>) -> String {
let mut known: Vec<(&str, &str)> = Vec::new();
if let Some(c) = commit_of(ctl) {
known.push(("reims-ctl", c));
}
if let Some(c) = library.and_then(|l| commit_of(&l.commit)) {
known.push(("the VM's library", c));
}
if let Some(c) = install.and_then(commit_of) {
known.push(("the install record", c));
}
let same = |a: &str, b: &str| a.starts_with(b) || b.starts_with(a);
let differ = known
.iter()
.any(|(_, a)| known.iter().any(|(_, b)| !same(a, b)));
let mut s = String::new();
if differ {
let names: Vec<String> = known.iter().map(|(n, c)| format!("{n} {c}")).collect();
s.push_str(&format!("builds differ: {}\n", names.join(", ")));
}
s.push_str(&format!("build {ctl}\n"));
match library {
Some(l) => s.push_str(&format!(
"library build {} on metal2vulkan {} ({})\n",
l.commit,
l.pin,
if l.asked {
"the running VM's, at this report's ask"
} else {
"the VM's last start, in logs/qemu.log"
}
)),
None => s.push_str("library build: not in logs/qemu.log\n"),
}
s
}
fn read_tail(p: &Path, cap: u64) -> Result<Vec<u8>> {
use std::io::{Read, Seek, SeekFrom};
let mut f = std::fs::File::open(p)?;
@@ -363,18 +522,39 @@ fn vulkan_gpus(gpus: &[GpuInfo]) -> String {
/// What the host is: the parts a report about a guest's graphics needs.
/// What the host is, and `warnings`, the ones reims-ctl gives the VM as the report is made: what
/// its user was shown. `vulkaninfo` is how the run of vulkaninfo's whole report ended
/// ([`vulkan_summary`]).
fn system_info(host: Host, warnings: &[String], vulkaninfo: &End) -> String {
/// ([`vulkan_summary`]); `library` the VM's library's build as its QEMU log names it. The head
/// names the builds and says where they differ ([`builds`]).
fn system_info(
host: Host,
warnings: &[String],
vulkaninfo: &End,
library: Option<&LibraryBuild>,
) -> String {
let (install, unread) = match crate::install::Install::load() {
Ok(install) => (install, None),
Err(e) => (None, Some(format!("{e:#}"))),
};
let mut s = String::new();
let mut section = |title: &str, body: String| {
s.push_str(&format!("== {title}\n{body}\n\n"));
};
section(
"reims-ctl",
format!("version {}\nhost {host}", env!("CARGO_PKG_VERSION")),
format!(
"version {}\n{}host {host}",
env!("CARGO_PKG_VERSION"),
builds(
env!("REIMS_CTL_STAMP"),
library,
install.as_ref().map(|i| i.commit.as_str())
)
),
);
section("warnings", warnings_list(warnings));
if let Some(i) = crate::install::Install::load() {
if let Some(why) = unread {
section("install", why);
}
if let Some(i) = install {
section(
"install",
format!(
@@ -620,6 +800,47 @@ mod tests {
seen
}
/// A stopped VM's state.txt says why it stopped, and whether the degradation counts in its
/// QEMU log are as of the run's end: they are where QEMU exited, as the library writes them
/// at its exit; where QEMU was killed or crashed, the log's last are from earlier in the run,
/// or there are none. A run whose end its log does not tell says "stopped" alone.
#[test]
fn a_stopped_vms_state_says_whether_its_counts_are_as_of_its_end() {
let run = |trace: &str, lines: &str| {
format!(
"reims-ctl 0.1.0 started t at 2026-12-02 11:00:00 -0800\n#!/bin/sh\n\
exec qemu-system-x86_64 \\\n -name t{trace}\n----\n{lines}"
)
};
let traced = " \\\n -trace qemu_system_shutdown_request";
let counts = "reims-vgpu: degradation counts: rt-refused-x 2\n";
let shut = format!("{counts}qemu_system_shutdown_request reason=6\n{counts}");
assert_eq!(
stopped_state(&run(traced, &shut)),
"stopped: its guest shut down\n\
degradation counts: as of the run's end: the library writes them into \
logs/qemu.log as QEMU exits, where it had counted any\n"
);
let killed = "stopped: QEMU ended without shutting it down, as it does when killed or when it \
crashes\n";
assert_eq!(
stopped_state(&run(traced, counts)),
format!(
"{killed}degradation counts: not as of the run's end, which wrote none: \
logs/qemu.log's last are from earlier in the run\n"
)
);
assert_eq!(
stopped_state(&run(traced, "")),
format!(
"{killed}degradation counts: none in logs/qemu.log from this run, whose end \
wrote none\n"
)
);
assert_eq!(stopped_state(&run("", counts)), "stopped\n");
assert_eq!(stopped_state(""), "stopped\n");
}
/// A running VM is asked to write its library's degradation counts with a qom-set of its
/// display device's x-write-counts property, and state.txt's line says whether it did: a
/// refusal, as a VM on VMware SVGA answers, and a socket nothing listens on say why not
@@ -673,6 +894,121 @@ mod tests {
);
}
/// A running VM is asked twice, the span apart, so its library writes its pacing line over
/// the span at the second ask; a VM whose first ask fails is asked no more.
#[test]
fn a_running_vm_is_asked_twice_for_its_pacing() {
let env = crate::testenv::Env::new("report-pacing");
let socket = |name: &str| {
let runtime = crate::paths::runtime_dir();
let short = crate::paths::short_runtime_dir();
let name = format!("report-pacing-{name}-{}", std::process::id());
let s = crate::vm::qmp_socket_in(&env.root.join(&name), &name, &runtime, &short);
std::fs::create_dir_all(s.parent().unwrap()).unwrap();
let _ = std::fs::remove_file(&s);
s
};
let (written, refused) = (socket("written"), socket("refused"));
let asked = fake_qmp(&written, "{\"return\": {}}");
let no = "{\"error\": {\"class\": \"GenericError\", \
\"desc\": \"Property 'vmware-svga.x-write-counts' not found\"}}";
let refusals = fake_qmp(&refused, no);
let apart = Duration::from_millis(300);
let started = Instant::now();
let wrote = ask_pacing(&written, apart);
assert!(started.elapsed() >= apart);
let not = ask_pacing(&refused, apart);
for s in [&written, &refused] {
let _ = std::fs::remove_file(s);
}
assert_eq!(asked.lock().unwrap().len(), 2);
assert_eq!(refusals.lock().unwrap().len(), 1);
assert_eq!(
wrote,
"degradation counts: the library wrote them into logs/qemu.log for this report, where \
it had counted any\npacing: the library wrote its line over the 0 s between two asks \
into logs/qemu.log, where its build writes one"
);
assert_eq!(
not,
"degradation counts: not written for this report: QMP qom-set: Property \
'vmware-svga.x-write-counts' not found"
);
}
/// The library's build is the last a QEMU log names: a report's ask's line, or the line its
/// device writes as it starts, in the library's log format; none where the log names none.
#[test]
fn the_library_s_build_is_the_last_the_log_names() {
let start = "reims-vgpu WARN reims_vgpu_vulkan::rt_platform::device: reims-vgpu \
3731afd9b1aa-dirty on metal2vulkan 0b0ac58eb0f6; rt's Shared memory: type 2, \
HOST_VISIBLE";
let ask = "reims-vgpu: build 41f0bba449cc on metal2vulkan 0b0ac58eb0f6";
let started = LibraryBuild {
commit: "3731afd9b1aa-dirty".into(),
pin: "0b0ac58eb0f6".into(),
asked: false,
};
let at_ask = LibraryBuild {
commit: "41f0bba449cc".into(),
pin: "0b0ac58eb0f6".into(),
asked: true,
};
assert_eq!(
library_build(&format!("qemu\n{start}\nmore\n")),
Some(started.clone())
);
assert_eq!(
library_build(&format!("{start}\n{ask}\n")),
Some(at_ask.clone())
);
assert_eq!(library_build(&format!("{ask}\n{start}\n")), Some(started));
assert_eq!(
library_build("qemu-system-x86_64: on metal2vulkan nothing\n"),
None
);
assert_eq!(library_build(""), None);
}
/// system.txt's head: reims-ctl's stamp, dirty or unknown as built, the library's build, and
/// a first line where the commits known differ, a short commit matching a long one it begins.
#[test]
fn the_head_names_the_builds_and_says_where_they_differ() {
let library = |commit: &str| LibraryBuild {
commit: commit.into(),
pin: "0b0ac58eb0f69ed3b37007fbdf3b135a46f90699".into(),
asked: true,
};
let long = "41f0bba449c1e1f1b2e5d3c4a5b6c7d8e9f00112";
// Stamped: one commit, long and short.
assert_eq!(
builds(long, Some(&library(long)), Some("41f0bba449")),
format!(
"build {long}\nlibrary build {long} on metal2vulkan \
0b0ac58eb0f69ed3b37007fbdf3b135a46f90699 (the running VM's, at this report's \
ask)\n"
)
);
// Dirty: the same commit, so no line says they differ.
let dirty = format!("{long}-dirty");
let head = builds(&dirty, Some(&library(&dirty)), Some("41f0bba449"));
assert!(head.starts_with(&format!("build {dirty}\n")), "{head}");
// Unknown: a build outside a checkout is compared with nothing.
let head = builds("unknown", None, Some("3731afd9b1"));
assert_eq!(head, "build unknown\nlibrary build: not in logs/qemu.log\n");
// Mismatch: the VM's library is another commit's.
let head = builds(long, Some(&library("3731afd9b1aa")), Some("41f0bba449"));
assert!(
head.starts_with(&format!(
"builds differ: reims-ctl {long}, the VM's library 3731afd9b1aa, the install \
record 41f0bba449\nbuild {long}\n"
)),
"{head}"
);
let head = builds(long, None, Some("3731afd9b1"));
assert!(head.starts_with("builds differ: reims-ctl"), "{head}");
}
/// system.txt's Vulkan GPUs: each GPU's label, IDs and manifest on a line, and below it its
/// driver's version raw, with the driver's own name and text where it says them, as a
/// Vulkan 1.2 driver does; `none` where no probe found a GPU.
@@ -691,6 +1027,8 @@ mod tests {
driver_version: version,
driver_name: String::new(),
driver_info: String::new(),
pci: None,
twin: false,
};
let uhd = GpuInfo {
driver_id: 5,
+6
View File
@@ -4,6 +4,8 @@
//! command it opens its interactive interface.
mod ambrosia;
#[cfg(test)]
mod build_stamp;
mod cli;
mod copy;
mod create;
@@ -21,11 +23,14 @@ mod opencore;
mod os;
mod paths;
mod prebuilt;
mod processor;
mod qemu;
mod qmp;
mod record;
mod reims_util;
mod restore;
mod runtime;
mod snapshot;
#[cfg(test)]
mod testenv;
mod tui;
@@ -38,6 +43,7 @@ use clap::Parser;
fn main() {
quiet_on_closed_stdout();
update::note_binary();
let cli = cli::Cli::parse();
match cli::main(cli) {
Ok(code) => std::process::exit(code),
+128 -18
View File
@@ -79,18 +79,31 @@ fn state_file() -> PathBuf {
paths::config_dir().join("migrations.toml")
}
fn load() -> State {
std::fs::read_to_string(state_file())
.ok()
.and_then(|t| toml::from_str(&t).ok())
.unwrap_or_default()
/// The migrations' record: none run where there is no file. An error where there is one this
/// build can't read, or can't read as the record: taken for none run, every migration would run
/// again on each VM, at every run, since its save is refused over the file
/// ([`crate::record::old_text`]).
fn load() -> Result<State> {
let file = state_file();
match std::fs::read_to_string(&file) {
Ok(text) => toml::from_str(&text).with_context(|| format!("parse {}", file.display())),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(State::default()),
Err(e) => Err(e).with_context(|| format!("read {}", file.display())),
}
}
/// Writes `state` over its file as it is, keeping what another build of reims-ctl wrote there in
/// its place and form ([`crate::record::text_over`]); refused, with the file left as it is, where
/// this build can't read it or keep what it holds ([`crate::record::Refused`]).
fn save(state: &State) -> Result<()> {
let file = state_file();
std::fs::create_dir_all(file.parent().unwrap())?;
let tmp = file.with_extension("toml.tmp");
std::fs::write(&tmp, toml::to_string_pretty(state)?)?;
let old = crate::record::old_text(&file)?;
std::fs::write(
&tmp,
crate::record::text_over(state, &file, old.as_deref(), &[])?,
)?;
std::fs::rename(&tmp, &file).with_context(|| format!("write {}", file.display()))
}
@@ -297,12 +310,16 @@ fn plan_of(n: u32, vm: &Vm, running: bool) -> Plan {
/// Runs the migrations this reims-ctl carries that have not run, on every VM in the registry,
/// telling `say` what each did. Where none has run yet and there are VMs, the first line says the
/// update worked. A record that can't be written is told, and the migrations run again next time.
/// One that can't be read is told, and none runs until it can be.
pub fn run(say: &mut dyn FnMut(&str)) {
if load().done >= CURRENT {
if load().is_ok_and(|state| state.done >= CURRENT) {
return;
}
let Some(_lock) = lock() else { return };
let mut state = load();
let mut state = match load() {
Ok(state) => state,
Err(e) => return say(&format!("reims-ctl's update of its VMs waits: {e:#}")),
};
if state.done >= CURRENT {
return;
}
@@ -326,7 +343,9 @@ pub fn run(say: &mut dyn FnMut(&str)) {
// A VM that waited for its start since an earlier update still has every migration to run.
let waited = state.deferred.iter().any(|d| same_dir(d, &vm.dir));
let first = if waited { 1 } else { state.done + 1 };
let running = runtime::running(&vm);
// A VM whose restore was cut off part way waits too, as one that runs: its files change
// only as that restore, run again, finishes.
let running = runtime::running(&vm) || crate::snapshot::cut_off(&vm).is_some();
let mut defer = false;
for n in first..=CURRENT {
let p = plan_of(n, &vm, running);
@@ -356,13 +375,35 @@ pub fn run(say: &mut dyn FnMut(&str)) {
}
}
/// The last migration run: the level a VM's snapshot records ([`crate::snapshot`]). An error,
/// naming the record, where it can't be read ([`load`]): a snapshot taken then would record a
/// level that isn't known, so a snapshot waits until it can be read.
pub fn level() -> Result<u32> {
load().map(|state| state.done)
}
/// Has the migrations run again on the VM in `dir` at its next start ([`at_start`]): its
/// snapshot, restored, is of an older level, from before some of them ran. An error where that
/// can't be recorded: the migrations' lock can't be taken, or their record read or written.
pub fn defer(dir: &Path) -> Result<()> {
let _lock = lock().context("reims-ctl's migrations lock can't be taken")?;
let mut state = load()?;
if !state.deferred.iter().any(|d| same_dir(d, dir)) {
state.deferred.push(dir.to_path_buf());
save(&state)?;
}
Ok(())
}
/// At a start of a stopped VM, a migration that waited while it ran, now, telling `progress`.
/// None where the migrations' record can't be read, which [`run`] tells.
pub fn at_start(vm: &mut Vm, progress: &mut dyn FnMut(&str)) {
if !load().deferred.iter().any(|d| same_dir(d, &vm.dir)) {
let deferred = |state: State| state.deferred.iter().any(|d| same_dir(d, &vm.dir));
if !load().is_ok_and(deferred) {
return;
}
let Some(_lock) = lock() else { return };
let mut state = load();
let Ok(mut state) = load() else { return };
let before = state.deferred.len();
state.deferred.retain(|d| !same_dir(d, &vm.dir));
if state.deferred.len() == before || save(&state).is_err() {
@@ -627,6 +668,42 @@ mod tests {
env.set("REIMS_CTL_UTIL", &util);
}
/// The migrations' save over a record this build can't read, as one that isn't UTF-8 or that
/// its mode keeps from the user, is refused, naming the file, and leaves the file byte for
/// byte.
#[test]
fn the_migrations_save_over_a_record_this_build_cannot_read_leaves_it() {
let _env = crate::testenv::Env::new("unreadable-migrations");
let state = State {
done: CURRENT,
deferred: vec![],
};
crate::record::assert_unreadable_refused(&state_file(), &|| save(&state));
}
/// A migrations' record this build can't read, one that isn't UTF-8 or that isn't the record
/// (a `done` that isn't a number), is not taken for none run: no migration runs, the run says
/// why, naming the file, and the record is left byte for byte.
#[test]
fn a_migrations_record_this_build_cannot_read_runs_none() {
let _env = crate::testenv::Env::new("unreadable-migrations-run");
let file = state_file();
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
let held: [&[u8]; 2] = [b"done = \"\xff\"\n", b"done = \"six\"\n"];
for held in held {
std::fs::write(&file, held).unwrap();
let mut said = Vec::new();
run(&mut |s| said.push(s.to_string()));
assert_eq!(said.len(), 1, "{said:?}");
assert!(
said[0].starts_with("reims-ctl's update of its VMs waits: "),
"{said:?}"
);
assert!(said[0].contains("migrations.toml"), "{said:?}");
assert_eq!(std::fs::read(&file).unwrap(), held);
}
}
/// Migration 1 is for an x86-64 VM whose settings name no graphics, stopped; one whose
/// settings name graphics, as its user chose (apple-gfx among them, migration 3's), is left
/// be.
@@ -869,7 +946,7 @@ mod tests {
.exists()
);
assert!(!env.root.join("fresh/opencore.img.pre-migration-2").exists());
assert_eq!(load().done, CURRENT);
assert_eq!(load().unwrap().done, CURRENT);
let mut said = Vec::new();
run(&mut |s| said.push(s.to_string()));
assert!(said.is_empty(), "{said:?}");
@@ -922,6 +999,33 @@ mod tests {
assert_eq!(plan_of(3, &Vm::load(&dir).unwrap(), false), Plan::Skip);
}
/// The migrations' record keeps what a newer reims-ctl wrote into it: a key of its own and a
/// table of its own stay as written, byte for byte, as the last migration run changes, whose
/// line is all that changes.
#[test]
fn the_migrations_record_keeps_what_a_newer_build_wrote() {
let env = crate::testenv::Env::new("newer-migrations");
save(&State {
done: 3,
deferred: vec![env.root.join("vms/a")],
})
.unwrap();
let file = state_file();
let ours = std::fs::read_to_string(&file).unwrap();
let newer = ours.replacen("done = 3\n", "done = 3\nstarted = \"2026-12-03\"\n", 1)
+ "\n[notes]\nskipped = [\"b\"]\n";
assert!(newer.contains("started = "), "{newer}");
std::fs::write(&file, &newer).unwrap();
let mut state = load().unwrap();
assert_eq!(state.done, 3);
state.done = 4;
save(&state).unwrap();
assert_eq!(
std::fs::read_to_string(&file).unwrap(),
newer.replacen("done = 3\n", "done = 4\n", 1)
);
}
#[test]
fn migration_4_finds_each_legacy_component_for_every_graphics_choice() {
let env = crate::testenv::Env::new("migrate-graft-plan");
@@ -1073,15 +1177,15 @@ mod tests {
said.iter().any(|line| line.starts_with("busy is running")),
"{said:?}"
);
assert_eq!(load().deferred, vec![dir.clone()]);
assert_eq!(load().done, CURRENT);
assert_eq!(load().unwrap().deferred, vec![dir.clone()]);
assert_eq!(load().unwrap().done, CURRENT);
assert_eq!(std::fs::read(dir.join("opencore.img")).unwrap(), before);
assert!(!args.exists());
process.kill().unwrap();
process.wait().unwrap();
std::fs::remove_file(pidfile).unwrap();
at_start(&mut v, &mut |_| {});
assert!(load().deferred.is_empty());
assert!(load().unwrap().deferred.is_empty());
assert_eq!(plan_of(4, &v, false), Plan::Skip);
assert!(dir.join("opencore.img.pre-migration-4").exists());
assert!(
@@ -1116,6 +1220,8 @@ mod tests {
driver_version: 0,
driver_name: String::new(),
driver_info: String::new(),
pci: None,
twin: false,
}
}
@@ -1172,6 +1278,7 @@ mod tests {
driver_file: Some(NVIDIA.into()),
device_id: None,
select: Some("10de:2204".into()),
pci: None,
name: Some("NVIDIA GeForce RTX 3090".into()),
};
assert_eq!(plan, Plan::Gpu(want.clone()));
@@ -1199,6 +1306,7 @@ mod tests {
driver_file: Some(RADEON.into()),
device_id: Some(0x744c),
select: Some("1002:744c".into()),
pci: None,
name: Some("AMD Radeon RX 7900 XTX (RADV NAVI31)".into()),
})
);
@@ -1313,6 +1421,7 @@ mod tests {
driver_file: Some(NV.into()),
device_id: None,
select: Some("10de:1f95".into()),
pci: None,
name: Some(GTX.into()),
};
assert_eq!(plan, Plan::Gpu(want.clone()));
@@ -1349,6 +1458,7 @@ mod tests {
driver_file: Some(INTEL.into()),
device_id: Some(0x1f95),
select: Some("10de:1f95".into()),
pci: None,
name: Some(GTX.into()),
})
);
@@ -1399,7 +1509,7 @@ mod tests {
let mut said = Vec::new();
run(&mut |s| said.push(s.to_string()));
assert!(said.is_empty(), "{said:?}");
assert_eq!(load().done, CURRENT);
assert_eq!(load().unwrap().done, CURRENT);
let _ = std::fs::remove_file(state_file());
// Three VMs: two whose settings name no graphics, one of them running, and one its user
@@ -1435,7 +1545,7 @@ mod tests {
"{said:?}"
);
assert!(!said.iter().any(|s| s.starts_with("chosen")), "{said:?}");
let state = load();
let state = load().unwrap();
assert_eq!(state.done, CURRENT);
assert_eq!(state.deferred, vec![env.root.join("busy")]);
let mut said = Vec::new();
@@ -1454,7 +1564,7 @@ mod tests {
said[0].starts_with("on reims-vgpu's own GPU device"),
"{said:?}"
);
assert!(load().deferred.is_empty());
assert!(load().unwrap().deferred.is_empty());
let mut said = Vec::new();
at_start(&mut v, &mut |s| said.push(s.to_string()));
assert!(said.is_empty(), "{said:?}");
File diff suppressed because it is too large. Load diff
+128 -3
View File
@@ -60,6 +60,25 @@ pub fn local_now() -> super::LocalTime {
}
}
/// Whether this process's security session reaches the window server, where a window can open:
/// a signed-in user's session does, and an SSH login's does not. Security's `SessionGetInfo` for
/// the caller's session, its `sessionHasGraphicAccess` bit (the SDK's AuthSession.h).
#[cfg(target_os = "macos")]
pub fn session_has_graphics() -> bool {
#[link(name = "Security", kind = "framework")]
unsafe extern "C" {
fn SessionGetInfo(session: u32, session_id: *mut u32, attributes: *mut u32) -> i32;
}
/// `callerSecuritySession`: the session of the process that asks.
const CALLER_SESSION: u32 = u32::MAX;
/// `sessionHasGraphicAccess`.
const GRAPHIC_ACCESS: u32 = 0x0010;
let (mut id, mut attributes) = (0u32, 0u32);
// SAFETY: both pointers are to locals, which the call writes.
let status = unsafe { SessionGetInfo(CALLER_SESSION, &mut id, &mut attributes) };
status == 0 && attributes & GRAPHIC_ACCESS != 0
}
/// The host's RAM in MiB, where the host says.
#[cfg(target_os = "macos")]
pub fn memory_mib() -> Option<u64> {
@@ -117,15 +136,22 @@ pub fn uid() -> u32 {
unsafe { libc::getuid() }
}
/// What tells the file `m` describes, at `_path`, from another put there since: its device and
/// inode, which a new file has its own of.
pub fn file_id(_path: &Path, m: &std::fs::Metadata) -> Option<(u64, u64)> {
use std::os::unix::fs::MetadataExt;
Some((m.dev(), m.ino()))
}
/// The group that owns the file `m` describes.
pub fn gid(m: &std::fs::Metadata) -> Option<u32> {
use std::os::unix::fs::MetadataExt;
Some(m.gid())
}
/// When the inode of the file `m` describes last changed (its ctime): any write to the file, or
/// change of its times, sets it to the present, and no program can set it otherwise.
pub fn changed(m: &std::fs::Metadata) -> Option<std::time::SystemTime> {
/// When the inode of the file `m` describes, at `_path`, last changed (its ctime): any write to
/// the file, or change of its times, sets it to the present, and no program can set it otherwise.
pub fn changed(_path: &Path, m: &std::fs::Metadata) -> Option<std::time::SystemTime> {
use std::os::unix::fs::MetadataExt;
let secs = u64::try_from(m.ctime()).ok()?;
let nanos = u32::try_from(m.ctime_nsec()).ok()?;
@@ -423,6 +449,105 @@ pub fn allocated(m: &std::fs::Metadata) -> u64 {
m.blocks() * 512
}
/// The bytes of the file at `p` that no other file shares, as the file system counts its
/// reflinks: the extents FIEMAP does not mark shared, as btrfs and XFS mark them (on a file
/// system that makes no reflinks, all of them); None where it answers no FIEMAP (tmpfs).
#[cfg(target_os = "linux")]
pub fn private_bytes(p: &Path) -> Option<u64> {
use std::os::fd::AsRawFd;
/// struct fiemap and struct fiemap_extent (linux/fiemap.h).
#[repr(C)]
struct Fiemap {
start: u64,
length: u64,
flags: u32,
mapped: u32,
count: u32,
reserved: u32,
extents: [Extent; 256],
}
#[repr(C)]
#[derive(Clone, Copy)]
struct Extent {
logical: u64,
physical: u64,
length: u64,
reserved64: [u64; 2],
flags: u32,
reserved: [u32; 3],
}
/// _IOWR('f', 11, struct fiemap), the header of 32 bytes.
const FS_IOC_FIEMAP: u64 = 0xc020_660b;
const FIEMAP_FLAG_SYNC: u32 = 1;
const FIEMAP_EXTENT_LAST: u32 = 1;
const FIEMAP_EXTENT_SHARED: u32 = 0x2000;
let f = std::fs::File::open(p).ok()?;
let mut private = 0;
let mut at = 0u64;
loop {
// SAFETY: all zeros is a valid Fiemap.
let mut m: Box<Fiemap> = Box::new(unsafe { std::mem::zeroed() });
m.start = at;
m.length = u64::MAX - at;
m.flags = FIEMAP_FLAG_SYNC;
m.count = m.extents.len() as u32;
// SAFETY: m is a struct fiemap with room for `count` extents, alive for the call.
if unsafe { libc::ioctl(f.as_raw_fd(), FS_IOC_FIEMAP as _, &mut *m as *mut Fiemap) } != 0 {
return None;
}
let got = &m.extents[..(m.mapped as usize).min(m.extents.len())];
for e in got {
if e.flags & FIEMAP_EXTENT_SHARED == 0 {
private += e.length;
}
}
match got.last() {
Some(e) if e.flags & FIEMAP_EXTENT_LAST == 0 => at = e.logical + e.length,
_ => return Some(private),
}
}
}
/// The bytes of the file at `p` that no other file shares, as APFS counts its clones: its private
/// size (getattrlist's ATTR_CMNEXT_PRIVATESIZE); None where the file system answers none.
#[cfg(target_os = "macos")]
pub fn private_bytes(p: &Path) -> Option<u64> {
use std::os::unix::ffi::OsStrExt;
#[repr(C, packed(4))]
struct Answer {
length: u32,
returned: libc::attribute_set_t,
private: libc::off_t,
}
let path = std::ffi::CString::new(p.as_os_str().as_bytes()).ok()?;
let mut list = libc::attrlist {
bitmapcount: libc::ATTR_BIT_MAP_COUNT,
reserved: 0,
commonattr: libc::ATTR_CMN_RETURNED_ATTRS,
volattr: 0,
dirattr: 0,
fileattr: 0,
forkattr: libc::ATTR_CMNEXT_PRIVATESIZE,
};
// SAFETY: all zeros is a valid Answer.
let mut a: Answer = unsafe { std::mem::zeroed() };
// SAFETY: path is NUL-terminated, and list and a are alive for the call, a of its size.
let r = unsafe {
libc::getattrlist(
path.as_ptr(),
(&mut list as *mut libc::attrlist).cast(),
(&mut a as *mut Answer).cast(),
std::mem::size_of::<Answer>(),
libc::FSOPT_ATTR_CMN_EXTENDED,
)
};
let returned = { a.returned };
let private = { a.private };
(r == 0 && returned.forkattr & libc::ATTR_CMNEXT_PRIVATESIZE != 0)
.then(|| u64::try_from(private).ok())
.flatten()
}
/// Whether `a` and `b`, which exist, are on one file system: the same device.
pub fn same_file_system(a: &Path, b: &Path) -> bool {
use std::os::unix::fs::MetadataExt as _;
+65 -4
View File
@@ -197,15 +197,70 @@ pub fn owned_by_me(_m: &std::fs::Metadata) -> bool {
true
}
/// What tells the file at `path` from another put there since: its volume's serial number and
/// its file index, which a new file has its own of, as std's metadata does not give. Not its
/// creation time: NTFS gives a file made at a name moments after another left it that file's
/// creation time (its "tunneling"), as an update's set-aside copy is made. None where the file
/// cannot be opened to read its attributes.
pub fn file_id(path: &Path, _m: &std::fs::Metadata) -> Option<(u64, u64)> {
use std::os::windows::fs::OpenOptionsExt;
use std::os::windows::io::AsRawHandle;
use windows_sys::Win32::Storage::FileSystem::{
BY_HANDLE_FILE_INFORMATION, FILE_READ_ATTRIBUTES, GetFileInformationByHandle,
};
let f = std::fs::OpenOptions::new()
.access_mode(FILE_READ_ATTRIBUTES)
.open(path)
.ok()?;
let mut info = BY_HANDLE_FILE_INFORMATION::default();
// SAFETY: the handle is the open file's, and the call writes the structure given.
if unsafe { GetFileInformationByHandle(f.as_raw_handle(), &mut info) } == 0 {
return None;
}
let index = (u64::from(info.nFileIndexHigh) << 32) | u64::from(info.nFileIndexLow);
Some((u64::from(info.dwVolumeSerialNumber), index))
}
/// The group that owns the file `m` describes: none on Windows.
pub fn gid(_m: &std::fs::Metadata) -> Option<u32> {
None
}
/// When the file `m` describes last changed, as Unix's ctime tells: none, as std's metadata on
/// Windows gives no such time.
pub fn changed(_m: &std::fs::Metadata) -> Option<std::time::SystemTime> {
None
/// When the file at `path` last changed, as Unix's ctime tells: its change time, which NTFS sets
/// to the present at any write to the file and any change of its times or attributes, and which
/// std's metadata does not give (`FILE_BASIC_INFO`'s `ChangeTime`). None where the file system
/// keeps none, which it answers as 0, or the file's attributes cannot be read. Opened to read its
/// attributes alone, the file is read while another program, a running QEMU among them, has it
/// open however it shares it.
pub fn changed(path: &Path, _m: &std::fs::Metadata) -> Option<std::time::SystemTime> {
use std::os::windows::fs::OpenOptionsExt;
use std::os::windows::io::AsRawHandle;
use windows_sys::Win32::Storage::FileSystem::{
FILE_BASIC_INFO, FILE_READ_ATTRIBUTES, FileBasicInfo, GetFileInformationByHandleEx,
};
/// The Unix epoch, 1970-01-01, in a FILETIME's 100 ns units since 1601-01-01.
const UNIX_EPOCH_TICKS: i64 = 116_444_736_000_000_000;
let f = std::fs::OpenOptions::new()
.access_mode(FILE_READ_ATTRIBUTES)
.open(path)
.ok()?;
let mut info = FILE_BASIC_INFO::default();
// SAFETY: the handle is the open file's, and the buffer is a FILE_BASIC_INFO of the size
// given, which FileBasicInfo asks for.
let ok = unsafe {
GetFileInformationByHandleEx(
f.as_raw_handle(),
FileBasicInfo,
(&mut info as *mut FILE_BASIC_INFO).cast(),
std::mem::size_of::<FILE_BASIC_INFO>() as u32,
)
};
if ok == 0 || info.ChangeTime <= 0 {
return None;
}
let ticks = u64::try_from(info.ChangeTime - UNIX_EPOCH_TICKS).ok()?;
let since = std::time::Duration::new(ticks / 10_000_000, (ticks % 10_000_000) as u32 * 100);
Some(std::time::UNIX_EPOCH + since)
}
/// Whether this process may open the file `p` to read and write it.
@@ -1137,6 +1192,12 @@ pub fn allocated(m: &std::fs::Metadata) -> u64 {
m.len()
}
/// The bytes of the file at `p` that no other file shares: None, as Windows tells no file's
/// share of the clusters a block clone shares.
pub fn private_bytes(_p: &Path) -> Option<u64> {
None
}
/// Whether `a` and `b`, which exist, are on one volume: the same volume path
/// (`GetVolumePathNameW`, which a folder a volume is mounted on answers too).
pub fn same_file_system(a: &Path, b: &Path) -> bool {
+4
View File
@@ -43,6 +43,10 @@ pub fn home() -> PathBuf {
/// after a `\`; elsewhere as it is.
pub fn native(p: PathBuf) -> PathBuf {
if cfg!(windows) {
if crate::vm::is_windows_raw_device(&p) {
let s = p.to_string_lossy().replace('/', "\\");
return PathBuf::from(s.trim_end_matches('\\'));
}
p.components().collect()
} else {
p
+16 -30
View File
@@ -53,8 +53,7 @@ impl Kext {
}
// What build.rs embeds: the sets, `SET` and `SET_ARM64E`, each None where the checkout it was
// built from had none, and `AMBROSIA_MODULE`, None where clang could not build it; for Windows,
// neither `SET_ARM64E` nor `AMBROSIA_MODULE`.
// built from had none, and `AMBROSIA_MODULE`, None where clang could not build it.
include!(concat!(env!("OUT_DIR"), "/set.rs"));
/// The config.plist of the device's bundle for Ambrosia, `firmware/ambrosia/config.plist`: it
@@ -381,8 +380,12 @@ fn newc_member(out: &mut Vec<u8>, ino: u32, mode: u32, path: &str, data: &[u8])
Ok(())
}
/// The bundles of the guest's kexts, written there if they are not, in the set's order.
/// The bundles of the guest's kexts, written there if they are not, in the set's order; for
/// every OpenCore image reims-util makes with them. Refused where this reims-ctl was updated
/// since it started: the image would hold this build's kexts, which don't match the installed
/// QEMU ([`crate::update::refuse_replaced`]).
pub fn guest_kexts() -> Result<Vec<PathBuf>> {
crate::update::refuse_replaced()?;
kexts_in(&dir(), set()?)
}
@@ -402,17 +405,6 @@ fn hash<'a>(parts: impl IntoIterator<Item = &'a [u8]>) -> String {
format!("{h:016x}")
}
/// A name for a file or directory written beside its place, apart from every other writer's.
fn beside(place: &Path) -> PathBuf {
let t = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_nanos();
let mut name = place.file_name().unwrap_or_default().to_os_string();
name.push(format!(".{}-{t}.tmp", std::process::id()));
place.with_file_name(name)
}
/// `rom` in `dir`, as [`rom_file`] names it.
fn rom_in(dir: &Path, rom: &[u8]) -> Result<PathBuf> {
file_in(dir, "ReimsGraphics", "rom", rom)
@@ -425,12 +417,7 @@ fn file_in(dir: &Path, stem: &str, ext: &str, bytes: &[u8]) -> Result<PathBuf> {
return Ok(file);
}
std::fs::create_dir_all(dir).with_context(|| format!("create {}", dir.display()))?;
let tmp = beside(&file);
let written = std::fs::write(&tmp, bytes).and_then(|()| std::fs::rename(&tmp, &file));
if let Err(e) = written {
let _ = std::fs::remove_file(&tmp);
return Err(e).with_context(|| format!("write {}", file.display()));
}
crate::record::replace(&file, bytes).with_context(|| format!("write {}", file.display()))?;
Ok(file)
}
@@ -457,7 +444,7 @@ fn kexts_in(dir: &Path, set: &[Kext]) -> Result<Vec<PathBuf>> {
if whole(&place) {
return Ok(bundles(&place));
}
let tmp = beside(&place);
let tmp = crate::record::beside(&place);
let write = || -> std::io::Result<()> {
for k in set {
for (p, b) in k.files {
@@ -475,7 +462,7 @@ fn kexts_in(dir: &Path, set: &[Kext]) -> Result<Vec<PathBuf>> {
// One that is not whole, left by an earlier write that stopped, goes aside first; one a writer
// at once with this one renamed into place first is whole, and stays.
if place.exists() && !whole(&place) {
let old = beside(&place);
let old = crate::record::beside(&place);
if std::fs::rename(&place, &old).is_ok() {
let _ = std::fs::remove_dir_all(&old);
}
@@ -834,18 +821,17 @@ mod tests {
);
}
/// A reims-ctl for Windows, which runs no arm64 VM, carries neither the arm64 set nor the
/// module (build.rs).
#[cfg(windows)]
/// Every reims-ctl carries the arm64 guest's set, Windows' among them (build.rs): a checkout
/// without guest/prebuilt-arm64e fails here.
#[test]
fn a_reims_ctl_for_windows_carries_no_arm64_guest() {
assert!(super::SET_ARM64E.is_none());
assert!(AMBROSIA_MODULE.is_none());
fn the_arm64_set_is_carried() {
let set = super::SET_ARM64E.expect("guest/prebuilt-arm64e/set.toml");
assert!(!set.is_empty());
}
/// The module build.rs built is an aarch64 ELF static PIE, the module format Ambrosia loads:
/// a checkout whose clang can't build it fails here, not at an arm64 VM's start.
#[cfg(not(windows))]
/// a checkout whose clang can't build it fails here, not at an arm64 VM's start, on every host
/// reims-ctl builds on, Windows among them.
#[test]
fn the_module_is_built() {
let elf = AMBROSIA_MODULE.expect(
+219
View File
@@ -0,0 +1,219 @@
//! The processor an x86-64 guest's About This Mac names, from the host's CPU.
//!
//! macOS names the processor from two values of the guest's, never from CPUID's brand string:
//! Apple's processor type, SMBIOS type 131, whose high byte is the family ("Intel Core i7"), and
//! the core count `machdep.cpu.core_count` reads, which with QEMU's CPU is the VM's vCPUs rounded
//! up to a power of two: 4 for 3 vCPUs, 8 for 5 to 8, 16 for 9 to 16 (measured at 3 to 9 vCPUs on
//! macOS 26.7.2; System Information's "Total Number of Cores" is the vCPUs themselves, SMBIOS type
//! 4's). The name is the family with that count before it, "Quad-Core Intel Core i7", where Apple's
//! table of names has that pair, and "Unknown" where it has not: the table is Intel's Macs'
//! (AppleSystemInfo's Processors.loctable), which has, among others, "Dual-Core" and "Quad-Core
//! Intel Core i3", "Dual-Core", "Quad-Core", "6-Core" and "8-Core Intel Core i5" and "Intel Core
//! i7", "6-Core", "8-Core" and "10-Core Intel Core i9", "Single-Core", "Dual-Core", "Quad-Core" and
//! "6-Core Intel Xeon", and "8-Core" to "28-Core Intel Xeon W". Only the powers of two are reached,
//! so a VM of 9 vCPUs or more on a Core i9 host is "Unknown" (16 cores), as is one of 5 to 8 on a
//! Core i3 host. About This Mac, Settings' About and System Information show the same name ("x86-64
//! macOS guests: About This Mac", docs/qemu.md).
//!
//! OpenCore writes type 131 from its config.plist's PlatformInfo > Generic > ProcessorType, and
//! picks one itself where that is 0, as reims-util's images have it: from QEMU's CPU, model 0x5E,
//! with no family in its brand string, it picks 0x0905, Core i3, which shows as "Quad-Core Intel
//! Core i3" with 4 vCPUs and "Unknown" with 8 (measured on macOS 26.7.2). reims-ctl writes the
//! value for the host's CPU on cold starts when the image uses automatic detection
//! ([`crate::opencore::match_processor_type`]). Where Apple has no name for the family and core
//! count, the image keeps its setting. The processor type controls the displayed name.
/// A family of the host's CPU that Apple has names for.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Family {
CoreI3,
CoreI5,
CoreI7,
CoreI9,
Xeon,
}
impl Family {
/// The family a CPU's brand string states, by its words, whatever their case, "(R)" and
/// "(TM)" aside:
/// - Intel's "i3", "i5", "i7" and "i9", alone or before a model number ("Core(TM) i7-8700B");
/// - Intel's newer "Core Ultra 5", "Core Ultra 7" and "Core Ultra 9", and "Core 3" to "Core 7",
/// as the same steps;
/// - "Xeon", and AMD's "Threadripper" and "EPYC", as Xeon;
/// - AMD's "Ryzen 3", "Ryzen 5", "Ryzen 7" and "Ryzen 9", "AI" and "PRO" between the two
/// words read past ("Ryzen AI 9 HX 370"), as i3 to i9, the same rank.
///
/// None for any other: a Pentium, a Celeron, a Core 2, an Athlon, an "AI Max+".
pub fn of(brand: &str) -> Option<Family> {
let words: Vec<String> = brand
.to_ascii_lowercase()
.replace("(r)", " ")
.replace("(tm)", " ")
.split(|c: char| c.is_whitespace() || c == '-')
.filter(|w| !w.is_empty())
.map(String::from)
.collect();
let has = |w: &str| words.iter().any(|x| x == w);
if has("xeon") || has("threadripper") || has("epyc") {
return Some(Family::Xeon);
}
let rank = |w: &str| match w {
"3" | "i3" => Some(Family::CoreI3),
"5" | "i5" => Some(Family::CoreI5),
"7" | "i7" => Some(Family::CoreI7),
"9" | "i9" => Some(Family::CoreI9),
_ => None,
};
if let Some(f) = words
.iter()
.find_map(|w| w.starts_with('i').then(|| rank(w)).flatten())
{
return Some(f);
}
// The rank after "Core" ("Ultra" read past) or "Ryzen" ("AI" and "PRO" read past).
words.iter().enumerate().find_map(|(i, w)| {
let skip: &[&str] = match w.as_str() {
"core" => &["ultra"],
"ryzen" => &["ai", "pro"],
_ => return None,
};
let next = words[i + 1..]
.iter()
.find(|x| !skip.contains(&x.as_str()))?;
next.parse::<u8>().ok().and_then(|_| rank(next))
})
}
/// Apple's processor type for the family, in a guest of `cpus` vCPUs: a value Intel's Macs
/// had, whose family Apple's table names at the core count macOS reads, `cpus` rounded up to
/// a power of two, where any of the family's types is named there. A Xeon is "Intel Xeon",
/// 0x0501, up to 4 vCPUs, and "Intel Xeon W", 0x0F01, from 5 to 16: macOS counts 5 to 8 vCPUs as 8
/// cores, which "Intel Xeon" has no name for and "Intel Xeon W" has. Returns 0 where Apple has no name.
pub fn processor_type(self, cpus: u32) -> u16 {
match (self, cpus) {
(Family::CoreI3, 2..=4) => 0x0909,
(Family::CoreI5, 2..=8) => 0x0609,
(Family::CoreI7, 2..=8) => 0x0709,
(Family::CoreI9, 5..=8) => 0x1009,
(Family::Xeon, 1..=4) => 0x0501,
(Family::Xeon, 5..=16) => 0x0F01,
_ => 0,
}
}
}
/// The ProcessorType an x86-64 VM of `cpus` vCPUs gets on a host whose CPU's brand string is
/// `brand`: its family's ([`Family::processor_type`]), or 0, OpenCore's own pick, where it states
/// none or the host gives none.
pub fn processor_type(brand: Option<&str>, cpus: u32) -> u16 {
brand
.and_then(Family::of)
.map_or(0, |f| f.processor_type(cpus))
}
/// Apple's name for the family of a processor type, as About This Mac shows it after the core
/// count: "Intel Core i7"; None for 0 and any type reims-ctl does not write.
pub fn family_name(processor_type: u16) -> Option<&'static str> {
Some(match processor_type >> 8 {
0x09 => "Intel Core i3",
0x06 => "Intel Core i5",
0x07 => "Intel Core i7",
0x10 => "Intel Core i9",
0x05 => "Intel Xeon",
0x0F => "Intel Xeon W",
_ => return None,
})
}
#[cfg(test)]
mod tests {
use super::*;
/// Each brand string to the family it states: Intel's words from the first Core i7 to Core
/// Ultra, Xeon's, and AMD's Ryzen ranks, Threadripper and EPYC; None where it states none.
#[test]
fn a_brand_string_states_its_family() {
use Family::*;
let cases: &[(&str, Option<Family>)] = &[
(
"Intel(R) Core(TM) i7 CPU 920 @ 2.67GHz",
Some(CoreI7),
),
("Intel(R) Core(TM) i3-8100B CPU @ 3.60GHz", Some(CoreI3)),
("Intel(R) Core(TM) i5-1035G1 CPU @ 1.00GHz", Some(CoreI5)),
("Intel(R) Core(TM) i7-8700B CPU @ 3.20GHz", Some(CoreI7)),
("12th Gen Intel(R) Core(TM) i7-12700H", Some(CoreI7)),
("13th Gen Intel(R) Core(TM) i9-13900H", Some(CoreI9)),
("Intel(R) Core(TM) Ultra 5 125H", Some(CoreI5)),
("Intel(R) Core(TM) Ultra 7 155H", Some(CoreI7)),
("Intel(R) Core(TM) Ultra 9 275HX", Some(CoreI9)),
("Intel(R) Core(TM) 3 100U", Some(CoreI3)),
("Intel(R) Core(TM) 7 150U", Some(CoreI7)),
("Intel(R) Xeon(R) W-2145 CPU @ 3.70GHz", Some(Xeon)),
("Intel(R) Xeon(R) CPU E5-2680 v4 @ 2.40GHz", Some(Xeon)),
("Intel(R) Xeon(R) Gold 6338 CPU @ 2.00GHz", Some(Xeon)),
("AMD Ryzen 3 3200G with Radeon Vega Graphics", Some(CoreI3)),
("AMD Ryzen 5 5600X 6-Core Processor", Some(CoreI5)),
("AMD Ryzen 5 PRO 4650G with Radeon Graphics", Some(CoreI5)),
("AMD Ryzen 7 7840HS w/ Radeon 780M Graphics", Some(CoreI7)),
("AMD Ryzen 7 8745H w/ Radeon 780M Graphics", Some(CoreI7)),
("AMD Ryzen 9 7950X 16-Core Processor", Some(CoreI9)),
("AMD Ryzen AI 9 HX 370 w/ Radeon 890M", Some(CoreI9)),
("AMD Ryzen AI 7 PRO 360 w/ Radeon 880M", Some(CoreI7)),
("AMD Ryzen Threadripper PRO 5995WX 64-Cores", Some(Xeon)),
("AMD EPYC 7763 64-Core Processor", Some(Xeon)),
("Intel(R) Core(TM)2 Duo CPU E8400 @ 3.00GHz", None),
("Intel(R) Core(TM) m3-7Y30 CPU @ 1.00GHz", None),
("Intel(R) Pentium(R) Gold 7505 @ 2.00GHz", None),
("Intel(R) Celeron(R) N4020 CPU @ 1.10GHz", None),
("Intel(R) N100", None),
("AMD Athlon Silver 3050U with Radeon Graphics", None),
("AMD Ryzen AI Max+ 395 w/ Radeon 8060S", None),
("AMD Ryzen Z1 Extreme", None),
("Intel Core Processor (Skylake, IBRS, no TSX)", None),
("", None),
];
for (brand, family) in cases {
assert_eq!(Family::of(brand), *family, "{brand:?}");
}
}
/// The value for each family, which Apple's table names: Core i3 to i9 by their family's
/// type at a supported count, a Xeon as "Intel Xeon" up to 4 vCPUs and "Intel Xeon W" from 5;
/// 0 where the host states no family, or gives no brand string.
#[test]
fn each_family_has_its_processor_type() {
let i7 = Some("AMD Ryzen 7 7840HS w/ Radeon 780M Graphics");
assert_eq!(processor_type(i7, 8), 0x0709);
assert_eq!(processor_type(i7, 4), 0x0709);
assert_eq!(
processor_type(Some("13th Gen Intel(R) Core(TM) i9-13900H"), 8),
0x1009
);
assert_eq!(
processor_type(Some("Intel(R) Core(TM) i3-8100B"), 4),
0x0909
);
assert_eq!(
processor_type(Some("Intel(R) Core(TM) Ultra 5 125H"), 6),
0x0609
);
let xeon = Some("Intel(R) Xeon(R) W-2145 CPU @ 3.70GHz");
assert_eq!(processor_type(xeon, 1), 0x0501);
assert_eq!(processor_type(xeon, 4), 0x0501);
assert_eq!(processor_type(xeon, 5), 0x0F01);
assert_eq!(processor_type(xeon, 6), 0x0F01);
assert_eq!(processor_type(xeon, 8), 0x0F01);
assert_eq!(processor_type(Some("Intel(R) Pentium(R) Gold 7505"), 4), 0);
assert_eq!(
processor_type(Some("Intel(R) Core(TM) i5-12400"), 8),
0x0609
);
assert_eq!(processor_type(Some("Intel(R) Core(TM) i9-13900H"), 4), 0);
assert_eq!(processor_type(None, 8), 0);
for t in [0x0909, 0x0609, 0x0709, 0x1009, 0x0501, 0x0F01] {
assert!(family_name(t).is_some(), "{t:#06x}");
}
assert_eq!(family_name(0), None);
}
}
File diff suppressed because it is too large. Load diff
+476
View File
@@ -0,0 +1,476 @@
//! The TOML files reims-ctl keeps its records in, written so that what another build of reims-ctl
//! wrote into them stays as it was ([`text_over`]): each VM's `vm.toml`, the registry
//! (`vms.toml`), the install's record (`install.toml`) and the migrations' (`migrations.toml`).
//!
//! A newer build may add keys to a record, and an older build may save the same file: one still
//! open from before an update, or one a switch of channel installed. Re-serialising its own struct
//! would drop the keys it does not know. So each save edits the file as it is, with `toml_edit`:
//! a key the saving build does not know keeps its place and its form, and so does each key it
//! knows whose value it leaves unchanged; only what it changes is written. A record of any type
//! that serializes to TOML and reads back as itself can be written this way.
//!
//! A file this build cannot edit so is never written over: the save is refused ([`Refused`]),
//! and the file stays as it is. So is one it cannot read: a save reads the file as it is with
//! [`old_text`], which takes only a file that is not there for no file.
//!
//! A save writes the record's text into a file of its own beside it and renames that over it
//! ([`replace`]): a reader never meets the record half-written, and of two saves at once, from
//! two processes or two threads, the last rename leaves its whole text, never a mix of the two.
use anyhow::Result;
use serde::Serialize;
use serde::de::DeserializeOwned;
use std::path::{Path, PathBuf};
use toml_edit::{ArrayOfTables, DocumentMut, Item, Table, TableLike};
/// A save refused because its record's file holds what this build cannot keep through it
/// ([`text_over`]): the file is left as it is.
#[derive(Debug)]
pub struct Refused {
/// The record's file.
pub file: PathBuf,
/// Why this build cannot keep what the file holds.
pub why: String,
}
impl std::fmt::Display for Refused {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{} was left as it is: {}. Saving over it would drop what it holds that this \
reims-ctl doesn't know, which a newer reims-ctl may have written. Update or restart \
reims-ctl, or move the file aside and try again",
crate::paths::tilde(&self.file),
self.why
)
}
}
impl std::error::Error for Refused {}
/// `record`'s text written over `old`, the text of its file, `file`, as it is now, where there is
/// one: `old` itself, edited in place.
/// - A key this build reads is written as `record` has it. Its value is replaced where it
/// differs, keeping the old value's place and spacing. The key is removed where `record`
/// leaves it out, as a cleared setting is, and added at the end of its table where `old` lacks
/// it.
/// - Every other key stays where and as it is: one a newer build wrote. The exceptions are the
/// `retired` keys, as dotted paths (`display.hidpi`), which an older build wrote and this one
/// reads past and drops.
/// - A `[[name]]` array's tables are matched to `old`'s by what this build reads of them, so a
/// table left as it was keeps its other keys while others are added or removed.
///
/// `record`'s own text where there is no file. Refused ([`Refused`]) where `old` is not TOML this
/// build reads, or not TOML it reads as such a record, as a newer build may write, or where the
/// edited text would not read back as `record`, as a key this build reads under another name
/// would make it: a write would drop what the file holds.
pub fn text_over<T>(record: &T, file: &Path, old: Option<&str>, retired: &[&str]) -> Result<String>
where
T: Serialize + DeserializeOwned + PartialEq,
{
let new = toml::to_string_pretty(record)?;
let Some(old) = old else {
return Ok(new);
};
edited(record, old, &new, retired).map_err(|why| {
Refused {
file: file.to_path_buf(),
why,
}
.into()
})
}
/// A name for a file or directory written beside `place` and then renamed into it, apart from
/// every other writer's: `.<name>.<pid>-<n>.tmp`, `n` counting the names this process gave. Two
/// writers sharing one name would write into one file, each truncating what the other wrote,
/// and the first rename would install it while the second still writes.
pub fn beside(place: &Path) -> PathBuf {
static GIVEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let n = GIVEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let mut name = std::ffi::OsString::from(".");
name.push(place.file_name().unwrap_or_default());
name.push(format!(".{}-{n}.tmp", std::process::id()));
place.with_file_name(name)
}
/// Writes `bytes` over `file` through a file of its own beside it ([`beside`]), renamed over
/// `file` once written, so `file` holds either what it held or all of `bytes`; the file beside
/// it is removed where the write or the rename fails.
pub fn replace(file: &Path, bytes: &[u8]) -> std::io::Result<()> {
let tmp = beside(file);
let written = std::fs::write(&tmp, bytes).and_then(|()| std::fs::rename(&tmp, file));
if written.is_err() {
let _ = std::fs::remove_file(&tmp);
}
written
}
/// The files written beside `place` ([`beside`]) that are there still: none once every save
/// ended, as each renames its own or removes it.
#[cfg(test)]
pub fn left_beside(place: &Path) -> Vec<PathBuf> {
let mut head = std::ffi::OsString::from(".");
head.push(place.file_name().unwrap_or_default());
head.push(".");
let head = head.to_string_lossy().into_owned();
let Ok(entries) = std::fs::read_dir(place.parent().unwrap_or(Path::new("."))) else {
return Vec::new();
};
(entries.flatten())
.map(|e| e.path())
.filter(|p| {
let name = p.file_name().unwrap_or_default().to_string_lossy();
name.starts_with(&head) && name.ends_with(".tmp")
})
.collect()
}
/// The text of `file`, a record's, as it is now, for a save over it ([`text_over`]): `None` where
/// there is no file. Refused ([`Refused`]) where there is one this build can't read: one that
/// isn't UTF-8, or that a permission or an I/O error keeps from it. A save that took it for no
/// file would write its own text over what the file holds.
pub fn old_text(file: &Path) -> Result<Option<String>> {
match std::fs::read_to_string(file) {
Ok(text) => Ok(Some(text)),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(Refused {
file: file.to_path_buf(),
why: format!("this reims-ctl can't read it ({e})"),
}
.into()),
}
}
/// Checks that `save`, a save of the record whose file is `file`, is refused ([`Refused`], naming
/// `file`) where the file is there and this build can't read it, and leaves the file byte for
/// byte as it was: one that isn't UTF-8, and on Unix one its mode keeps from the test's user,
/// where the mode does (root reads it all the same).
#[cfg(test)]
pub(crate) fn assert_unreadable_refused(file: &Path, save: &dyn Fn() -> Result<()>) {
let refused = |what: &str| {
let e = save().expect_err(what);
let Some(x) = e.downcast_ref::<Refused>() else {
panic!("{what}: not refused: {e:#}");
};
assert_eq!(x.file, file, "{what}");
assert!(
x.why.starts_with("this reims-ctl can't read it ("),
"{what}: {x}"
);
};
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
let not_utf8 = b"name = \"\xff\xfe\"\n";
std::fs::write(file, not_utf8).unwrap();
refused("not UTF-8");
assert_eq!(std::fs::read(file).unwrap(), not_utf8);
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let text = b"name = \"kept\"\n";
std::fs::write(file, text).unwrap();
let mode = |m| {
let mode = std::fs::Permissions::from_mode(m);
std::fs::set_permissions(file, mode).unwrap();
};
mode(0o000);
let kept_from_us = std::fs::read(file).is_err();
if kept_from_us {
refused("unreadable by its mode");
}
mode(0o644);
assert_eq!(std::fs::read(file).unwrap(), text);
}
}
/// [`text_over`]'s edit of `old`, where it can make one that reads back as `record`, whose own
/// text is `new`; else why it cannot.
fn edited<T>(record: &T, old: &str, new: &str, retired: &[&str]) -> Result<String, String>
where
T: Serialize + DeserializeOwned + PartialEq,
{
let mut doc: DocumentMut = old.parse().map_err(|e: toml_edit::TomlError| {
format!("it isn't TOML this reims-ctl reads ({})", e.message())
})?;
let read: T = toml::from_str(old)
.map_err(|e| format!("this reims-ctl can't read what it holds ({})", e.message()))?;
// What this build reads of the file, as it writes it: the keys it knows.
let ours = |r: &T| -> Option<DocumentMut> { toml::to_string_pretty(r).ok()?.parse().ok() };
let (Some(known), Some(new)) = (ours(&read), new.parse::<DocumentMut>().ok()) else {
return Err("this reims-ctl can't write its record as TOML".into());
};
merge_table(
doc.as_table_mut(),
Some(known.as_table() as &dyn TableLike),
new.as_table(),
"",
retired,
);
let text = doc.to_string();
match toml::from_str::<T>(&text) {
Ok(r) if r == *record => Ok(text),
_ => Err("this reims-ctl can't write its changes around what else it holds".into()),
}
}
/// Writes `new`'s keys into `old`, the table at `path`, whose keys this build knows are
/// `known`'s ([`text_over`]).
fn merge_table(
old: &mut dyn TableLike,
known: Option<&dyn TableLike>,
new: &dyn TableLike,
path: &str,
retired: &[&str],
) {
let at = |key: &str| {
if path.is_empty() {
key.to_string()
} else {
format!("{path}.{key}")
}
};
let gone: Vec<String> = old
.iter()
.map(|(k, _)| k.to_string())
.filter(|k| !new.contains_key(k))
.filter(|k| known.is_some_and(|t| t.contains_key(k)) || retired.contains(&at(k).as_str()))
.collect();
for k in gone {
old.remove(&k);
}
for (k, n) in new.iter() {
let known = known.and_then(|t| t.get(k));
match old.get_mut(k) {
Some(o) => merge_item(o, known, n, &at(k), retired),
None => {
let mut n = n.clone();
unplace(&mut n);
old.insert(k, n);
}
}
}
}
/// Writes `new` over `old`, the item at `path`, of which this build knows `known`.
fn merge_item(old: &mut Item, known: Option<&Item>, new: &Item, path: &str, retired: &[&str]) {
if let (Some(o), Some(n)) = (old.as_table_like_mut(), new.as_table_like()) {
merge_table(o, known.and_then(Item::as_table_like), n, path, retired);
return;
}
if let (Some(o), Some(n)) = (old.as_array_of_tables_mut(), new.as_array_of_tables()) {
merge_tables(
o,
known.and_then(Item::as_array_of_tables),
n,
path,
retired,
);
return;
}
if let (Some(o), Some(n)) = (old.as_value_mut(), new.as_value()) {
if read(&Item::Value(o.clone())) != read(&Item::Value(n.clone())) {
let decor = o.decor().clone();
*o = n.clone();
*o.decor_mut() = decor;
}
return;
}
*old = new.clone();
unplace(old);
}
/// Writes `new`'s tables over `old`'s, the `[[path]]` array of which this build knows `known`:
/// each of `new`'s, in its order, is the table of `old`'s that reads as it, with that table's
/// other keys, or else as `new` has it.
fn merge_tables(
old: &mut ArrayOfTables,
known: Option<&ArrayOfTables>,
new: &ArrayOfTables,
path: &str,
retired: &[&str],
) {
let known: Vec<&Table> = known
.filter(|k| k.len() == old.len())
.map(|k| k.iter().collect())
.unwrap_or_default();
let known_read: Vec<_> = known
.iter()
.map(|t| read(&Item::Table((*t).clone())))
.collect();
// Every table at the place of the first, so they stay together, in the array's order.
let place = old.get(0).and_then(Table::position);
let mut used = vec![false; known.len()];
let mut out = ArrayOfTables::new();
for n in new.iter() {
let wanted = read(&Item::Table(n.clone()));
let found = (0..known.len()).find(|&i| !used[i] && known_read[i] == wanted);
let mut t = match (found, found.and_then(|i| old.get(i))) {
(Some(i), Some(o)) => {
used[i] = true;
let mut o = o.clone();
merge_table(&mut o, Some(known[i] as &dyn TableLike), n, path, retired);
o
}
_ => {
let mut n = n.clone();
unplace_table(&mut n);
n
}
};
t.set_position(place);
out.push(t);
}
*old = out;
}
/// What `item` reads as, however it is written: its value as a key's, `v`'s. None where it does
/// not read.
fn read(item: &Item) -> Option<toml::Value> {
let mut item = item.clone();
unplace(&mut item);
let mut doc = DocumentMut::new();
doc.insert("v", item);
toml::from_str::<toml::Table>(&doc.to_string())
.ok()?
.remove("v")
}
/// `item`'s tables with no place of their own in a document: one taken from another document
/// follows the tables before it in the one it joins.
fn unplace(item: &mut Item) {
match item {
Item::Table(t) => unplace_table(t),
Item::ArrayOfTables(a) => a.iter_mut().for_each(unplace_table),
_ => {}
}
}
fn unplace_table(t: &mut Table) {
t.set_position(None);
for (_, item) in t.iter_mut() {
unplace(item);
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde::Deserialize;
#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Record {
n: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
note: Option<String>,
inner: Inner,
#[serde(default, rename = "item", skip_serializing_if = "Vec::is_empty")]
items: Vec<Element>,
}
#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Inner {
a: bool,
}
#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Element {
id: String,
}
fn record(text: &str) -> Record {
toml::from_str(text).unwrap()
}
/// The file the tests' records are written over.
fn file() -> &'static Path {
Path::new("/r/record.toml")
}
/// A file another build wrote, with keys, a table and comments of its own and values in
/// forms this build does not write, is edited where this build's record changes, and stays
/// as it was elsewhere: an unchanged value keeps its form, and a changed one its comment.
#[test]
fn a_record_is_written_over_its_file_as_the_file_is() {
let old = "# kept\nn = 0x10 # sixteen\nnote = 'hi'\nlater = [1, 2]\n\n[inner]\na = true\n\
b = \"another build's\"\n\n[theirs]\nx = 1\n";
let mut r = record(old);
assert_eq!(
r,
Record {
n: 16,
note: Some("hi".into()),
inner: Inner { a: true },
items: vec![],
}
);
let same = text_over(&r, file(), Some(old), &[]).unwrap();
assert_eq!(same, old);
r.n = 17;
r.note = None;
r.inner.a = false;
let edited = text_over(&r, file(), Some(old), &[]).unwrap();
assert_eq!(
edited,
"# kept\nn = 17 # sixteen\nlater = [1, 2]\n\n[inner]\na = false\n\
b = \"another build's\"\n\n[theirs]\nx = 1\n"
);
assert_eq!(record(&edited), r);
// Retired keys go.
let retired = text_over(&r, file(), Some(&edited), &["later", "inner.b"]).unwrap();
assert_eq!(
retired,
"# kept\nn = 17 # sixteen\n\n[inner]\na = false\n\n[theirs]\nx = 1\n"
);
}
/// A `[[item]]` table this build leaves as it was keeps the keys it does not know, while one
/// before it is removed and another is added after it.
#[test]
fn an_array_s_tables_keep_their_keys_as_others_come_and_go() {
let old = "n = 1\n\n[inner]\na = true\n\n[[item]]\nid = \"a\"\nspeed = 1\n\n\
[[item]]\nid = \"b\"\nspeed = 2\n";
let mut r = record(old);
r.items.remove(0);
r.items.push(Element { id: "c".into() });
let text = text_over(&r, file(), Some(old), &[]).unwrap();
assert!(
text.starts_with("n = 1\n\n[inner]\na = true\n\n[[item]]\nid = \"b\"\nspeed = 2\n"),
"{text}"
);
assert!(text.ends_with("[[item]]\nid = \"c\"\n"), "{text}");
assert!(!text.contains("\"a\""), "{text}");
assert_eq!(record(&text), r);
}
/// With no file, the record's own text is written. A file whose keys this build can't keep
/// through the save is refused, typed and naming the file, so it is left as it is: one that
/// isn't TOML, one this build can't read as the record, as a newer build may write, and one
/// whose edit wouldn't read back as the record, as a key this build reads under another name
/// makes it.
#[test]
fn a_file_this_build_cannot_keep_is_refused() {
let r = record("n = 1\n[inner]\na = true\n");
let own = toml::to_string_pretty(&r).unwrap();
assert_eq!(text_over(&r, file(), None, &[]).unwrap(), own);
let refused = |e: anyhow::Error| {
let x = e.downcast_ref::<Refused>().expect("a Refused");
assert_eq!(x.file, file());
assert!(x.to_string().contains(" was left as it is: "), "{x}");
x.why.clone()
};
let not_toml = refused(text_over(&r, file(), Some("n = ["), &[]).unwrap_err());
assert!(not_toml.starts_with("it isn't TOML"), "{not_toml}");
let other = "n = \"one\"\n[inner]\na = true\n";
let unread = refused(text_over(&r, file(), Some(other), &[]).unwrap_err());
assert!(unread.starts_with("this reims-ctl can't read"), "{unread}");
#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Renamed {
#[serde(alias = "count")]
n: u32,
}
let e = text_over(&Renamed { n: 2 }, file(), Some("count = 1\n"), &[]).unwrap_err();
let around = refused(e);
assert!(around.contains("around what else it holds"), "{around}");
}
}
+116 -10
View File
@@ -1,4 +1,4 @@
//! reims-util (<https://github.com/steelbrain/reims-util>) makes what a new x86-64 VM boots from:
//! reims-util (<https://github.com/reims-go/reims-util>) makes what a new x86-64 VM boots from:
//! an OpenCore image, with OVMF's code and variables beside it, and a macOS installer, downloaded
//! from Apple and checked against Apple's chunklists. It also makes an existing VM a new OpenCore
//! image presenting the same Mac (opencore.rs). For a VM on reims-vgpu's own device, an image
@@ -43,9 +43,9 @@ use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
pub const REPO: &str = "https://github.com/steelbrain/reims-util";
pub const REPO: &str = "https://github.com/reims-go/reims-util";
/// The commit [`install`] installs.
pub const REV: &str = "7867384c0ab703b4c6aae36cbbb1a35fcffc8321";
pub const REV: &str = "c363a029b1a9bce696184b3247e6465aa11321bc";
/// The reims-util binary: `REIMS_CTL_UTIL`, else the one beside reims-ctl, where both are
/// installed, else the first on PATH.
@@ -342,7 +342,7 @@ pub fn opencore(
args.extend(["--model", m]);
}
args.extend(kexts.iter().map(String::as_str));
make_opencore(image, &args, progress)
make_opencore(image, &args, None, progress)
}
/// Makes an OpenCore image at `image` presenting the Mac `id`, for a VM that has its OVMF: no
@@ -353,6 +353,7 @@ pub fn opencore_as(
id: &Identity,
show_picker: bool,
kexts: &[String],
preboot_input: Option<&Path>,
progress: &mut dyn FnMut(&str),
) -> Result<()> {
let mut args = identity_args(id);
@@ -361,7 +362,7 @@ pub fn opencore_as(
args.push("--show-picker");
}
args.extend(kexts.iter().map(String::as_str));
make_opencore(image, &args, progress)
make_opencore(image, &args, preboot_input, progress)
}
/// Makes an OpenCore image at `image` presenting the Mac `id`, with `OVMF_CODE.fd` and
@@ -375,7 +376,7 @@ pub fn opencore_presenting(
) -> Result<()> {
let mut args = identity_args(id);
args.extend(kexts.iter().map(String::as_str));
make_opencore(image, &args, progress)
make_opencore(image, &args, None, progress)
}
/// The arguments that make reims-util's image present the Mac `id`.
@@ -386,14 +387,23 @@ fn identity_args(id: &Identity) -> Vec<&str> {
]
}
fn make_opencore(image: &Path, args: &[&str], progress: &mut dyn FnMut(&str)) -> Result<()> {
fn make_opencore(
image: &Path,
args: &[&str],
preboot_input: Option<&Path>,
progress: &mut dyn FnMut(&str),
) -> Result<()> {
let mut all: Vec<&OsStr> = vec!["opencore".as_ref(), "-o".as_ref(), image.as_os_str()];
all.extend(args.iter().map(OsStr::new));
if let Some(dir) = preboot_input {
all.extend([OsStr::new("--preboot-input"), dir.as_os_str()]);
}
let r = run(&all, progress)?;
if let Ok(o) = serde_json::from_value::<OpencoreResult>(r) {
progress(&format!(
"OpenCore presents the VM as an {}, serial {}",
o.smbios.model, o.smbios.serial
"OpenCore presents the VM as {}; its serial is {}",
mac_named(&o.smbios.model),
o.smbios.serial
));
}
Ok(())
@@ -411,7 +421,65 @@ pub fn model_for(version: &str) -> Option<&'static str> {
}
}
fn major(version: &str) -> u32 {
/// The macOS releases the Mac `model` runs, of those an OpenCore image reims-util makes presents
/// ([`model_for`]): the iMac20,1 runs macOS 10.15.6 to 26, and the iMacPro1,1 10.13 to 15. None
/// for another model, which reims-ctl knows no releases of.
pub fn model_runs(model: &str) -> Option<&'static str> {
match model {
"iMac20,1" => Some("macOS 10.15.6 to 26"),
"iMacPro1,1" => Some("macOS 10.13 to 15"),
_ => None,
}
}
/// The SMBIOS Memory Error Correction of the Mac `model`'s RAM, of those an OpenCore image
/// reims-util makes presents ([`model_for`]), which System Information shows as the memory's
/// "ECC": 3, none, for the iMac20,1, whose DDR4 has no ECC, and 6, multi-bit ECC, for the
/// iMacPro1,1, whose DDR4 has ECC. None for another model, whose RAM reims-ctl does not know.
pub fn model_memory_error_correction(model: &str) -> Option<u8> {
match model {
"iMac20,1" => Some(0x03),
"iMacPro1,1" => Some(0x06),
_ => None,
}
}
/// The memory slots of the Mac `model`, of those an OpenCore image reims-util makes presents
/// ([`model_for`]), which System Information lists: the iMac20,1's four SO-DIMM slots (SMBIOS's
/// Form Factor 13). None for another model, whose slots reims-ctl does not know.
pub fn model_memory_slots(model: &str) -> Option<MemorySlots> {
match model {
"iMac20,1" => Some(MemorySlots {
count: 4,
form_factor: 0x0D,
}),
_ => None,
}
}
/// A Mac's memory slots ([`model_memory_slots`]): how many there are, and their SMBIOS Form Factor.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct MemorySlots {
pub count: u16,
pub form_factor: u8,
}
/// The Mac `model` as reims-ctl names it, where it says which Mac a VM's image presents: with the
/// macOS releases it runs ([`model_runs`]), which the VM's must be, as a kept image's Mac was
/// chosen for another macOS.
pub fn mac_named(model: &str) -> String {
let a = if model.starts_with(['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']) {
"an"
} else {
"a"
};
match model_runs(model) {
Some(runs) => format!("{a} {model}, which runs {runs}"),
None => format!("{a} {model}, whose macOS releases reims-ctl does not know"),
}
}
pub(crate) fn major(version: &str) -> u32 {
version
.trim()
.split('.')
@@ -660,6 +728,44 @@ mod tests {
assert_eq!(model_for(""), None);
}
/// The iMac20,1's RAM has no ECC and the iMacPro1,1's has; another model's is unknown.
#[test]
fn a_macs_memory_has_ecc_as_its_ram_does() {
assert_eq!(model_memory_error_correction("iMac20,1"), Some(3));
assert_eq!(model_memory_error_correction("iMacPro1,1"), Some(6));
assert_eq!(model_memory_error_correction("MacPro7,1"), None);
}
/// The iMac20,1 has four SO-DIMM slots; another model's slots are unknown.
#[test]
fn a_macs_memory_has_the_slots_the_mac_has() {
let imac = MemorySlots {
count: 4,
form_factor: 13,
};
assert_eq!(model_memory_slots("iMac20,1"), Some(imac));
assert_eq!(model_memory_slots("iMacPro1,1"), None);
assert_eq!(model_memory_slots("MacPro7,1"), None);
}
/// Each model an image reims-util makes presents is named with the macOS releases it runs,
/// those model_for's choice rests on, and another model as one whose releases are unknown.
#[test]
fn a_mac_is_named_with_the_macos_it_runs() {
assert_eq!(
mac_named("iMac20,1"),
"an iMac20,1, which runs macOS 10.15.6 to 26"
);
assert_eq!(
mac_named("iMacPro1,1"),
"an iMacPro1,1, which runs macOS 10.13 to 15"
);
assert_eq!(
mac_named("MacPro7,1"),
"a MacPro7,1, whose macOS releases reims-ctl does not know"
);
}
#[test]
fn versions_read_reims_utils_list() {
let list: Vec<Version> = serde_json::from_str(
+12 -8
View File
@@ -237,12 +237,13 @@ fn gib(bytes: u64) -> String {
// ------------------------------------------------------------------ stopping
/// Set to stop every restore of this process: at Ctrl-C ([`stop_at_interrupt`]), or as the
/// interface quits.
/// Set to stop every restore of this process, and every conversion of an x86-64 VM's disk: at
/// Ctrl-C ([`stop_at_interrupt`]), or as the interface quits.
static CANCEL: AtomicBool = AtomicBool::new(false);
/// The creates of arm64 VMs running in this process, each from its restore's start to its
/// directory's removal where it fails ([`Busy`]).
/// directory's removal where it fails, and of x86-64 VMs whose disk is converted, each from
/// taking its directory to that ([`Busy`]).
static RUNNING: AtomicUsize = AtomicUsize::new(0);
/// The flag a restore watches.
@@ -255,12 +256,13 @@ pub fn cancel() {
CANCEL.store(true, Ordering::SeqCst);
}
/// The arm64 creates running in this process.
/// The creates running in this process that stop at [`cancel`]: arm64 VMs', and x86-64 VMs'
/// whose disk is converted.
pub fn running() -> usize {
RUNNING.load(Ordering::SeqCst)
}
/// Waits up to `timeout` for every arm64 create to end; whether they did.
/// Waits up to `timeout` for every create [`running`] counts to end; whether they did.
pub fn wait_stopped(timeout: Duration) -> bool {
let end = Instant::now() + timeout;
while running() > 0 {
@@ -272,7 +274,8 @@ pub fn wait_stopped(timeout: Duration) -> bool {
true
}
/// Held by an arm64 create while it runs, its restore and its cleanup.
/// Held by an arm64 create while it runs, its restore and its cleanup, and by an x86-64 create
/// whose disk is converted, from taking its directory to its cleanup.
pub struct Busy(());
impl Busy {
@@ -289,8 +292,9 @@ impl Drop for Busy {
}
/// Ctrl-C (SIGINT) and SIGTERM, and Ctrl+Break on Windows, stop the restores of this process,
/// and the downloads of their IPSWs: a restore's VM directory is removed, a download keeps its
/// part, and the create says the VM was not made.
/// the downloads of their IPSWs and the conversions of x86-64 VMs' disks: a restore's or a
/// conversion's VM directory is removed, a download keeps its part, and the create says the VM
/// was not made.
pub fn stop_at_interrupt() {
crate::os::set_at_interrupt(&CANCEL);
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+212
View File
@@ -0,0 +1,212 @@
//! What reims-ctl reads of a qcow2 image's internal snapshots (QEMU's docs/interop/qcow2.txt):
//! each one's name, and the space it alone holds, which deleting it frees.
//!
//! An image refers to a cluster from its own L1 table and from each snapshot's: a snapshot made
//! by `qemu-img snapshot -c` adds one to the refcount of every L2 table and data cluster the
//! image's L1 table reaches (qcow2-refcount.c, `qcow2_update_snapshot_refcount`), and a write
//! after it copies what it changes. So a cluster a snapshot's L1 table reaches whose refcount is
//! 1 is that snapshot's alone, and an L2 table with a refcount above 1 is shared, as every data
//! cluster in it then is. What a snapshot holds is its L1 table's clusters, and the L2 tables
//! and data clusters it reaches with a refcount of 1. A compressed cluster, which qemu-img
//! writes only when asked to, is counted as held by none.
//!
//! The images read are those qemu-img makes: no external data file, no extended L2 entries, and
//! refcounts of 8 to 64 bits; another is refused. An image over a backing file reads as any
//! other: its snapshots' table, their L1 tables and every cluster they count are in its own file,
//! and a cluster it never wrote, read from the backing file, is in no L2 entry, so held by none.
use crate::os::FileExt;
use anyhow::{Context, Result, ensure};
use std::collections::HashMap;
use std::collections::hash_map::Entry as Slot;
use std::fs::File;
use std::path::Path;
/// Bits 9 to 55 of an L1 or L2 entry, or a refcount table entry: where the table or the cluster
/// is in the file.
const OFFSET: u64 = 0x00ff_ffff_ffff_fe00;
/// An L2 entry's flag for a compressed cluster.
const COMPRESSED: u64 = 1 << 62;
/// The most snapshots, and the longest name, an image may have (qcow2.h's QCOW_MAX_SNAPSHOTS,
/// and a name's 16-bit length).
const MOST_SNAPSHOTS: u32 = 65536;
/// An internal snapshot: its name (qemu-img's tag) and its L1 table.
pub struct Entry {
pub name: String,
l1_offset: u64,
l1_size: u32,
}
pub struct Image {
file: File,
cluster_bits: u32,
refcount_order: u32,
refcount_table: Vec<u64>,
pub snapshots: Vec<Entry>,
}
fn be32(b: &[u8], o: usize) -> u32 {
u32::from_be_bytes(b[o..o + 4].try_into().unwrap())
}
fn be64(b: &[u8], o: usize) -> u64 {
u64::from_be_bytes(b[o..o + 8].try_into().unwrap())
}
fn be16(b: &[u8], o: usize) -> u16 {
u16::from_be_bytes(b[o..o + 2].try_into().unwrap())
}
impl Image {
pub fn open(path: &Path) -> Result<Image> {
let file = File::open(path).with_context(|| format!("open {}", path.display()))?;
Image::of(file).with_context(|| format!("read {}", path.display()))
}
fn of(file: File) -> Result<Image> {
let mut h = [0u8; 104];
file.read_exact_at(&mut h[..72], 0)?;
ensure!(h[..4] == *b"QFI\xfb", "not a qcow2 image");
let version = be32(&h, 4);
let cluster_bits = be32(&h, 20);
ensure!(
(9..=21).contains(&cluster_bits),
"qcow2 clusters of 2^{cluster_bits} bytes"
);
let refcount_order = if version >= 3 {
file.read_exact_at(&mut h[72..104], 72)?;
// An external data file (bit 2) or extended L2 entries (bit 4) lay clusters out
// otherwise.
ensure!(
be64(&h, 72) & (1 << 2 | 1 << 4) == 0,
"a qcow2 image with an external data file or extended L2 entries"
);
be32(&h, 96)
} else {
4
};
ensure!(
(3..=6).contains(&refcount_order),
"a qcow2 image with refcounts of {} bits",
1u64 << refcount_order.min(63)
);
let cluster = 1u64 << cluster_bits;
let table_bytes = u64::from(be32(&h, 56)) * cluster;
ensure!(
table_bytes <= 1 << 30,
"a refcount table of {table_bytes} bytes"
);
let mut table = vec![0u8; table_bytes as usize];
file.read_exact_at(&mut table, be64(&h, 48))?;
let refcount_table = (table.as_chunks::<8>().0.iter())
.map(|e| u64::from_be_bytes(*e))
.collect();
let count = be32(&h, 60);
ensure!(count <= MOST_SNAPSHOTS, "{count} snapshots");
let mut snapshots = Vec::with_capacity(count as usize);
let mut at = be64(&h, 64);
for _ in 0..count {
let mut e = [0u8; 40];
file.read_exact_at(&mut e, at)?;
let extra = u64::from(be32(&e, 36));
let (id_len, name_len) = (u64::from(be16(&e, 12)), u64::from(be16(&e, 14)));
ensure!(
extra <= 1 << 20,
"a snapshot with {extra} bytes of extra data"
);
let mut name = vec![0u8; name_len as usize];
file.read_exact_at(&mut name, at + 40 + extra + id_len)?;
snapshots.push(Entry {
name: String::from_utf8_lossy(&name).into_owned(),
l1_offset: be64(&e, 0),
l1_size: be32(&e, 8),
});
at += (40 + extra + id_len + name_len).next_multiple_of(8);
}
Ok(Image {
file,
cluster_bits,
refcount_order,
refcount_table,
snapshots,
})
}
/// The bytes the snapshot named `name` alone holds: what deleting it frees.
pub fn held(&self, name: &str) -> Result<u64> {
let s = self
.snapshots
.iter()
.find(|s| s.name == name)
.with_context(|| format!("no snapshot named {name}"))?;
let cluster = 1u64 << self.cluster_bits;
let l1_bytes = u64::from(s.l1_size) * 8;
ensure!(l1_bytes <= 1 << 30, "an L1 table of {l1_bytes} bytes");
let mut l1 = vec![0u8; l1_bytes as usize];
self.file.read_exact_at(&mut l1, s.l1_offset)?;
let mut refcounts = Refcounts {
image: self,
blocks: HashMap::new(),
};
let mut held = l1_bytes.div_ceil(cluster) * cluster;
let mut l2 = vec![0u8; cluster as usize];
for e in l1.as_chunks::<8>().0 {
let table = u64::from_be_bytes(*e) & OFFSET;
if table == 0 || refcounts.of(table)? != 1 {
continue;
}
held += cluster;
self.file.read_exact_at(&mut l2, table)?;
for e in l2.as_chunks::<8>().0 {
let e = u64::from_be_bytes(*e);
if e & COMPRESSED != 0 || e & OFFSET == 0 {
continue;
}
if refcounts.of(e & OFFSET)? == 1 {
held += cluster;
}
}
}
Ok(held)
}
}
/// The refcount blocks read so far, by their index in the refcount table.
struct Refcounts<'a> {
image: &'a Image,
blocks: HashMap<usize, Vec<u8>>,
}
impl Refcounts<'_> {
/// The refcount of the cluster at `offset` in the file; 0 where no block counts it.
fn of(&mut self, offset: u64) -> Result<u64> {
let img = self.image;
let cluster = 1u64 << img.cluster_bits;
let bits = 1u64 << img.refcount_order;
let per_block = cluster * 8 / bits;
let index = offset >> img.cluster_bits;
let block = (index / per_block) as usize;
let Some(&at) = img.refcount_table.get(block) else {
return Ok(0);
};
if at & OFFSET == 0 {
return Ok(0);
}
let b = match self.blocks.entry(block) {
Slot::Occupied(e) => e.into_mut(),
Slot::Vacant(e) => {
let mut b = vec![0u8; cluster as usize];
img.file.read_exact_at(&mut b, at & OFFSET)?;
e.insert(b)
}
};
let bytes = (bits / 8) as usize;
let at = (index % per_block) as usize * bytes;
Ok(b[at..at + bytes]
.iter()
.fold(0u64, |v, &x| v << 8 | u64::from(x)))
}
}
File diff suppressed because it is too large. Load diff
+79 -2
View File
@@ -104,10 +104,30 @@ pub fn toml_path(p: &Path) -> String {
/// A stand-in program at `path` that runs `script`, a POSIX shell script, and the path to run it
/// by: `path` itself, made executable. On Windows, which runs no script by its `#!` line, `path`
/// holds the script and `path.cmd` runs it in MSYS2's or Git's `sh`, the path returned.
///
/// On Unix a child, `sh`, writes it, not this process: a file this process held open for writing
/// would be held too by each child another test forks meanwhile, until that child execs, and
/// Linux refuses to exec a file open for writing anywhere (ETXTBSY). The child's descriptor ends
/// with it, before this returns.
#[cfg(unix)]
pub fn program(path: &Path, script: &str) -> PathBuf {
std::fs::write(path, script).unwrap();
crate::os::set_mode(path, 0o755).unwrap();
use std::io::Write;
let mut sh = std::process::Command::new("/bin/sh")
.args(["-c", "cat > \"$1\" && chmod 755 \"$1\"", "sh"])
.arg(path)
.stdin(std::process::Stdio::piped())
.spawn()
.unwrap();
sh.stdin
.take()
.unwrap()
.write_all(script.as_bytes())
.unwrap();
assert!(
sh.wait().unwrap().success(),
"{} not written",
path.display()
);
path.to_path_buf()
}
@@ -141,3 +161,60 @@ pub fn program(path: &Path, script: &str) -> PathBuf {
.unwrap();
cmd
}
#[cfg(test)]
mod tests {
/// A stand-in program runs as soon as it is written while other tests fork: each forked
/// child holds this process's descriptors until it execs, and Linux refuses to exec a file
/// open for writing anywhere (ETXTBSY). Here eight threads keep forking children that wait 1
/// ms before they exec, as a busy test run's do, and each of 100 programs, 256 KiB long so
/// that a write takes a while, must run at once.
#[cfg(unix)]
#[test]
fn a_program_runs_at_once_while_other_tests_fork() {
use std::os::unix::process::CommandExt;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
let d = std::env::temp_dir().join(format!("reims-ctl-forks-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
let done = Arc::new(AtomicBool::new(false));
let forkers: Vec<_> = (0..8)
.map(|_| {
let done = done.clone();
std::thread::spawn(move || {
while !done.load(Ordering::Relaxed) {
let mut c = std::process::Command::new("/bin/sh");
c.args(["-c", ":"]);
// SAFETY: usleep is async-signal-safe, all a forked child may call.
unsafe {
c.pre_exec(|| {
libc::usleep(1000);
Ok(())
});
}
let _ = c.status();
}
})
})
.collect();
let script = format!("#!/bin/sh\nexit 0\n{}", "# padding\n".repeat(26 << 10));
let mut failed = None;
for i in 0..100 {
let p = super::program(&d.join(format!("p{i}")), &script);
match std::process::Command::new(&p).status() {
Ok(s) if s.success() => {}
other => {
failed = Some(format!("program {i}: {other:?}"));
break;
}
}
}
done.store(true, Ordering::Relaxed);
for f in forkers {
f.join().unwrap();
}
let _ = std::fs::remove_dir_all(&d);
assert_eq!(failed, None);
}
}
+1054 -165
View File
File diff suppressed because it is too large. Load diff
+193 -4
View File
@@ -17,6 +17,8 @@ use crate::paths;
use anyhow::{Context, Result, bail};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::OnceLock;
use std::time::SystemTime;
/// The branches an update can follow.
#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum)]
@@ -81,7 +83,7 @@ pub enum Outcome {
/// the install is already the latest commit of that branch ([`current`]), it says so and builds
/// nothing; scripts/install-ctl.sh run by hand builds it again.
pub fn update(channel: Option<Channel>) -> Result<Outcome> {
let i = Install::load().with_context(|| {
let i = Install::load()?.with_context(|| {
format!(
"no install record: run {} in your reims-vgpu checkout once, and reims-ctl update \
can use it from then on",
@@ -295,6 +297,82 @@ pub fn remove_set_aside(bin: &Path) {
}
}
/// A program's file as reims-ctl tells one build's from another's at the same path: its length,
/// its time of last write and its identity ([`crate::os::file_id`]), the last of which an install
/// that writes the new build anew there changes, whatever times it keeps.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BinaryFile {
len: u64,
modified: Option<SystemTime>,
id: Option<(u64, u64)>,
}
impl BinaryFile {
pub fn of(path: &Path) -> Option<BinaryFile> {
let m = std::fs::metadata(path).ok()?;
Some(BinaryFile {
len: m.len(),
modified: m.modified().ok(),
id: crate::os::file_id(path, &m),
})
}
}
/// This process's binary as it started ([`note_binary`]): its path, and its file then.
static STARTED_FROM: OnceLock<Option<(PathBuf, BinaryFile)>> = OnceLock::new();
/// Notes this process's binary, its path and its file, as reims-ctl starts, before an update from
/// another terminal can install a new one there ([`binary_replaced`]).
pub fn note_binary() {
STARTED_FROM.get_or_init(|| {
let exe = restart_path(std::env::current_exe().ok()?);
let file = BinaryFile::of(&exe)?;
Some((exe, file))
});
}
/// Where this process's binary has been replaced since it started ([`note_binary`]): the path
/// that holds another build now, as an update run from another terminal leaves it while this
/// interface stays open. None where it was not noted, or its path holds it still, or nothing.
pub fn binary_replaced() -> Option<PathBuf> {
let (exe, then) = STARTED_FROM.get()?.as_ref()?;
replaced(exe, then).then(|| exe.clone())
}
/// Whether the file at `path` is no longer `then`, the file noted there: another file is there
/// now. A path that holds nothing now holds no other build, and is not taken for one.
fn replaced(path: &Path, then: &BinaryFile) -> bool {
BinaryFile::of(path).is_some_and(|now| now != *then)
}
/// Refuses, with [`replaced_note`], where this process's binary was replaced since it started
/// ([`binary_replaced`]). What it carries of its own build, the guest's kexts, the device's
/// option ROM and an arm64 VM's bundle, is not the build of the QEMU and library the install
/// holds now, so it refuses what would pair them: a VM's start, an OpenCore image made with the
/// kexts, a VM's create and the QEMU command it prints.
pub fn refuse_replaced() -> Result<()> {
refuse(binary_replaced())
}
/// [`refuse_replaced`]'s answer where `replaced` is what [`binary_replaced`] found.
fn refuse(replaced: Option<PathBuf>) -> Result<()> {
match replaced {
Some(exe) => bail!("{}", replaced_note(&exe)),
None => Ok(()),
}
}
/// What [`refuse_replaced`] says where this process's binary, at `exe`, was replaced since it
/// started.
pub fn replaced_note(exe: &Path) -> String {
format!(
"reims-ctl was updated since this one started ({} holds another build now): quit it and \
run reims-ctl again. This one carries the macOS drivers and option ROM of its own \
build, which don't match the installed QEMU and can keep the guest from using its GPU",
paths::tilde(exe)
)
}
/// The binary to run after an update, from the path this process was started from
/// (`std::env::current_exe`), read before the update, which on Windows renames this running
/// binary aside ([`remove_set_aside`]). The update installs the new reims-ctl over that path
@@ -334,6 +412,92 @@ mod tests {
let _ = std::fs::remove_dir_all(&d);
}
/// A binary another is installed over at its path since it was noted, as an update installs
/// the new reims-ctl over the one an open interface runs, is told from the one noted: by its
/// file, whether the new one is written beside it and renamed over it, as cargo install
/// does, or written in its place, and even where it keeps its length and time of last
/// write. The one noted, left as it was, is not; nor is a path that holds nothing now.
#[test]
fn a_binary_installed_over_the_one_noted_is_seen() {
let d = std::env::temp_dir().join(format!("reims-ctl-replaced-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
let bin = d.join("reims-ctl");
std::fs::write(&bin, "build a").unwrap();
let noted = BinaryFile::of(&bin).unwrap();
let kept = replaced(&bin, &noted);
// Written beside it and renamed over it, of the same length and time of last write.
let new = d.join("reims-ctl.new");
std::fs::write(&new, "build b").unwrap();
let f = std::fs::File::options().write(true).open(&new).unwrap();
f.set_modified(std::fs::metadata(&bin).unwrap().modified().unwrap())
.unwrap();
drop(f);
std::fs::rename(&new, &bin).unwrap();
let renamed_over = replaced(&bin, &noted);
let noted = BinaryFile::of(&bin).unwrap();
// Written in its place.
std::fs::write(&bin, "build c, longer").unwrap();
let written_over = replaced(&bin, &noted);
std::fs::remove_file(&bin).unwrap();
let gone = replaced(&bin, &noted);
let _ = std::fs::remove_dir_all(&d);
assert_eq!(
(kept, renamed_over, written_over, gone),
(false, true, true, false),
"(kept, renamed over, written over, gone)"
);
let note = replaced_note(Path::new("/opt/bin/reims-ctl"));
// The note shows the path in the host's own separators (`paths::tilde`).
let shown = if cfg!(windows) {
r"\opt\bin\reims-ctl"
} else {
"/opt/bin/reims-ctl"
};
assert!(
note.starts_with(&format!(
"reims-ctl was updated since this one started ({shown} holds another build now): \
quit it and run reims-ctl again."
)),
"{note}"
);
}
/// On Windows the installer sets the running reims-ctl aside before it installs the new one:
/// it renames it beside itself (`NAME.old-N`), which the process keeps running, and copies
/// it back to its path. The copy has the same bytes, length and time of last write, but it is
/// another file, so the binary noted there counts as replaced from then on, before the
/// install writes the new build over the copy. The file set aside is still the one noted.
/// Until the binary is replaced nothing is refused; after that, what would pair this build's
/// kexts and ROM with the install's QEMU is refused with the note.
#[test]
fn a_binary_set_aside_and_copied_back_is_replaced() {
let d = std::env::temp_dir().join(format!("reims-ctl-aside-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
let bin = d.join("reims-ctl.exe");
std::fs::write(&bin, "build a").unwrap();
let noted = BinaryFile::of(&bin).unwrap();
let before = refuse(replaced(&bin, &noted).then(|| bin.clone())).is_ok();
let aside = d.join("reims-ctl.exe.old-0");
std::fs::rename(&bin, &aside).unwrap();
std::fs::copy(&aside, &bin).unwrap();
let f = std::fs::File::options().write(true).open(&bin).unwrap();
f.set_modified(std::fs::metadata(&aside).unwrap().modified().unwrap())
.unwrap();
drop(f);
let copied_back = replaced(&bin, &noted);
let aside_kept = !replaced(&aside, &noted);
let refused = refuse(copied_back.then(|| bin.clone())).map_err(|e| format!("{e:#}"));
let _ = std::fs::remove_dir_all(&d);
assert_eq!(
(before, copied_back, aside_kept),
(true, true, true),
"(nothing refused before, the copy is another file, the one set aside is the same)"
);
assert_eq!(refused, Err(replaced_note(&bin)));
}
/// A start removes what the installer set aside, reims-ctl's and reims-util's `NAME.old-N`,
/// and leaves the programs themselves and every other file, a near name's among them.
#[test]
@@ -381,8 +545,33 @@ mod tests {
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
let bin = d.join("sleeper");
std::fs::copy("/bin/sleep", &bin).unwrap();
let mut child = Command::new(&bin).arg("30").spawn().unwrap();
// The running binary is this test binary, copied, idling in install's idle test, as the
// prune test's QEMU does: a copy of /bin/sleep ran no sleep where /bin/sleep is uutils'
// one binary of every utility (Ubuntu 26.04's coreutils), which picks the utility by its
// file's name, whatever argv[0] says ("coreutils: unknown program 'sleeper'", GitHub's
// ubuntu-26.04 runner, 2026-12-04).
let this = std::env::current_exe().unwrap();
std::fs::copy(&this, &bin).unwrap();
// The copy's write handle is closed, but another test's child forked while it was open
// holds it until that child execs, and an exec of a file open for writing fails with
// ETXTBSY: spawn again until that child has let go of it.
let busy = std::time::Instant::now();
let mut child = loop {
let spawned = Command::new(&bin)
.args(["--exact", "install::tests::idle_as_a_qemu"])
.env("REIMS_CTL_TEST_IDLE", "1")
.stdout(std::process::Stdio::null())
.spawn();
match spawned {
Err(e)
if e.raw_os_error() == Some(libc::ETXTBSY)
&& busy.elapsed() < std::time::Duration::from_secs(10) =>
{
std::thread::sleep(std::time::Duration::from_millis(1));
}
spawned => break spawned.unwrap(),
}
};
// spawn returns once the child's exec lets go of this process's memory, which the kernel
// does a moment before it names the new binary as the child's exe: wait for that name.
let exe = format!("/proc/{}/exe", child.id());
@@ -396,7 +585,7 @@ mod tests {
}
// cargo install --force: the new binary written beside, then renamed over the old.
let new = d.join("sleeper.new");
std::fs::copy("/bin/sleep", &new).unwrap();
std::fs::copy(&this, &new).unwrap();
std::fs::rename(&new, &bin).unwrap();
let named = std::fs::read_link(format!("/proc/{}/exe", child.id())).unwrap();
let _ = child.kill();
+180 -1
View File
@@ -23,6 +23,7 @@
//! udev rule says otherwise: scripts/install-ctl.sh adds one ([`UDEV_RULE`]), which gives USB
//! devices other than hubs to the kvm group and to the user at the host's screen.
use crate::disks::HostDisk;
use crate::host::{Host, Os, Profile};
use crate::vm::{UsbDevice, Vm, parse_usb_port};
use crate::{qmp, runtime};
@@ -40,6 +41,9 @@ pub const UDEV_RULE: &str = r#"SUBSYSTEM=="usb", ENV{DEVTYPE}=="usb_device", ATT
/// Where Linux lists the host's USB devices, and lsusb's names for them.
const SYSFS: &str = "/sys/bus/usb/devices";
/// Linux's sysfs, where `block/<disk>` leads to the disk's device, below its bus's and, on USB,
/// its USB device's ([`disks_on`]).
const SYS: &str = "/sys";
const USB_IDS: &str = "/usr/share/hwdata/usb.ids";
/// A USB device plugged into the host, other than a hub.
@@ -461,9 +465,10 @@ pub fn apply(
if now.config.usb == old {
return Ok((now, vec![format!("{name}: nothing changed")]));
}
let new: Vec<&UsbDevice> = now.config.usb.iter().filter(|u| !old.contains(u)).collect();
refuse_in_use_here(&new)?;
now.save()?;
let gone: Vec<&UsbDevice> = old.iter().filter(|u| !now.config.usb.contains(u)).collect();
let new: Vec<&UsbDevice> = now.config.usb.iter().filter(|u| !old.contains(u)).collect();
let label = |u: &UsbDevice| match u.name.as_str() {
"" => u.id.clone(),
n => n.to_string(),
@@ -523,6 +528,70 @@ pub fn apply(
Ok((now, said))
}
/// The host's disks on `d`, a USB stick's or a USB disk's: each of `disks` whose device, where
/// `sys` (Linux's sysfs) leads `block/<disk>`, lies below `d`'s port.
fn disks_on<'a>(d: &HostDevice, sys: &Path, disks: &'a [HostDisk]) -> Vec<&'a HostDisk> {
let below = |k: &&HostDisk| {
std::fs::canonicalize(sys.join("block").join(&k.kernel))
.is_ok_and(|p| p.components().any(|c| c.as_os_str() == d.port.as_str()))
};
disks.iter().filter(below).collect()
}
/// Why `d` can't be the guest's while the host uses a disk on it (mounted, swap, part of another
/// device), a sentence in [`crate::disks::refusal`]'s form; None where it uses none. QEMU takes
/// the device from the host's drivers (`libusb_detach_kernel_driver`), and a file system the
/// host has mounted on it would lose its disk mid-use, with what the host had not written yet.
fn in_use(d: &HostDevice, sys: &Path, disks: &[HostDisk]) -> Option<String> {
let k = disks_on(d, sys, disks)
.into_iter()
.find(|k| !k.uses.is_empty())?;
Some(format!(
"USB device {} ({}) holds {} ({}), which is this host's: {}. Unmount or eject it on the \
host first: a guest given a disk the host uses would destroy it",
d.name,
d.id(),
k.label(),
k.path.display(),
k.uses.join(", ")
))
}
/// Refuses to give a guest any of `chosen` that is plugged in, among `devices`, while the host
/// uses a disk on it ([`in_use`]), `disks` the host's disks as `sys` leads to them.
fn refuse_in_use(
chosen: &[&UsbDevice],
devices: &[HostDevice],
sys: &Path,
disks: &[HostDisk],
) -> Result<()> {
let found = chosen
.iter()
.flat_map(|u| devices.iter().filter(|d| d.is(u)))
.find_map(|d| in_use(d, sys, disks));
match found {
Some(why) => bail!("{why}"),
None => Ok(()),
}
}
/// [`refuse_in_use`] on this host's USB devices and disks; none where `chosen` is empty.
fn refuse_in_use_here(chosen: &[&UsbDevice]) -> Result<()> {
if chosen.is_empty() {
return Ok(());
}
let disks = crate::disks::host_disks();
refuse_in_use(chosen, &host_devices(), Path::new(SYS), &disks)
}
/// Refuses a start that would give the guest a USB device the host uses a disk on
/// ([`in_use`]): one chosen and plugged in. One plugged in while the VM runs is QEMU's to take
/// (`usb_host_auto_check`), unseen here.
pub fn check_start(vm: &Vm) -> Result<()> {
let chosen: Vec<&UsbDevice> = vm.config.usb.iter().collect();
refuse_in_use_here(&chosen)
}
/// Why `d` can't be opened, and what lets QEMU open it.
pub fn unusable(d: &HostDevice) -> String {
format!("you can't open {}: {}", d.file().display(), fix())
@@ -669,6 +738,116 @@ mod tests {
}
}
/// A USB device holding a disk the host uses (a stick with a partition it has mounted) is
/// refused, saying what the host uses it for and to unmount or eject it first; one whose
/// disk nothing uses goes through, as does one chosen but not plugged in. Each disk's
/// `block` entry leads to its device below its USB device's port, as Linux's sysfs does; a
/// disk on another bus is on no USB device, and one behind a hub is on its own device, not
/// on another device on that hub.
#[cfg(unix)]
#[test]
fn a_usb_device_holding_a_disk_the_host_uses_is_refused() {
let f = Sysfs::new("in-use");
let (sys, by_id) = (f.0.join("sys"), f.0.join("by-id"));
std::fs::create_dir_all(sys.join("block")).unwrap();
std::fs::create_dir_all(&by_id).unwrap();
// A disk below `device` in sys/devices, with one partition, `block/<name>` leading to it.
let disk = |name: &str, device: &str, dev: &str, part: &str| {
let d = sys.join("devices").join(device).join("block").join(name);
let write = |rel: &str, v: &str| {
let p = d.join(rel);
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
std::fs::write(p, format!("{v}\n")).unwrap();
};
write("dev", dev);
write("size", "62530624");
write("ro", "0");
write("device/model", "Ultra Fit");
write(&format!("{name}1/partition"), "1");
write(&format!("{name}1/dev"), part);
std::os::unix::fs::symlink(&d, sys.join("block").join(name)).unwrap();
};
let usb = "pci0000:00/0000:00:14.0/usb2";
disk(
"sdb",
&format!("{usb}/2-1/2-1:1.0/host6/6:0:0:0"),
"8:16",
"8:17",
);
disk(
"sdc",
&format!("{usb}/2-2/2-2:1.0/host7/7:0:0:0"),
"8:32",
"8:33",
);
// Behind a hub at port 2-3: its path passes the hub's port too.
disk(
"sdd",
&format!("{usb}/2-3/2-3.4/2-3.4:1.0/host8/8:0:0:0"),
"8:48",
"8:49",
);
disk(
"nvme0n1",
"pci0000:00/0000:00:1d.0/nvme/nvme0",
"259:0",
"259:1",
);
let used = crate::disks::HostUse {
mounts: vec![
(Some((8, 17)), "/media/u/STICK".into()),
(Some((259, 1)), "/".into()),
],
swaps: vec![],
};
let disks = crate::disks::read_disks(&sys, &by_id, &used);
assert_eq!(disks.len(), 4, "{disks:?}");
let device = |port: &str, product: u16| HostDevice {
vendor: 0x0781,
product,
port: port.into(),
bus: 2,
address: 3,
name: "SanDisk Ultra Fit".into(),
kinds: vec!["storage"],
};
let devices = [
device("2-1", 0x5583),
device("2-2", 0x5584),
device("2-3.1", 0x5585),
device("2-3.4", 0x5586),
];
let mounted = choice_of(&devices[0], &devices);
let free = choice_of(&devices[1], &devices);
let sdb = disks.iter().find(|k| k.kernel == "sdb").unwrap();
let e = refuse_in_use(&[&mounted], &devices, &sys, &disks).unwrap_err();
assert_eq!(
e.to_string(),
format!(
"USB device SanDisk Ultra Fit (0781:5583) holds {} (/dev/sdb), which is this \
host's: sdb1 mounted at /media/u/STICK. Unmount or eject it on the host first: a \
guest given a disk the host uses would destroy it",
sdb.label()
)
);
refuse_in_use(&[&free], &devices, &sys, &disks).unwrap();
let absent = UsbDevice {
id: "1234:5678".into(),
port: None,
name: String::new(),
};
refuse_in_use(&[&absent], &devices, &sys, &disks).unwrap();
// The host's NVMe disk, mounted at /, is on none. The disk behind the hub is on the
// device at 2-3.4 alone, not on the one beside it at 2-3.1.
let want: [&[&str]; 4] = [&["sdb"], &["sdc"], &[], &["sdd"]];
for (d, want) in devices.iter().zip(want) {
let on: Vec<&str> = (disks_on(d, &sys, &disks).iter())
.map(|k| k.kernel.as_str())
.collect();
assert_eq!(on, want, "{}", d.port);
}
}
const USB_IDS_TEXT: &str = "# usb.ids\n\
0bda Realtek Semiconductor Corp.\n\
\t5458 BillBoard Device\n\
+96 -25
View File
@@ -13,8 +13,10 @@
//! - Input is `input-send-event`: the USB tablet's absolute position and buttons, and the USB
//! keyboard's keys (keys.rs).
//!
//! QMP's socket serves one client at a time, so the viewer lets its connection go after each
//! frame, and `reims-ctl stop` gets in while it runs.
//! QMP's socket serves one client at a time, so the viewer connects for each exchange, a frame's
//! or a batch of input's, and lets the connection go as QEMU answers: `reims-ctl stop`, a
//! report's ask for the counts and the interface's probes get in while it runs, also while it
//! sends input as a frame is still being drawn.
//!
//! QEMU's USB keyboard queues 16 scancodes, drops a key whose scancodes do not fit, and gives the
//! guest one each time it polls the keyboard (hw/input/hid.c). Keys go out at most 12 scancodes
@@ -880,32 +882,29 @@ fn take_batch(pending: &mut VecDeque<Vec<Ev>>, queued: &mut f64) -> Vec<Ev> {
batch
}
fn connect<'a>(conn: &'a mut Option<Qmp>, socket: &Path) -> Result<&'a mut Qmp> {
if conn.is_none() {
*conn = Some(Qmp::connect(socket, Duration::from_secs(5))?);
}
Ok(conn.as_mut().unwrap())
/// Runs `command` on the VM's QMP socket in an exchange of its own: connected for it alone, and
/// closed once QEMU answers. QEMU serves the socket one client at a time (qmp.rs), so a
/// connection the viewer kept between its exchanges would keep every other client out while it
/// views: a report's ask for the counts, a stop's keys and power button, a resume, a USB
/// device's attach, the interface's probe for a pause.
fn exchange(t: &Target, command: &str, arguments: Value) -> Result<Value> {
Qmp::connect(&t.socket, Duration::from_secs(5))?.execute(command, Some(arguments))
}
fn send_input(conn: &mut Option<Qmp>, t: &Target, evs: Vec<Ev>) -> Result<()> {
fn send_input(t: &Target, evs: Vec<Ev>) -> Result<()> {
let mut events = Vec::new();
for e in evs {
e.json(&mut events);
}
let r = connect(conn, &t.socket).and_then(|q| {
q.execute(
"input-send-event",
Some(t.with_device(json!({ "events": events }))),
)
});
if r.is_err() {
*conn = None;
}
r.map(|_| ())
exchange(
t,
"input-send-event",
t.with_device(json!({ "events": events })),
)
.map(drop)
}
fn qmp_thread(c: Capture) {
let mut conn: Option<Qmp> = None;
let mut pending: VecDeque<Vec<Ev>> = VecDeque::new();
// Scancodes the guest has yet to take from its queue, by estimate.
let mut queued = 0.0f64;
@@ -954,7 +953,7 @@ fn qmp_thread(c: Capture) {
}
pending.retain(|g| !g.iter().any(|e| matches!(e, Ev::Key(_, true))));
if !pending.is_empty() {
let _ = send_input(&mut conn, &c.target, pending.drain(..).flatten().collect());
let _ = send_input(&c.target, pending.drain(..).flatten().collect());
}
break;
}
@@ -967,7 +966,7 @@ fn qmp_thread(c: Capture) {
input_at = Some(t);
// Show what the input did soon.
next = next.min(t + Duration::from_millis(30));
if let Err(e) = send_input(&mut conn, &c.target, batch) {
if let Err(e) = send_input(&c.target, batch) {
if gone() {
break;
}
@@ -979,11 +978,8 @@ fn qmp_thread(c: Capture) {
continue;
}
let t0 = Instant::now();
let dumped = connect(&mut conn, &c.target.socket)
.and_then(|q| q.execute("screendump", Some(c.target.screendump(&c.file))))
let dumped = exchange(&c.target, "screendump", c.target.screendump(&c.file))
.and_then(|_| Ok(std::fs::read(&c.file)?));
// Between frames QMP's socket is free for other clients.
conn = None;
let data = match dumped {
Ok(d) => d,
Err(e) => {
@@ -1090,6 +1086,81 @@ mod tests {
assert_eq!(left, (false, true, true), "(killed, running, others)");
}
/// The viewer holds the VM's QMP socket, which QEMU serves one client at a time (qmp.rs),
/// only for each of its exchanges: a report's ask for the counts, a stop's keys and power
/// button, and the interface's probes get in between them, while the viewer sends input
/// as its last frame is still being drawn too.
#[test]
fn the_viewer_leaves_qmp_to_others_between_its_exchanges() {
use std::io::BufRead;
let dir = crate::testenv::SocketDir::new("view-qmp");
let sock = dir.0.join("qmp.sock");
let listener = crate::os::UnixListener::bind(&sock).unwrap();
std::thread::spawn(move || {
for mut conn in listener.incoming().map_while(Result::ok) {
let _ = conn.write_all(b"{\"QMP\": {}}\n");
let reader = std::io::BufReader::new(conn.try_clone().unwrap());
for _ in reader.lines().map_while(Result::ok) {
let _ = conn.write_all(b"{\"return\": {}}\n");
}
}
});
let sh = Arc::new(Shared {
stop: AtomicBool::new(false),
// The frame captured last is still being drawn.
busy: AtomicBool::new(true),
screen: Mutex::new(Screen {
cols: 80,
rows: 24,
cell: ASSUMED_CELL,
pixel_mouse: false,
place: None,
latch: Mods::NONE,
layout: 0,
}),
});
let (input, rx) = channel();
let (enc, _enc_rx) = channel();
let (ui, _ui_rx) = channel();
let (done, done_rx) = channel();
let c = Capture {
sh: sh.clone(),
target: Target {
socket: sock.clone(),
device: "gfx",
},
file: dir.0.join("frame.ppm"),
vm: Vm {
dir: dir.0.clone(),
config: crate::vm::tests::x86_64_config(),
},
rx,
enc,
ui,
gap: Duration::from_secs_f64(1.0 / 15.0),
done,
};
std::thread::spawn(move || qmp_thread(c));
// The mouse moving over the frame, as it does while one waits for a slow app.
let moving = std::thread::spawn(move || {
for i in 0..100u16 {
if input.send(vec![Ev::Abs(i, i)]).is_err() {
break;
}
std::thread::sleep(Duration::from_millis(20));
}
});
std::thread::sleep(Duration::from_millis(200));
let other = Qmp::connect(&sock, Duration::from_secs(1))
.and_then(|mut q| q.execute("qom-set", None))
.map(drop)
.map_err(|e| format!("{e:#}"));
sh.stop.store(true, Ordering::SeqCst);
let _ = moving.join();
let _ = done_rx.recv_timeout(Duration::from_secs(5));
assert_eq!(other, Ok(()));
}
#[test]
fn the_toolbar_shows_disconnect_first_and_finds_its_buttons() {
let (line, buttons) = toolbar("mac", Mods::CMD);
+539 -90
View File
@@ -4,6 +4,9 @@
//! firmware copies, `qemu.pid` while QEMU runs, the QMP socket where the path is short enough,
//! and `logs/`. The registry (`vms.toml` in the config directory) lists each VM by its name and
//! directory, so a VM may live anywhere.
//!
//! A save writes `vm.toml` over the file as it is ([`Vm::save`]), so settings a newer reims-ctl
//! added stay, in their place and form, when an older one saves the VM.
use crate::host::Profile;
use crate::paths;
@@ -14,6 +17,17 @@ use std::path::{Path, PathBuf};
pub const CONFIG_FILE: &str = "vm.toml";
/// The settings an older reims-ctl wrote that this one reads past, and leaves out of a VM's next
/// save ([`Vm::save`]): apple-gfx's video acceleration, HiDPI and refresh rate, and an x86-64
/// VM's installer kind and SMC key, which settings held before 2026-10-12.
pub(crate) const RETIRED: [&str; 5] = [
"video_acceleration",
"display.hidpi",
"display.refresh",
"q35.installer_kind",
"q35.osk",
];
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VmConfig {
pub name: String,
@@ -230,15 +244,83 @@ impl DiskController {
}
}
/// Host cache policy for an x86-64 VM's system disk.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum DiskCache {
/// QEMU's default (`writeback` with flushes forwarded to the host, except
/// during installation when `cache.no-flush=on` is added automatically).
#[default]
Default,
/// Host page cache enabled (`cache.direct=off`), guest flushes forwarded.
Writeback,
/// Bypass host page cache (`cache.direct=on`), guest flushes forwarded.
None,
/// Host page cache enabled and guest flushes ignored (`cache.direct=off,cache.no-flush=on`).
Unsafe,
}
impl DiskCache {
pub const ALL: [DiskCache; 4] = [
DiskCache::Default,
DiskCache::Writeback,
DiskCache::None,
DiskCache::Unsafe,
];
pub fn id(self) -> &'static str {
match self {
DiskCache::Default => "default",
DiskCache::Writeback => "writeback",
DiskCache::None => "none",
DiskCache::Unsafe => "unsafe",
}
}
pub fn parse(s: &str) -> Result<DiskCache> {
let low = s.trim().to_ascii_lowercase();
DiskCache::ALL
.into_iter()
.find(|c| c.id() == low)
.with_context(|| format!("disk cache is default, writeback, none or unsafe, not {s:?}"))
}
pub fn is_default(&self) -> bool {
*self == DiskCache::Default
}
}
/// Reports whether `path` is a Windows raw physical disk or volume/partition
/// device path (`\\.\PhysicalDriveN`, `\\.\HarddiskVolumeN`,
/// `\\.\HarddiskNPartitionM`, `\\.\Volume{...}`, or `\\?\Volume{...}`),
/// excluding extended-length regular file paths like `\\?\D:\...`.
pub fn is_windows_raw_device(path: &Path) -> bool {
let norm = path.to_string_lossy().replace('/', "\\");
let rest = if let Some(r) = norm.strip_prefix(r"\\.\") {
r
} else if let Some(r) = norm.strip_prefix(r"\\?\") {
let low = r.to_ascii_lowercase();
return low.starts_with("volume{");
} else {
return false;
};
let low = rest.to_ascii_lowercase();
low.starts_with("physicaldrive")
|| low.starts_with("harddiskvolume")
|| low.starts_with("harddisk")
|| low.starts_with("volume{")
}
/// reims-vgpu's displays, one by default and up to [`DISPLAYS_MAX`], each in a window of its own:
/// every window opens at the resolution's size ([`Display::window_size`]) and keeps the size the
/// person gives it, which its display follows, at the refresh rate of the host screen it is on.
/// The guest starts a HiDPI desktop by itself on a display whose window is at least 3840 pixels
/// wide, and offers one in its Displays settings from 2880 (the kext's HiDPI modes, whose pixels
/// halve exactly: the guest is offered the window's pixels, the width rounded down to a multiple
/// of 16 and the height to even). The count an older reims-ctl saved for apple-gfx's displays
/// comes back as reims-vgpu's ([`saved_display_count`]); its HiDPI and refresh rate are read
/// past, and left out of the next save.
/// each window opens at its display's size of the resolution ([`Display::window_sizes`]) and keeps
/// the size the person gives it, which its display follows, at the refresh rate of the host
/// screen it is on. The guest starts a HiDPI desktop by itself on a display whose window is at
/// least 3840 pixels wide, and offers one in its Displays settings from 2880 (the kext's HiDPI
/// modes, whose pixels halve exactly: the guest is offered the window's pixels, the width rounded
/// down to a multiple of 16 and the height to even). The count an older reims-ctl saved for
/// apple-gfx's displays comes back as reims-vgpu's ([`saved_display_count`]); its HiDPI and
/// refresh rate are read past, and left out of the next save, as is the `capture` an older
/// reims-ctl saved, a setting the windows no longer have.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct Display {
@@ -249,21 +331,13 @@ pub struct Display {
deserialize_with = "saved_display_count"
)]
pub count: u32,
/// The size every window opens at, `<width>x<height>`.
/// The size each window opens at, `<width>x<height>`: one size for every display, or one for
/// each display, comma-separated, in the displays' order.
pub resolution: String,
/// Borderless windows that fill their screens: every display's.
pub borderless: bool,
/// Whether a click into a window captures the mouse and the keyboard, until the keys its
/// title names or the window losing the keyboard let them go; off, the windows never
/// capture them (`REIMS_VGPU_WINDOW_CAPTURE=0`, [`crate::qemu`]). Saved only where it is not
/// [`DEFAULT_CAPTURE`], so a VM that never chose follows the default.
#[serde(skip_serializing_if = "Display::is_default_capture")]
pub capture: bool,
}
/// Whether a VM's windows capture the mouse and the keyboard where its settings do not say.
pub const DEFAULT_CAPTURE: bool = true;
/// The most displays reims-vgpu's device takes (the device's `RGFX_DISPLAYS_MAX`, QEMU's
/// `displays` property's top).
pub const DISPLAYS_MAX: u32 = 4;
@@ -287,7 +361,6 @@ impl Default for Display {
count: 1,
resolution: "1920x1080".into(),
borderless: false,
capture: DEFAULT_CAPTURE,
}
}
}
@@ -297,24 +370,46 @@ impl Display {
*count == 1
}
fn is_default_capture(capture: &bool) -> bool {
*capture == DEFAULT_CAPTURE
}
/// The `displays` reims-vgpu's device is given: none for one, the device's own, which a
/// QEMU built before the property takes.
pub fn qemu_displays(&self) -> Option<u32> {
(self.count != 1).then_some(self.count)
}
/// The size each of reims-vgpu's windows opens at, the resolution's, in the host's points (a
/// The size each of reims-vgpu's windows opens at, display i's at i, from the resolution: one
/// size for every display, or a comma-separated list of one for each. In the host's points (a
/// guest point per host point), shrunk to fit the screen, which its guest takes in pixels and
/// follows: measured on a Linux desktop at 2.1x, 1280x720 opened 1280x720 points and the
/// guest ran 2688x1512. None for the device's own, 1920x1080.
pub fn window_size(&self) -> Option<(u32, u32)> {
parse_resolution(self.resolution.trim())
.ok()
.filter(|&size| size != (1920, 1080))
/// guest ran 2688x1512. On a headless start, each display's mode. An error for a size that is
/// not one, or a list of another count of sizes than the displays.
pub fn window_sizes(&self) -> Result<Vec<(u32, u32)>> {
let sizes = (self.resolution.split(','))
.map(|s| parse_resolution(s.trim()))
.collect::<Result<Vec<_>>>()?;
let count = self.count.max(1) as usize;
match sizes.len() {
1 => Ok(vec![sizes[0]; count]),
n if n == count => Ok(sizes),
n => bail!(
"the resolution gives {n} sizes for {count} display{}: give one size for every \
display, or one for each display, comma-separated, as 2560x1440,1920x1080",
if count == 1 { "" } else { "s" }
),
}
}
/// The device's `resolution`, from [`Display::window_sizes`]: none where every display opens
/// at the device's own 1920x1080, as a QEMU built before the property takes; one size where
/// every display has it; else each display's, comma-separated, which QEMU's line writes with
/// each comma doubled ([`crate::qemu::opt`]). None for a resolution reims-ctl does not take.
pub fn qemu_resolution(&self) -> Option<String> {
let sizes = self.window_sizes().ok()?;
let named = |&(w, h): &(u32, u32)| format!("{w}x{h}");
if sizes.iter().all(|s| *s == sizes[0]) {
(sizes[0] != (1920, 1080)).then(|| named(&sizes[0]))
} else {
Some(sizes.iter().map(named).collect::<Vec<_>>().join(","))
}
}
/// [`Display::check`], and more than one display refused on VMware SVGA, which has one. A
@@ -335,7 +430,7 @@ impl Display {
if !(1..=DISPLAYS_MAX).contains(&self.count) {
bail!("a VM has 1 to {DISPLAYS_MAX} displays, not {}", self.count);
}
parse_resolution(self.resolution.trim()).map(|_| ())
self.window_sizes().map(|_| ())
}
}
@@ -361,7 +456,8 @@ pub fn parse_resolution(s: &str) -> Result<(u32, u32)> {
#[serde(default)]
pub struct Gpu {
/// The Vulkan driver's manifest (ICD JSON) that reaches the GPU. Where [`Gpu::select`] is
/// none, the loader is limited to it: `VK_DRIVER_FILES`.
/// none, the loader is limited to it: `VK_DRIVER_FILES`, and each start finds it again first
/// ([`crate::gpu`], "A VM's driver at its start"), as a driver update can move it.
#[serde(skip_serializing_if = "Option::is_none")]
pub driver_file: Option<PathBuf>,
/// The GPU's PCI device ID, where its driver drives several GPUs: the loader keeps that GPU
@@ -374,6 +470,12 @@ pub struct Gpu {
/// ([`crate::gpu`]).
#[serde(skip_serializing_if = "Option::is_none")]
pub select: Option<String>,
/// The GPU's PCI address, `0000:02:00.0`, where another GPU of its vendor and device IDs is
/// on the host, which those IDs cannot tell from it: the GPU is then named by its address,
/// `DRI_PRIME=pci-0000_02_00_0`, which Mesa's device-select layer and the library read
/// ([`crate::gpu`], "Two GPUs of the same IDs").
#[serde(skip_serializing_if = "Option::is_none")]
pub pci: Option<String>,
/// The GPU's name, for display.
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
@@ -395,6 +497,31 @@ impl Gpu {
.map(Some)
.with_context(|| format!("the GPU's select is vendor:device in hex, not {s:?}"))
}
/// `DRI_PRIME`'s value that names the GPU at [`Gpu::pci`], `pci-0000_02_00_0`, where it has
/// an address: its domain, bus, device and function in hex, as `0000:02:00.0` gives them.
pub fn dri_prime(&self) -> Result<Option<String>> {
let Some(a) = self.pci.as_deref() else {
return Ok(None);
};
let hex = |x: &str, len: usize| {
let ok = x.len() == len && x.bytes().all(|b| b.is_ascii_hexdigit());
ok.then(|| x.to_ascii_lowercase())
};
let parts = (|| {
let (domain, rest) = a.split_once(':')?;
let (bus, rest) = rest.split_once(':')?;
let (device, function) = rest.split_once('.')?;
let p = [(domain, 4), (bus, 2), (device, 2), (function, 1)];
p.into_iter()
.map(|(x, len)| hex(x, len))
.collect::<Option<Vec<_>>>()
})();
let Some(parts) = parts else {
bail!("the GPU's pci is its PCI address, 0000:02:00.0, not {a:?}");
};
Ok(Some(format!("pci-{}", parts.join("_"))))
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
@@ -498,6 +625,9 @@ pub struct Q35 {
/// installer may boot instead.
#[serde(default, skip_serializing_if = "DiskController::is_ahci")]
pub disk_controller: DiskController,
/// Host I/O cache mode for the system disk.
#[serde(default, skip_serializing_if = "DiskCache::is_default")]
pub disk_cache: DiskCache,
/// The system disk's AHCI port, on [`DiskController::Ahci`]: 3, after OpenCore's 2.
#[serde(default = "default_disk_port")]
pub disk_port: u32,
@@ -682,6 +812,7 @@ impl VmConfig {
}
self.display.check()?;
self.gpu.selected()?;
self.gpu.dri_prime()?;
for k in self.extra_env.keys() {
check_env_name(k)?;
}
@@ -758,7 +889,8 @@ impl VmConfig {
/// How long `stop` waits for the guest to shut down before it powers the VM off: `None`
/// for a timeout of 0, no limit, as an SSH port of 0 is no forward. A stop then waits until
/// the guest shuts down, which may ask about unsaved documents for as long as they stay
/// open; only a forced stop powers the VM off.
/// open, or until QEMU pauses the VM for a full disk, which ends it with an error; only a
/// forced stop powers the VM off.
pub fn stop_timeout(&self) -> Option<std::time::Duration> {
stop_timeout(self.stop_timeout_secs)
}
@@ -840,40 +972,14 @@ pub fn check_mac(mac: &str) -> Result<()> {
Ok(())
}
/// A locally administered MAC in QEMU's 52:54:00 prefix.
/// A locally administered MAC in QEMU's 52:54:00 prefix, its last three bytes from the OS's
/// random source (the getrandom crate's, on Windows `ProcessPrng`).
pub fn random_mac() -> String {
let b = random_bytes::<3>();
let mut b = [0u8; 3];
getrandom::fill(&mut b).expect("the OS's random source");
format!("52:54:00:{:02x}:{:02x}:{:02x}", b[0], b[1], b[2])
}
fn random_bytes<const N: usize>() -> [u8; N] {
use std::io::Read;
let mut b = [0u8; N];
if std::fs::File::open("/dev/urandom")
.and_then(|mut f| f.read_exact(&mut b))
.is_err()
{
// Windows has no /dev/urandom. The clock alone is no random source there: it counts
// 100 ns, so its low bytes hold some 22 bits, the first of them a multiple of 4, and the
// pid, shifted past them, changes none. std's RandomState is keyed from the OS's random
// source (ProcessPrng on Windows), so a hash it keys is unpredictable; the clock and the
// pid are hashed in too.
use std::hash::{BuildHasher, Hasher};
let t = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default();
let keys = std::collections::hash_map::RandomState::new();
for (i, chunk) in b.chunks_mut(8).enumerate() {
let mut h = keys.build_hasher();
h.write_usize(i);
h.write_u128(t.as_nanos());
h.write_u32(std::process::id());
chunk.copy_from_slice(&h.finish().to_le_bytes()[..chunk.len()]);
}
}
b
}
/// A size such as `8G`, `8GiB`, `512M` or `1.5T`, in MiB; a bare number is GiB.
pub fn parse_size_mib(s: &str) -> Result<u64> {
let t = s.trim();
@@ -924,14 +1030,18 @@ impl Vm {
})
}
/// Writes the settings into `vm.toml`, over the file as it is: what another build of
/// reims-ctl wrote there and this one does not know stays in its place and form, and the
/// keys an older build wrote that this one retired ([`RETIRED`]) go
/// ([`crate::record::text_over`]). Refused, with the file left as it is, where this build
/// can't read it, or can't keep what it holds through the save ([`crate::record::Refused`]).
pub fn save(&self) -> Result<()> {
self.config.check()?;
let text = toml::to_string_pretty(&self.config)?;
let file = self.dir.join(CONFIG_FILE);
let tmp = self.dir.join(format!(".{CONFIG_FILE}.tmp"));
std::fs::write(&tmp, text).with_context(|| format!("write {}", tmp.display()))?;
std::fs::rename(&tmp, &file).with_context(|| format!("write {}", file.display()))?;
Ok(())
let old = crate::record::old_text(&file)?;
let text = crate::record::text_over(&self.config, &file, old.as_deref(), &RETIRED)?;
crate::record::replace(&file, text.as_bytes())
.with_context(|| format!("write {}", file.display()))
}
pub fn name(&self) -> &str {
@@ -951,6 +1061,10 @@ impl Vm {
}
pub fn disk(&self) -> PathBuf {
if is_windows_raw_device(&self.config.disk) {
let s = self.config.disk.to_string_lossy().replace('/', "\\");
return PathBuf::from(s.trim_end_matches('\\'));
}
self.path(&self.config.disk)
}
@@ -1055,7 +1169,7 @@ pub fn qmp_socket_in(dir: &Path, name: &str, runtime: &Path, short: &Path) -> Pa
// ---------------------------------------------------------------- the registry
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Registry {
#[serde(default, rename = "vm")]
pub vms: Vec<Entry>,
@@ -1087,13 +1201,16 @@ impl Registry {
Ok(reg)
}
/// Writes the registry over its file as it is, keeping what another build of reims-ctl wrote
/// there in its place and form ([`crate::record::text_over`]); refused, with the file left as
/// it is, where this build can't read it or keep what it holds ([`crate::record::Refused`]).
pub fn save(&self) -> Result<()> {
let file = paths::registry_file();
std::fs::create_dir_all(file.parent().unwrap())?;
let tmp = file.with_extension("toml.tmp");
std::fs::write(&tmp, toml::to_string_pretty(self)?)?;
std::fs::rename(&tmp, &file)?;
Ok(())
let old = crate::record::old_text(&file)?;
let text = crate::record::text_over(self, &file, old.as_deref(), &[])?;
crate::record::replace(&file, text.as_bytes())
.with_context(|| format!("write {}", file.display()))
}
pub fn find(&self, name: &str) -> Option<&Entry> {
@@ -1138,16 +1255,71 @@ pub(crate) mod tests {
resolution: resolution.into(),
..Default::default()
};
assert_eq!(d("2560x1440").window_size(), Some((2560, 1440)));
assert_eq!(d(" 3840x2160").window_size(), Some((3840, 2160)));
assert_eq!(d("1920x1080").window_size(), None);
assert_eq!(d("2560x1440").window_sizes().unwrap(), [(2560, 1440)]);
assert_eq!(
d("2560x1440").qemu_resolution().as_deref(),
Some("2560x1440")
);
assert_eq!(
d(" 3840x2160").qemu_resolution().as_deref(),
Some("3840x2160")
);
assert_eq!(d("1920x1080").qemu_resolution(), None);
assert!(d("2560x1600").check().is_ok());
for bad in ["host", "2560", "19x", "0x1080", "70000x10"] {
for bad in [
"host",
"2560",
"19x",
"0x1080",
"70000x10",
"",
"2560x1440,",
] {
assert!(d(bad).check().is_err(), "{bad}");
assert_eq!(d(bad).window_size(), None, "{bad}");
assert_eq!(d(bad).qemu_resolution(), None, "{bad}");
}
}
/// A resolution gives one size for every display, or one for each display, comma-separated:
/// each display's window opens at its own, and the device is given them in the displays'
/// order. Sizes that are all the same are that one size, and all the device's own none.
/// Another count of sizes than the displays is refused, saying what to give.
#[test]
fn each_display_s_window_opens_at_its_own_size() {
let d = |count: u32, resolution: &str| Display {
count,
resolution: resolution.into(),
..Default::default()
};
assert_eq!(
d(3, "2560x1440").window_sizes().unwrap(),
[(2560, 1440), (2560, 1440), (2560, 1440)]
);
let two = d(2, "2560x1440, 1920x1080");
assert_eq!(two.window_sizes().unwrap(), [(2560, 1440), (1920, 1080)]);
assert_eq!(
two.qemu_resolution().as_deref(),
Some("2560x1440,1920x1080")
);
assert_eq!(
d(2, "1280x720,1280x720").qemu_resolution().as_deref(),
Some("1280x720")
);
assert_eq!(d(2, "1920x1080,1920x1080").qemu_resolution(), None);
let wrong = d(3, "2560x1440,1920x1080").check().unwrap_err().to_string();
assert_eq!(
wrong,
"the resolution gives 2 sizes for 3 displays: give one size for every display, or one \
for each display, comma-separated, as 2560x1440,1920x1080"
);
let one = d(1, "2560x1440,1920x1080").check().unwrap_err().to_string();
assert!(
one.starts_with("the resolution gives 2 sizes for 1 display: "),
"{one}"
);
assert!(d(2, "2560x1440,0x1080").check().is_err());
}
#[test]
fn sizes() {
assert_eq!(parse_size_mib("8G").unwrap(), 8192);
@@ -1294,6 +1466,7 @@ pub(crate) mod tests {
driver_file: Some("/usr/share/vulkan/icd.d/nvidia_icd.json".into()),
device_id: Some(0x2204),
select: Some("10de:2204".into()),
pci: None,
name: None,
},
audio: Audio::default(),
@@ -1312,6 +1485,7 @@ pub(crate) mod tests {
cpu_model: default_cpu_model(),
cpu_flags: default_cpu_flags(),
disk_controller: DiskController::Nvme,
disk_cache: DiskCache::Default,
disk_port: 3,
}),
vmapple: None,
@@ -1549,6 +1723,257 @@ pub(crate) mod tests {
}
}
/// A save keeps what a newer reims-ctl wrote into a VM's settings, as an interface open since
/// before an update, or an older build a switch of channel installed, saves them. A key of the
/// newer build's own, one in a table this build has, and a table of its own stay as written,
/// byte for byte, and only the changed setting's line differs. A save that changes nothing
/// writes the same bytes.
#[test]
fn a_save_keeps_what_a_newer_build_wrote() {
let env = crate::testenv::Env::new("newer-settings");
let dir = env.root.join("t");
std::fs::create_dir_all(&dir).unwrap();
let file = dir.join(CONFIG_FILE);
Vm {
dir: dir.clone(),
config: x86_64_config(),
}
.save()
.unwrap();
let ours = std::fs::read_to_string(&file).unwrap();
let newer = ours
.replacen(
"stop_timeout_secs = 90\n",
"stop_timeout_secs = 90\npacing = \"smooth\"\n",
1,
)
.replacen("[display]\n", "[display]\nhdr = \"pq\"\n", 1)
.replacen(
"[q35]\n",
"[snapshots]\nkeep = 3\nnames = [\"a\", \"b\"]\n\n[q35]\n",
1,
);
for added in ["pacing = ", "hdr = ", "[snapshots]"] {
assert!(newer.contains(added), "{added}: {newer}");
}
std::fs::write(&file, &newer).unwrap();
let mut vm = Vm::load(&dir).unwrap();
assert_eq!(vm.config, x86_64_config());
vm.save().unwrap();
assert_eq!(std::fs::read_to_string(&file).unwrap(), newer);
vm.config.memory_mib = 16384;
vm.save().unwrap();
let edited = newer.replacen("memory_mib = 8192\n", "memory_mib = 16384\n", 1);
assert_ne!(edited, newer);
assert_eq!(std::fs::read_to_string(&file).unwrap(), edited);
}
/// Every kind of change a save makes keeps what a newer build wrote: a cleared setting's key
/// goes, a key is added to a table, a `[[usb]]` table removed beside one kept leaves the kept
/// one's own keys, and a `[[host_disk]]` table is added. What an older build wrote and this
/// one retired goes ([`RETIRED`]).
#[test]
fn every_kind_of_change_keeps_what_a_newer_build_wrote() {
let env = crate::testenv::Env::new("newer-settings-changes");
let dir = env.root.join("t");
std::fs::create_dir_all(&dir).unwrap();
let file = dir.join(CONFIG_FILE);
let usb = |id: &str, name: &str| UsbDevice {
id: id.into(),
port: None,
name: name.into(),
};
let mut c = x86_64_config();
c.usb = vec![usb("1050:0407", "key"), usb("046d:c52b", "receiver")];
Vm {
dir: dir.clone(),
config: c,
}
.save()
.unwrap();
let ours = std::fs::read_to_string(&file).unwrap();
let newer = ours
.replacen(
"stop_timeout_secs = 90\n",
"stop_timeout_secs = 90\npacing = \"smooth\"\nvideo_acceleration = false\n",
1,
)
.replacen("[display]\n", "[display]\nhdr = \"pq\"\nhidpi = true\n", 1)
.replacen(
"id = \"046d:c52b\"\n",
"id = \"046d:c52b\"\nspeed = \"high\"\n",
1,
);
assert!(newer.contains("speed = "), "{newer}");
std::fs::write(&file, &newer).unwrap();
let mut vm = Vm::load(&dir).unwrap();
vm.config.q35.as_mut().unwrap().installer = None;
vm.config.extra_env.insert("B".into(), "c".into());
vm.config.usb.remove(0);
vm.config.host_disks.push(HostDiskChoice {
path: "/dev/disk/by-id/ata-disk".into(),
name: String::new(),
});
vm.save().unwrap();
let saved = std::fs::read_to_string(&file).unwrap();
assert_eq!(Vm::load(&dir).unwrap().config, vm.config);
for kept in [
"pacing = \"smooth\"\n",
"[display]\nhdr = \"pq\"\n",
"id = \"046d:c52b\"\nspeed = \"high\"\n",
"B = \"c\"\n",
"[[host_disk]]\n",
] {
assert!(saved.contains(kept), "{kept}: {saved}");
}
for gone in ["video_acceleration", "hidpi", "installer = ", "1050:0407"] {
assert!(!saved.contains(gone), "{gone}: {saved}");
}
}
/// A save over settings this build can't read, here a graphics device a newer build added,
/// is refused, naming the file, and leaves the file as it was: a plain write would drop
/// what this build doesn't know.
#[test]
fn a_save_over_settings_this_build_cannot_read_leaves_them() {
let env = crate::testenv::Env::new("unreadable-settings");
let dir = env.root.join("t");
std::fs::create_dir_all(&dir).unwrap();
let file = dir.join(CONFIG_FILE);
let vm = Vm {
dir: dir.clone(),
config: x86_64_config(),
};
vm.save().unwrap();
let newer = format!(
"graphics = \"a-newer-device\"\n{}",
std::fs::read_to_string(&file).unwrap()
);
std::fs::write(&file, &newer).unwrap();
let e = vm.save().unwrap_err();
let refused = e
.downcast_ref::<crate::record::Refused>()
.unwrap_or_else(|| panic!("not refused: {e:#}"));
assert_eq!(refused.file, file);
assert_eq!(std::fs::read_to_string(&file).unwrap(), newer);
assert_eq!(crate::record::left_beside(&file), Vec::<PathBuf>::new());
}
/// A save over settings whose file is there and this build can't read, as one that isn't
/// UTF-8 or that its mode keeps from the user, is refused, naming the file, and leaves the file
/// byte for byte: taken for no file, it would be written over with this build's settings.
#[test]
fn a_save_over_a_settings_file_this_build_cannot_read_leaves_it() {
let env = crate::testenv::Env::new("unreadable-settings-file");
let dir = env.root.join("t");
let vm = Vm {
dir: dir.clone(),
config: x86_64_config(),
};
let file = dir.join(CONFIG_FILE);
crate::record::assert_unreadable_refused(&file, &|| vm.save());
assert_eq!(crate::record::left_beside(&file), Vec::<PathBuf>::new());
}
/// The registry's save over a file this build can't read, as one that isn't UTF-8 or that its
/// mode keeps from the user, is refused, naming the file, and leaves the file byte for byte.
#[test]
fn the_registry_s_save_over_a_file_this_build_cannot_read_leaves_it() {
let _env = crate::testenv::Env::new("unreadable-registry");
let mut reg = Registry::default();
reg.add("a", Path::new("/vms/a")).unwrap();
crate::record::assert_unreadable_refused(&paths::registry_file(), &|| reg.save());
}
/// Two saves of the registry at once, as two reims-ctl open make them, here from two threads,
/// each saving a list of its own over and over: every read of the file meanwhile is one list
/// whole, never a mix of the two or a cut, and every save succeeds; the last rename wins.
#[test]
fn two_saves_of_the_registry_at_once_leave_one_list_whole() {
let _env = crate::testenv::Env::new("registry-two-saves");
let list = |name: &str| {
let mut reg = Registry::default();
// Many VMs, so that a write takes a while.
for n in 0..200 {
let dir = PathBuf::from(format!("/vms/{name}{n}"));
reg.add(&format!("{name}{n}"), &dir).unwrap();
}
reg
};
let lists = [list("a"), list("b")];
lists[0].save().unwrap();
let done = std::sync::atomic::AtomicBool::new(false);
let (failed, torn) = std::thread::scope(|s| {
let savers = lists.each_ref().map(|reg| {
s.spawn(move || {
(0..100)
.filter_map(|_| reg.save().err().map(|e| format!("{e:#}")))
.collect::<Vec<String>>()
})
});
// How many reads were not one list whole, and the first few.
let reader = s.spawn(|| {
let mut torn = (0, Vec::new());
while !done.load(std::sync::atomic::Ordering::Relaxed) {
let why = match Registry::load() {
Ok(read) if lists.contains(&read) => continue,
Ok(read) => format!("a list of {} VMs", read.vms.len()),
Err(e) => format!("{e:#}"),
};
torn.0 += 1;
if torn.1.len() < 3 {
torn.1.push(why);
}
}
torn
});
let failed: Vec<String> = savers.into_iter().flat_map(|t| t.join().unwrap()).collect();
done.store(true, std::sync::atomic::Ordering::Relaxed);
(failed, reader.join().unwrap())
});
assert!(
torn.0 == 0 && failed.is_empty(),
"{} reads not one list whole, as {:?}; {} saves failed, as {:?}",
torn.0,
torn.1,
failed.len(),
failed.first()
);
assert_eq!(
crate::record::left_beside(&paths::registry_file()),
Vec::<PathBuf>::new()
);
}
/// The registry's save keeps what a newer reims-ctl wrote into it: a key of its own, a key in
/// a VM's `[[vm]]` table and a table of its own stay as written, byte for byte, as a VM is
/// added, whose table is all that changes.
#[test]
fn the_registry_s_save_keeps_what_a_newer_build_wrote() {
let env = crate::testenv::Env::new("newer-registry");
let (a, b) = (env.root.join("a"), env.root.join("b"));
let mut reg = Registry::default();
reg.add("a", &a).unwrap();
reg.save().unwrap();
let file = paths::registry_file();
let ours = std::fs::read_to_string(&file).unwrap();
let pinned = ours.replacen("name = \"a\"\n", "name = \"a\"\npinned = true\n", 1);
assert_ne!(pinned, ours);
let newer = format!("version = 2\n\n{pinned}\n[groups]\nwork = [\"a\"]\n");
std::fs::write(&file, &newer).unwrap();
let mut reg = Registry::load().unwrap();
reg.add("b", &b).unwrap();
reg.save().unwrap();
let mut both = Registry::default();
both.add("a", &a).unwrap();
both.add("b", &b).unwrap();
let both = toml::to_string_pretty(&both).unwrap();
let b_table = both.strip_prefix(ours.as_str()).unwrap();
let want = newer.replacen("\n[groups]", &format!("{b_table}\n[groups]"), 1);
assert_eq!(std::fs::read_to_string(&file).unwrap(), want);
assert_eq!(Registry::load().unwrap(), reg);
}
/// A VM has 1 to 4 displays, the device's most; any other count saved by hand is refused.
#[test]
fn a_vm_has_1_to_4_displays() {
@@ -1590,22 +2015,20 @@ pub(crate) mod tests {
assert!(c.check().is_ok());
}
/// Capture input is saved only where it is not [`DEFAULT_CAPTURE`], so a VM whose settings
/// never chose follows the default, and the other value is saved and read back.
/// The `capture` an older reims-ctl saved, on or off, is read past with no error, and the
/// next save leaves it out: the windows have no such setting.
#[test]
fn capture_is_saved_only_off_the_default() {
let mut c = x86_64_config();
assert_eq!(c.display.capture, DEFAULT_CAPTURE);
fn a_saved_capture_is_read_past_and_left_out() {
let c = x86_64_config();
let text = toml::to_string_pretty(&c).unwrap();
assert!(!text.contains("capture"), "{text}");
assert_eq!(toml::from_str::<VmConfig>(&text).unwrap(), c);
c.display.capture = !DEFAULT_CAPTURE;
let text = toml::to_string_pretty(&c).unwrap();
assert!(
text.contains(&format!("capture = {}", !DEFAULT_CAPTURE)),
"{text}"
);
assert_eq!(toml::from_str::<VmConfig>(&text).unwrap(), c);
for saved in ["capture = false", "capture = true"] {
let old = text.replacen("[display]\n", &format!("[display]\n{saved}\n"), 1);
assert!(old.contains(saved), "{old}");
let read = toml::from_str::<VmConfig>(&old).unwrap();
assert_eq!(read, c);
assert!(!toml::to_string_pretty(&read).unwrap().contains("capture"));
}
}
/// A VM an earlier create saved with an SSH port of 0 has no forward, as `set --ssh-port 0`
@@ -1695,6 +2118,32 @@ pub(crate) mod tests {
assert!(e.contains("no [q35] settings"), "{e}");
}
/// A GPU's PCI address is `domain:bus:device.function` in hex, which names it to
/// `DRI_PRIME` as `pci-domain_bus_device_function`; the check refuses anything else.
#[test]
fn a_gpu_s_pci_address_names_it_to_dri_prime() {
let mut c = x86_64_config();
assert_eq!(c.gpu.dri_prime().unwrap(), None);
c.gpu.pci = Some("0000:02:00.0".into());
let prime = c.gpu.dri_prime().unwrap();
assert_eq!(prime.as_deref(), Some("pci-0000_02_00_0"));
c.gpu.pci = Some("0000:C7:1F.7".into());
let prime = c.gpu.dri_prime().unwrap();
assert_eq!(prime.as_deref(), Some("pci-0000_c7_1f_7"));
assert!(c.check().is_ok());
for bad in [
"",
"02:00.0",
"0000:02:00",
"0000:2:00.0",
"0000:02:00.10",
"0000_02_00_0",
] {
c.gpu.pci = Some(bad.into());
assert!(c.check().is_err(), "{bad:?}");
}
}
/// A GPU's select names its vendor and device IDs in hex, as `MESA_VK_DEVICE_SELECT` takes
/// them; the check refuses anything else.
#[test]
+7 -2
View File
@@ -62,9 +62,14 @@ uuid = { version = "1.29.2", features = ["v4"] }
# The IPSW is a zip (ipsw.rs).
zip = { version = "9.5.1", default-features = false, features = ["deflate-flate2"] }
# The space free on a volume (src/sys/windows.rs).
# The space free on a volume, the space a file takes on it, and sparse files (src/sys/windows.rs).
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Storage_FileSystem"] }
windows-sys = { version = "0.61.2", features = [
"Win32_Foundation",
"Win32_Storage_FileSystem",
"Win32_System_IO",
"Win32_System_Ioctl",
] }
[dev-dependencies]
# Writes the tests' synthetic IPSWs.
+12 -1
View File
@@ -247,7 +247,7 @@ The guest can't keep such a policy through a change of its own (`policy_nonce.rs
account (opendirectoryd's PlistFile module, when AppleVPKeyStore reports no owners), and at any
later LocalPolicy change, the guest begins a local policy nonce update, decodes the current
policy in libbootpolicy to re-sign it for the new nonce, and ends the update, which blesses the
new nonce and removes the policies named for the old **[read from code, 27.0.1 and 27.2.1]**.
new nonce and removes the policies named for the old, on 27.0.1 and 27.2.1.
libbootpolicy checks the policy's chain against Apple's roots alone (production, QA and the
Hacktivation one), compiled into it in the OS cryptex's dyld shared cache, which the project
can't change; it skips a policy it can't decode, the update still ends, and the next boot stops
@@ -363,6 +363,17 @@ Data out and has the first boot make it, by EACS:
guest wrote (the ean storage's keys among it), then removes the copies. It refuses while the
ean storage holds only `aptk`. The next boot unwraps the D-key, unlocks Data (boot mode
`_autounlock`) and goes to Setup Assistant **[measured]**.
- `mobile_obliterator` clears `/<G>/` in Preboot item by item, the request's `var` among them,
and stops at the first item it can't delete. A 27.2.1 (26B131) first boot under TCG on an
x86-64 Linux host failed to delete `PreLoginData`, which that boot had made ("Operation not
permitted"), left `var/db/.com.apple.eacs`, `Library` and `System`, and still made Data and
reset ("EACS completed with warnings"); the next boot ran EACS again from the request and
deleted the LocalPolicy `finish_eacs` had put back. That second run's deletion of
`PreLoginData` succeeded and it removed the request **[measured, 2026-12-02]**. So
`finish_eacs` first reads Preboot for the request (`pipeline::eacs_request_left`): where it is
left, it puts the partition and the nonces back as usual but keeps the copies, counts the boot
in `eacs-again` and asks for one more first boot, then finishes after it; after 3 boots that
leave it, it asks for a new restore.
- Its template migration (`templateMigrator`, in the BaseSystem) depends on how the restore left
the Update volume. With every volume recording 26A434's OS version and no
`Update/Hardware/Battery`, 9 of 16 fresh 14.6.1 restores failed it ("MobileObliteration
+46 -3
View File
@@ -282,14 +282,35 @@ fn lock(dir: &Path, name: &str) -> Result<File> {
.write(true)
.open(&path)
.with_context(|| format!("open {}", path.display()))?;
// flock(LOCK_EX | LOCK_NB) on Unix, LockFileEx on Windows; the lock goes when the file is
// closed.
if f.try_lock().is_err() {
if !matches!(try_lock_let_go(&f), Ok(true)) {
bail!("another download of {name} is running");
}
Ok(f)
}
/// How long [`try_lock_let_go`] waits for a lock another holds before it takes it for a running
/// holder's: a few milliseconds is what a forked child holds a lock on for on a busy host.
pub const LOCK_LET_GO: Duration = Duration::from_secs(1);
/// Takes `f`'s lock (flock(LOCK_EX | LOCK_NB) on Unix, LockFileEx on Windows; it goes when the
/// file is closed), waiting up to [`LOCK_LET_GO`] where another holds it: `Ok(false)` where it is
/// held still, `Err` where the file takes no lock. flock's lock is the open file's, which a fork
/// shares: a lock its holder let go of, its file closed or its process ended, is held on by each
/// child that another thread of the holder's process forked before, until that child execs.
pub fn try_lock_let_go(f: &File) -> std::io::Result<bool> {
let since = std::time::Instant::now();
loop {
match f.try_lock() {
Ok(()) => return Ok(true),
Err(std::fs::TryLockError::WouldBlock) if since.elapsed() < LOCK_LET_GO => {
std::thread::sleep(Duration::from_millis(5));
}
Err(std::fs::TryLockError::WouldBlock) => return Ok(false),
Err(std::fs::TryLockError::Error(e)) => return Err(e),
}
}
}
/// Hashes the first `have` bytes of the file at `path` into `hash`, opening it to read alone.
fn hash_prefix(path: &Path, have: u64, hash: &mut Sha1, cancel: &AtomicBool) -> Result<()> {
let f = File::open(path).with_context(|| format!("open {}", path.display()))?;
@@ -684,6 +705,28 @@ mod tests {
let _ = std::fs::remove_dir_all(&dir);
}
/// A lock its download let go of is held on by a child forked meanwhile, until the child
/// execs (flock's lock is the open file's, which the fork shares): the next download waits
/// for it rather than say another runs. A clone of the lock's descriptor, let go 100 ms
/// after the download's lock, stands in for the child.
#[test]
fn a_lock_a_forked_child_holds_on_is_waited_out() {
let dir = temp_dir("lock-held");
std::fs::create_dir_all(&dir).unwrap();
let held = lock(&dir, NAME).unwrap();
let child = held.try_clone().unwrap();
drop(held);
let exec = std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(100));
drop(child);
});
let taken = lock(&dir, NAME);
exec.join().unwrap();
assert!(taken.is_ok(), "{taken:?}");
drop(taken);
let _ = std::fs::remove_dir_all(&dir);
}
/// What a download still takes: the CDN's length, less what is here.
#[test]
fn what_a_download_still_takes() {
+3
View File
@@ -462,8 +462,11 @@ pub(crate) mod tests {
fn a_members_unix_mode_is_kept() {
let p = tempfile_path::TempPath::new("zip");
let mut w = zip::ZipWriter::new(File::create(&p.0).unwrap());
// Made on Unix, as Apple's IPSWs are: the writer marks a member made on Windows as DOS's,
// whose mode the reader makes up (0o664), unless the options name the system.
let opts = zip::write::SimpleFileOptions::default()
.compression_method(zip::CompressionMethod::Stored)
.system(zip::System::Unix)
.unix_permissions(0o755);
w.start_file("tool", opts).unwrap();
w.write_all(b"#!").unwrap();
+15 -4
View File
@@ -60,7 +60,8 @@ enum Command {
ecid: Option<u64>,
},
/// After a VM's first boot: macOS makes its Data volume at that boot and resets the VM, which
/// then doesn't start; this makes it bootable again, for Setup Assistant.
/// then doesn't start; this makes it bootable again, for Setup Assistant, or, where that boot
/// failed or left its request for the Data volume behind, ready for one more first boot.
FinishEacs {
/// The VM's directory.
dir: PathBuf,
@@ -155,8 +156,9 @@ fn restore(ipsw: PathBuf, dir: PathBuf, disk_gib: u64, ecid: Option<u64>) -> Res
);
println!(
"macOS {} makes its Data volume at the VM's first boot, then resets the VM, which \
then doesn't start. Once it has, run `reims-restore finish-eacs {}`; the next boot \
goes to Setup Assistant.",
then doesn't start. Once it has, run `reims-restore finish-eacs {}`. Where it says the \
VM needs one more first boot, boot it again and finish again; once it finishes, the \
next boot goes to Setup Assistant.",
done.version,
job.dir.display()
);
@@ -168,7 +170,15 @@ fn default_cache() -> Result<PathBuf> {
if let Some(x) = std::env::var_os("XDG_CACHE_HOME").filter(|x| !x.is_empty()) {
return Ok(PathBuf::from(x).join("reims-restore"));
}
let home = std::env::var_os("HOME").context("HOME is not set: pass --cache")?;
let home = std::env::var_os("HOME")
.or_else(|| {
if cfg!(windows) {
std::env::var_os("USERPROFILE")
} else {
None
}
})
.context("HOME is not set: pass --cache")?;
Ok(PathBuf::from(home).join(".cache/reims-restore"))
}
@@ -327,6 +337,7 @@ fn extract(
.create_new(true)
.open(out)
.with_context(|| format!("create {}", out.display()))?;
let _ = reims_restore::sys::set_sparse(&f);
f.set_len(src.len())?;
let mut buf = vec![0u8; 8 << 20];
let mut off = 0u64;
+282 -21
View File
@@ -88,6 +88,9 @@ pub const EACS_DISK: &str = "disk.pre-eacs";
pub const EACS_TRIES: &str = "eacs-tries";
/// The first boots a VM gets to make its Data volume by EACS before [`finish_eacs`] gives up.
pub const EACS_MAX_TRIES: u32 = 3;
/// Until [`finish_eacs`]: how many first boots made the Data volume but left EACS's request on
/// Preboot ([`eacs_request_left`]), each readied for one more first boot.
pub const EACS_AGAIN: &str = "eacs-again";
/// The auxiliary storage's size as QEMU attaches it.
const AUX_SIZE: u64 = aux::SIZE as u64;
@@ -445,6 +448,7 @@ fn check_dir(dir: &Path) -> Result<()> {
EACS_AUX,
EACS_DISK,
EACS_TRIES,
EACS_AGAIN,
] {
ensure!(
!dir.join(f).exists(),
@@ -475,6 +479,7 @@ impl Files {
for (name, size) in [(DISK, disk_size), (AUX_TRIMMED, AUX_SIZE)] {
let p = self.part(name);
let f = File::create(&p).with_context(|| format!("make {}", p.display()))?;
let _ = crate::sys::set_sparse(&f);
f.set_len(size)
.with_context(|| format!("size {} to {size} bytes", p.display()))?;
}
@@ -495,13 +500,19 @@ impl Files {
/// takes no space, where the file system makes one, else a sparse copy, once the space it
/// takes is free. Returns the bytes a copy takes, `None` for a clone.
fn keep_disk_for_eacs(&self) -> Result<Option<u64>> {
self.keep_disk_for_eacs_with(&clone_file)
}
/// [`Files::keep_disk_for_eacs`], making the clone with `clone`, whose refusal, for any
/// reason, falls back to the sparse copy.
fn keep_disk_for_eacs_with(&self, clone: &dyn Fn(&Path, &Path) -> bool) -> Result<Option<u64>> {
let (from, to) = (self.part(DISK), self.part(EACS_DISK));
if clone_file(&from, &to) {
if clone(&from, &to) {
return Ok(None);
}
let f = File::open(&from).context("open the disk")?;
let m = f.metadata()?;
let used = crate::sys::allocated(&m);
let used = crate::sys::allocated_at(&from, &m);
check_space(&self.dir, free_space(&self.dir)?, used)?;
copy_sparse(&f, 0, m.len(), &to, 0)?;
Ok(Some(used))
@@ -530,7 +541,9 @@ impl Files {
if name == EACS_DISK && !p.exists() {
continue;
}
File::open(&p)
OpenOptions::new()
.write(true)
.open(&p)
.and_then(|f| f.sync_all())
.with_context(|| format!("flush {}", p.display()))?;
}
@@ -625,6 +638,7 @@ fn clone_file(from: &Path, to: &Path) -> bool {
fn copy_sparse(from: &File, at: u64, len: u64, to: &Path, to_at: u64) -> Result<()> {
use reims_apfs::file_at::FileAt as _;
let out = File::create(to).with_context(|| format!("make {}", to.display()))?;
let _ = crate::sys::set_sparse(&out);
out.set_len(to_at + len)?;
let mut buf = vec![0u8; 1 << 20];
let mut done = 0;
@@ -652,8 +666,11 @@ fn copy_sparse(from: &File, at: u64, len: u64, to: &Path, to_at: u64) -> Result<
/// policy nonces back into NVRAM ([`aux::put_back_policy_entries`]), keeping what the guest
/// wrote in the auxiliary storage, its keys in the ean storage among it; then removes the copies.
/// Refuses before the guest's keystore has made its keys. After a first boot whose EACS failed
/// ([`aux::recovery_boot_mode`]) it starts the VM again instead ([`start_again`]). A run cut
/// short can run again.
/// ([`aux::recovery_boot_mode`]) it starts the VM again instead ([`start_again`]). After one that
/// made the Data volume but left EACS's request on Preboot ([`eacs_request_left`]), which would
/// have the next boot run EACS again and delete what this puts back, it puts the same back but
/// keeps the copies, counts the boot in [`EACS_AGAIN`] and asks for one more first boot; after
/// [`EACS_MAX_TRIES`] such boots it leaves the VM as it is. A run cut short can run again.
pub fn finish_eacs(dir: &Path) -> Result<()> {
use reims_apfs::file_at::FileAt as _;
let (isc, pre_aux) = (dir.join(EACS_ISC), dir.join(EACS_AUX));
@@ -677,6 +694,25 @@ pub fn finish_eacs(dir: &Path) -> Result<()> {
"the VM's first boot hasn't made its keys yet: boot it once, until macOS has made its \
Data volume and reset, then finish"
);
let left = eacs_request_left(&dir.join(DISK))?;
let again = dir.join(EACS_AGAIN);
let boots_left_it = match &left {
Some(path) => {
let n = std::fs::read_to_string(&again)
.ok()
.and_then(|s| s.trim().parse::<u32>().ok())
.unwrap_or(0)
+ 1;
ensure!(
n < EACS_MAX_TRIES,
"macOS's first boot made its Data volume but left the request for it on Preboot \
({path}) in all {EACS_MAX_TRIES} tries, so every boot makes it again: restore \
the VM again"
);
n
}
None => 0,
};
let restored =
std::fs::read(&pre_aux).with_context(|| format!("read {}", pre_aux.display()))?;
aux::put_back_policy_entries(&mut a, &restored)?;
@@ -717,10 +753,20 @@ pub fn finish_eacs(dir: &Path) -> Result<()> {
}
disk.sync_all().context("flush the disk")?;
put_aux(dir, &a)?;
if let Some(path) = left {
std::fs::write(&again, format!("{boots_left_it}\n"))
.with_context(|| format!("write {}", again.display()))?;
bail!(
"macOS's first boot made its Data volume but left the request for it on Preboot \
({path}), so the next boot makes it again (try {boots_left_it} of \
{EACS_MAX_TRIES}): the VM is ready for that boot, so boot it once more, until macOS \
has made its Data volume and reset, then finish again"
);
}
for f in [&isc, &pre_aux] {
std::fs::remove_file(f).with_context(|| format!("remove {}", f.display()))?;
}
for f in [dir.join(EACS_DISK), dir.join(EACS_TRIES)] {
for f in [dir.join(EACS_DISK), dir.join(EACS_TRIES), again] {
if f.exists() {
std::fs::remove_file(&f).with_context(|| format!("remove {}", f.display()))?;
}
@@ -728,10 +774,50 @@ pub fn finish_eacs(dir: &Path) -> Result<()> {
Ok(())
}
/// Where the VM's first boot left EACS's request ([`plan::EACS_COOKIE`]) under the volume
/// group's directory in the main container's Preboot, its path there; `None` where it is gone.
/// `mobile_obliterator` deletes the group's directory there item by item, the request's `var`
/// among them, but stops at the first item it can't delete: a 27.2.1 (26B131) first boot under
/// TCG on an x86-64 Linux host failed to delete `PreLoginData`, which the boot had made ("Operation
/// not permitted"), left `var`, `Library` and `System`, and still made the Data volume and reset.
/// The next boot ran EACS again from the request, deleting the macOS LocalPolicy [`finish_eacs`]
/// had put back; that boot's deletion of `PreLoginData` succeeded **[measured]**.
///
/// # Errors
///
/// The disk's main container, its System or Preboot volume, or a record on the path fails to
/// read or check.
fn eacs_request_left(disk: &Path) -> Result<Option<String>> {
let f = File::open(disk).with_context(|| format!("open {}", disk.display()))?;
let c = reims_apfs::open(Arc::new(f)).context("open the disk's main container")?;
let group = c
.system_volume()
.context("find the main container's System volume")?
.sb
.volume_group_id;
let path = format!(
"{}/{}",
Uuid::from_bytes(group).to_string().to_uppercase(),
plan::EACS_COOKIE
);
let volumes = c.volumes().context("read the main container's volumes")?;
let preboot = volumes
.iter()
.find(|v| v.role() == reims_apfs::ondisk::apfs::ROLE_PREBOOT)
.context("the main container has no Preboot volume")?;
match preboot.lookup(&path) {
Ok(e) if e.is_file() => Ok(Some(path)),
// A component that is not there, or not a directory: no request.
Ok(_) | Err(reims_apfs::Error::Invalid(_)) => Ok(None),
Err(e) => Err(e).with_context(|| format!("look for {path} on Preboot")),
}
}
/// After a first boot whose EACS failed: puts the VM back as the restore left it, the disk from
/// [`EACS_DISK`] and the auxiliary storage from [`EACS_AUX`], for another first boot, and counts
/// the failed boot in [`EACS_TRIES`]; after [`EACS_MAX_TRIES`] failed boots it leaves the VM as
/// it is. Either way it returns an error that says which, and what to do next.
/// [`EACS_DISK`] and the auxiliary storage from [`EACS_AUX`], for another first boot, counts the
/// failed boot in [`EACS_TRIES`] and starts [`EACS_AGAIN`]'s count over; after
/// [`EACS_MAX_TRIES`] failed boots it leaves the VM as it is. Either way it returns an error that
/// says which, and what to do next.
fn start_again(dir: &Path) -> Result<()> {
let tries = dir.join(EACS_TRIES);
let failed = std::fs::read_to_string(&tries)
@@ -759,13 +845,21 @@ fn start_again(dir: &Path) -> Result<()> {
let f = File::open(&pre).with_context(|| format!("open {}", pre.display()))?;
copy_sparse(&f, 0, f.metadata()?.len(), &part, 0)?;
}
File::open(&part)
OpenOptions::new()
.write(true)
.open(&part)
.and_then(|f| f.sync_all())
.with_context(|| format!("flush {}", part.display()))?;
std::fs::rename(&part, dir.join(DISK)).context("move the restored disk back into place")?;
let restored = std::fs::read(dir.join(EACS_AUX))
.with_context(|| format!("read {}", dir.join(EACS_AUX).display()))?;
put_aux(dir, &restored)?;
// The disk is the restore's again, so no boot since has left EACS's request on it: the count
// of those starts over.
let again = dir.join(EACS_AGAIN);
if again.exists() {
std::fs::remove_file(&again).with_context(|| format!("remove {}", again.display()))?;
}
std::fs::write(&tries, format!("{failed}\n"))
.with_context(|| format!("write {}", tries.display()))?;
bail!(
@@ -784,7 +878,7 @@ fn put_aux(dir: &Path, trimmed: &[u8]) -> Result<()> {
let p = dir.join(name);
let tmp = dir.join(format!("{name}.part"));
std::fs::write(&tmp, bytes).with_context(|| format!("write {}", tmp.display()))?;
File::open(&tmp)?.sync_all()?;
OpenOptions::new().write(true).open(&tmp)?.sync_all()?;
std::fs::rename(&tmp, &p).with_context(|| format!("move {} into place", p.display()))?;
}
Ok(())
@@ -878,7 +972,6 @@ mod tests {
let isc = table.isc();
write_at(&f.part(DISK), isc.offset() + 0x1000, b"the restore's iSC");
write_at(&f.part(DISK), isc.offset() + isc.len() - 0x1000, b"its end");
write_at(&f.part(DISK), table.main().offset(), b"the main container");
let n = Nvram {
policy_nonces: [
[0x11; 16], [0x22; 16], [3; 16], [4; 16], [5; 16], [6; 16], [7; 16],
@@ -886,6 +979,7 @@ mod tests {
container: table.main().guid,
group: Uuid::from_u128(0xbf30_4653),
};
write_main(&f.part(DISK), &table, n.group, true);
let a = aux::trimmed(&n, b"a ticket of the tests' own").unwrap();
std::fs::write(f.part(AUX_TRIMMED), &a).unwrap();
f.keep_for_eacs(&table).unwrap();
@@ -893,15 +987,77 @@ mod tests {
(d, table, n, a)
}
/// A main container of the tests' own at `t`'s main partition of `disk`: a System volume in
/// volume group `group`, and a Preboot volume holding the group's `var/db`, with EACS's
/// request in it where `request`.
fn write_main(disk: &Path, t: &Table, group: Uuid, request: bool) {
use reims_apfs::ondisk::apfs::{ROLE_PREBOOT, ROLE_SYSTEM};
use reims_apfs::write::{self as w, fsbuild};
let item = |path: String, kind| fsbuild::Item {
path,
kind,
mode: 0o755,
uid: 0,
gid: 0,
bsd_flags: 0,
xattrs: Vec::new(),
};
let g = group.to_string().to_uppercase();
let mut items = vec![
item(g.clone(), fsbuild::Kind::Dir),
item(format!("{g}/var"), fsbuild::Kind::Dir),
item(format!("{g}/var/db"), fsbuild::Kind::Dir),
];
let cookie = plan::eacs_cookie(group, t.main().guid);
if request {
items.push(item(
format!("{g}/{}", plan::EACS_COOKIE),
fsbuild::Kind::File {
len: cookie.len() as u64,
},
));
}
let mut system = w::VolumeDef::of(
"Macintosh HD",
[1; 16],
ROLE_SYSTEM,
fsbuild::build(&[], true, w::FORMAT_TIME).unwrap(),
);
system.system = true;
system.group = *group.as_bytes();
let preboot = w::VolumeDef::of(
"Preboot",
[2; 16],
ROLE_PREBOOT,
fsbuild::build(&items, true, w::FORMAT_TIME).unwrap(),
);
let block = w::geometry::BLOCK_SIZE;
let formed = w::container(
t.main().len() / block,
[3; 16],
w::FORMAT_TIME,
w::key_os_version("26B131").unwrap(),
vec![system, preboot],
)
.unwrap();
let base = t.main().offset();
for (addr, b) in &formed.blocks {
write_at(disk, base + addr * block, b);
}
for first in &formed.stream_blocks[1] {
write_at(disk, base + first * block, &cookie);
}
}
/// What a guest's EACS boot leaves, as far as finishing reads it: other bytes in the iBoot
/// system container and the main container, the keystore's entries counted in the ean
/// storage, and NVRAM's policy nonces not the restore's.
/// system container, the main container without EACS's request, the keystore's entries
/// counted in the ean storage, and NVRAM's policy nonces not the restore's.
fn boot_by_eacs(d: &Path, t: &Table, n: &Nvram) {
let isc = t.isc();
let disk = d.join(DISK);
write_at(&disk, isc.offset() + 0x1000, &[0; 17]);
write_at(&disk, isc.offset() + 0x20_0000, b"the guest's iSC");
write_at(&disk, t.main().offset(), b"the guest's Data");
write_main(&disk, t, n.group, false);
let mut other = n.clone();
other.policy_nonces[1] = [0x99; 16];
let mut a = aux::trimmed(&other, b"a ticket of the tests' own").unwrap();
@@ -939,6 +1095,8 @@ mod tests {
boot_by_eacs(&d, &t, &n);
std::fs::write(d.join(EACS_DISK), b"the restored disk").unwrap();
std::fs::write(d.join(EACS_TRIES), b"1\n").unwrap();
std::fs::write(d.join(EACS_AGAIN), b"1\n").unwrap();
let main = read_at(&d.join(DISK), t.main().offset(), 0x1_0000);
finish_eacs(&d).unwrap();
let disk = d.join(DISK);
let isc = t.isc();
@@ -951,7 +1109,11 @@ mod tests {
read_at(&disk, isc.offset() + isc.len() - 0x1000, 7),
b"its end"
);
assert_eq!(read_at(&disk, t.main().offset(), 16), b"the guest's Data");
assert_eq!(
read_at(&disk, t.main().offset(), 0x1_0000),
main,
"the main container stays as the guest left it"
);
let a = std::fs::read(d.join(AUX_TRIMMED)).unwrap();
assert_eq!(
aux::ean_entries(&a[aux::EAN_AT..]),
@@ -972,7 +1134,7 @@ mod tests {
let vz = std::fs::read(d.join(AUX)).unwrap();
assert_eq!(&vz[..aux::HEADER_LEN], &aux::vz_header()[..]);
assert_eq!(&vz[aux::HEADER_LEN..], &a[..]);
for f in [EACS_ISC, EACS_AUX, EACS_DISK, EACS_TRIES] {
for f in [EACS_ISC, EACS_AUX, EACS_DISK, EACS_TRIES, EACS_AGAIN] {
assert!(!d.join(f).exists(), "{f} is left");
}
assert!(finish_eacs(&d).is_err(), "nothing left to finish");
@@ -1000,6 +1162,7 @@ mod tests {
let mut a = std::fs::read(d.join(AUX_TRIMMED)).unwrap();
aux::add_system_entry(&mut a, 0, "recovery-boot-mode", b"the guest's");
std::fs::write(d.join(AUX_TRIMMED), &a).unwrap();
let main = read_at(&d.join(DISK), t.main().offset(), 0x1_0000);
let e = finish_eacs(&d).unwrap_err().to_string();
assert!(e.contains("failed to make its Data volume"), "{e}");
assert_eq!(
@@ -1007,14 +1170,91 @@ mod tests {
a,
"left as it is"
);
assert_eq!(
read_at(&d.join(DISK), t.main().offset(), 16),
b"the guest's Data"
);
assert_eq!(read_at(&d.join(DISK), t.main().offset(), 0x1_0000), main);
assert!(d.join(EACS_ISC).exists() && d.join(EACS_AUX).exists());
std::fs::remove_dir_all(&d).unwrap();
}
#[test]
fn a_restore_for_eacs_leaves_its_request_on_preboot() {
let (d, t, n, _) = restored_for_eacs();
let path = format!(
"{}/{}",
n.group.to_string().to_uppercase(),
plan::EACS_COOKIE
);
assert_eq!(eacs_request_left(&d.join(DISK)).unwrap(), Some(path));
boot_by_eacs(&d, &t, &n);
assert_eq!(eacs_request_left(&d.join(DISK)).unwrap(), None);
std::fs::remove_dir_all(&d).unwrap();
}
/// A first boot that made the Data volume but left EACS's request on Preboot, as a 27.2.1
/// first boot under TCG did when it failed to delete `PreLoginData` **[measured]**: finishing
/// puts the restore's iSC and nonces back for one more first boot, keeps the copies, and
/// finishes after a boot that removes the request.
#[test]
fn finishing_eacs_after_a_boot_that_left_its_request_readies_another() {
let (d, t, n, _) = restored_for_eacs();
std::fs::write(d.join(EACS_DISK), b"the restored disk").unwrap();
for k in 1..EACS_MAX_TRIES {
boot_by_eacs(&d, &t, &n);
write_main(&d.join(DISK), &t, n.group, true);
let e = finish_eacs(&d).unwrap_err().to_string();
assert!(e.contains("left the request for it on Preboot"), "{e}");
assert!(e.contains(&format!("try {k} of {EACS_MAX_TRIES}")), "{e}");
assert_eq!(
read_at(&d.join(DISK), t.isc().offset() + 0x1000, 17),
b"the restore's iSC"
);
let a = std::fs::read(d.join(AUX_TRIMMED)).unwrap();
assert_eq!(aux::ean_entries(&a[aux::EAN_AT..]), Some(3));
let parts = aux::read_bank(&a[aux::NVRAM_AT..aux::NVRAM_AT + 0x8_0000]).unwrap();
let system = &parts.iter().find(|(p, _)| p == "system").unwrap().1;
let nonces = &system
.iter()
.find(|(k, _)| k == "boop-storage-nonces")
.unwrap()
.1;
assert_eq!(nonces, &n.policy_nonces.concat());
for f in [EACS_ISC, EACS_AUX, EACS_DISK] {
assert!(d.join(f).is_file(), "{f} is kept for the next boot");
}
assert_eq!(
std::fs::read_to_string(d.join(EACS_AGAIN)).unwrap(),
format!("{k}\n")
);
}
boot_by_eacs(&d, &t, &n);
finish_eacs(&d).unwrap();
for f in [EACS_ISC, EACS_AUX, EACS_DISK, EACS_AGAIN] {
assert!(!d.join(f).exists(), "{f} is left");
}
std::fs::remove_dir_all(&d).unwrap();
}
#[test]
fn finishing_eacs_gives_up_when_every_boot_leaves_its_request() {
let (d, t, n, _) = restored_for_eacs();
boot_by_eacs(&d, &t, &n);
write_main(&d.join(DISK), &t, n.group, true);
let k = EACS_MAX_TRIES - 1;
std::fs::write(d.join(EACS_AGAIN), format!("{k}\n")).unwrap();
let a = std::fs::read(d.join(AUX_TRIMMED)).unwrap();
let e = finish_eacs(&d).unwrap_err().to_string();
assert!(e.contains("restore the VM again"), "{e}");
assert_eq!(
std::fs::read(d.join(AUX_TRIMMED)).unwrap(),
a,
"left as it is"
);
assert_eq!(
read_at(&d.join(DISK), t.isc().offset() + 0x1000, 17),
[0; 17]
);
std::fs::remove_dir_all(&d).unwrap();
}
#[test]
fn a_restore_keeps_its_disk_to_start_again_from() {
let d = temp_dir();
@@ -1032,6 +1272,24 @@ mod tests {
std::fs::remove_dir(&d).unwrap();
}
/// Where the file system makes no clone (ext4), the restore keeps its disk as a sparse copy
/// of the same bytes, on any file system the test runs on.
#[test]
fn a_restore_keeps_a_copy_of_its_disk_where_no_clone_is_made() {
let d = temp_dir();
let f = Files::new(&d);
f.make(1 << 20).unwrap();
write_at(&f.part(DISK), 0x1000, b"the restored disk");
let copied = f.keep_disk_for_eacs_with(&|_, _| false).unwrap();
assert!(copied.is_some(), "a copy, not a clone");
let kept = f.part(EACS_DISK);
assert_eq!(std::fs::metadata(&kept).unwrap().len(), 1 << 20);
assert_eq!(read_at(&kept, 0x1000, 17), b"the restored disk");
f.discard();
assert_eq!(std::fs::read_dir(&d).unwrap().count(), 0);
std::fs::remove_dir(&d).unwrap();
}
/// Sets a VM of the tests' small files back to after a first boot whose EACS failed: the
/// guest's disk, and the restore's auxiliary storage with NVRAM asking for recoveryOS.
fn fail_first_boot(d: &Path, restored: &[u8]) {
@@ -1062,6 +1320,8 @@ mod tests {
fn finishing_eacs_after_a_failed_first_boot_starts_the_vm_again() {
let (d, restored) = failed_first_boot();
for t in 1..EACS_MAX_TRIES {
// A boot before this one left EACS's request, on the disk the restore's replaces.
std::fs::write(d.join(EACS_AGAIN), b"1\n").unwrap();
let e = finish_eacs(&d).unwrap_err().to_string();
assert!(e.contains(&format!("try {t} of {EACS_MAX_TRIES}")), "{e}");
assert_eq!(std::fs::read(d.join(DISK)).unwrap(), b"the restored disk");
@@ -1072,6 +1332,7 @@ mod tests {
for f in [EACS_DISK, EACS_ISC, EACS_AUX] {
assert!(d.join(f).is_file(), "{f} is kept for the next try");
}
assert!(!d.join(EACS_AGAIN).exists(), "its count starts over");
fail_first_boot(&d, &restored);
}
let e = finish_eacs(&d).unwrap_err().to_string();
+16 -21
View File
@@ -10,28 +10,23 @@
//! while another, uninterruptible, runs: the update's first step fails, nothing is rolled or
//! removed, and the policy the restore wrote stays the blessed one.
//!
//! The kext's command for the update begins with
//! The kext's command for the update begins with two checks of the local update's state, a
//! record of bytes. The first reads the state's byte and, unless an update is running, branches
//! past the refusal to make the new nonce. The second reads, from the record's fourth byte,
//! whether the running update is interruptible, and branches to the refusal unless it is; an
//! interruptible one is logged and marked interrupted, and the command goes on to make the new
//! nonce. The patch turns the first branch into a `nop`, so the refusal is taken unless a
//! running update is interruptible, which only that update's own timer makes it.
//!
//! ```text
//! ldrb wT, [xN] ; the local update's state
//! cmp wT, #2 ; one running?
//! b.ne new ; no: make the new nonce
//! ldrb wT, [xN, #3] ; is it interruptible?
//! cmp wT, #1
//! b.ne refuse ; no: refuse this one
//! ... ; log it, and mark it interrupted:
//! strb wzr, [xN, #3]
//! new: mov w0, #3 ; the proposed local nonce
//! bl ... ; made new
//! ```
//!
//! and the patch makes its first `b.ne` a `nop`, so the refusal is taken unless a running update
//! is interruptible, which only that update's own timer makes it. The kext holds the first six
//! instructions' shape in other commands too; the update's beginning is the one whose first
//! branch lands, eight instructions on, on `mov w0, #3` and a `bl` right after
//! `strb wzr, [xN, #3]`. The bytes are read from the IPSW's own boot kernel collection at
//! install time, as the anchors are, and the restore checks there is one such place, and that
//! its bytes occur once in the kext, before it writes the patch.
//! What is matched (`begins_update`) is those six instructions: each check is a byte load from
//! the record, a compare with the running value (2) or the interruptible value (1), and a branch
//! if not equal, both loads into the same register from the same base register. The kext holds
//! that shape in other commands too; the update's beginning is the one whose first branch lands
//! eight instructions on, on a move of the proposed nonce, 3, into the first argument register,
//! with a store of zero to the record's fourth byte just before it and a call just after. The
//! bytes are read from the IPSW's own boot kernel collection at install time, as the anchors
//! are, and the restore checks there is one such place, and that its bytes occur once in the
//! kext, before it writes the patch.
use anyhow::{Result, ensure};
+4 -2
View File
@@ -1,6 +1,8 @@
//! What the restore asks the host's OS where Unix (`unix.rs`) and Windows (`windows.rs`) differ:
//! the space free on a file system, and the space a file takes on it. Positioned reads and writes
//! are reims-apfs's [`reims_apfs::file_at::FileAt`].
//! the space free on a file system, the space a file takes on it, and sparse files, whose ranges
//! never written take no space: the disk images the restore makes are, and NTFS makes a file
//! sparse only when asked ([`set_sparse`]). Positioned reads and writes are reims-apfs's
//! [`reims_apfs::file_at::FileAt`].
#[cfg(unix)]
mod unix;
+9 -3
View File
@@ -17,8 +17,14 @@ pub fn free_space(dir: &Path) -> Result<u64> {
Ok(u64::from(s.f_bavail) * u64::from(s.f_frsize))
}
/// The space the file `m` describes takes on its file system: its 512-byte blocks, fewer than
/// its length where it is sparse.
pub fn allocated(m: &std::fs::Metadata) -> u64 {
/// The space the file at `path`, which `m` describes, takes on its file system: its 512-byte
/// blocks, fewer than its length where it is sparse.
pub fn allocated_at(_path: &Path, m: &std::fs::Metadata) -> u64 {
m.blocks() * 512
}
/// Nothing: a file here leaves the ranges of it never written unallocated, as holes, wherever
/// its file system keeps them, with no flag to set first (NTFS needs one, `windows.rs`).
pub fn set_sparse(_file: &std::fs::File) -> std::io::Result<()> {
Ok(())
}
+90 -7
View File
@@ -1,10 +1,19 @@
//! [`super`] on Windows, where reims-ctl makes no arm64 VM (its host.rs), so no restore runs:
//! these answer as reims-ctl's code that the restore shares with x86-64 VMs needs them.
//! [`super`] on Windows: the space free on a volume, the space a file takes on it, and sparse
//! files. NTFS leaves the ranges of a file never written unallocated only once the file is
//! marked sparse (`FSCTL_SET_SPARSE`): a file that is not takes its whole length as it is sized,
//! so a VM's new disk, and the copy of it the restore keeps for EACS, would each take the disk's
//! whole size at once.
use anyhow::{Context, Result};
use std::fs::{File, Metadata};
use std::os::windows::ffi::OsStrExt as _;
use std::os::windows::io::AsRawHandle as _;
use std::path::Path;
use windows_sys::Win32::Storage::FileSystem::GetDiskFreeSpaceExW;
use windows_sys::Win32::Storage::FileSystem::{
GetCompressedFileSizeW, GetDiskFreeSpaceExW, INVALID_FILE_SIZE,
};
use windows_sys::Win32::System::IO::DeviceIoControl;
use windows_sys::Win32::System::Ioctl::FSCTL_SET_SPARSE;
/// The space free to this user on the volume `dir`, which exists, is on.
pub fn free_space(dir: &Path) -> Result<u64> {
@@ -26,8 +35,82 @@ pub fn free_space(dir: &Path) -> Result<u64> {
Ok(free)
}
/// The space the file `m` describes takes on its volume, counted as its length: a sparse file's
/// holes count as written, so a check of room for its copy asks for more than the copy takes.
pub fn allocated(m: &std::fs::Metadata) -> u64 {
m.len()
/// Marks `file`, open for writing, sparse, so that the ranges of it never written stay
/// unallocated: those `set_len` adds, and the all-zero blocks the restore's copies leave
/// unwritten. A volume that keeps no sparse files (FAT32, exFAT) refuses, and the file then
/// takes its whole length.
pub fn set_sparse(file: &File) -> std::io::Result<()> {
let mut returned = 0u32;
// SAFETY: the handle is open for the call, which takes no input or output buffer and runs
// synchronously, on a handle opened without overlapped I/O.
let ok = unsafe {
DeviceIoControl(
file.as_raw_handle(),
FSCTL_SET_SPARSE,
std::ptr::null(),
0,
std::ptr::null_mut(),
0,
&mut returned,
std::ptr::null_mut(),
)
};
if ok == 0 {
return Err(std::io::Error::last_os_error());
}
Ok(())
}
/// The space the file at `path`, which `m` describes, takes on its volume: its allocated
/// clusters (`GetCompressedFileSizeW`), fewer than its length where it is sparse or compressed;
/// its length where the call fails.
pub fn allocated_at(path: &Path, m: &Metadata) -> u64 {
let wide: Vec<u16> = path.as_os_str().encode_wide().chain(Some(0)).collect();
let mut high = 0u32;
// SAFETY: a NUL-terminated path, and one out-pointer the call fills.
let low = unsafe { GetCompressedFileSizeW(wide.as_ptr(), &mut high) };
// INVALID_FILE_SIZE is a size's low half too: the call's last error, NO_ERROR where it
// succeeded, tells the two apart.
if low == INVALID_FILE_SIZE && std::io::Error::last_os_error().raw_os_error() != Some(0) {
return m.len();
}
(u64::from(high) << 32) | u64::from(low)
}
#[cfg(test)]
mod tests {
use super::*;
/// A file marked sparse and sized to 1 GiB takes under 1 MiB of its volume, as
/// `allocated_at` reads it; on a volume that keeps no sparse files the test has nothing to
/// check.
#[test]
fn sparse_file_does_not_allocate_virtual_length_on_ntfs() {
let dir = std::env::temp_dir().join(format!("reims-restore-sparse-{}", std::process::id()));
let _ = std::fs::create_dir_all(&dir);
let path = dir.join("disk.img");
let f = File::create(&path).unwrap();
if set_sparse(&f).is_err() {
let _ = std::fs::remove_file(&path);
let _ = std::fs::remove_dir(&dir);
return;
}
f.set_len(1u64 << 30).unwrap();
drop(f);
std::fs::OpenOptions::new()
.write(true)
.open(&path)
.unwrap()
.sync_all()
.unwrap();
let m = std::fs::metadata(&path).unwrap();
let alloc = allocated_at(&path, &m);
let _ = std::fs::remove_file(&path);
let _ = std::fs::remove_dir(&dir);
assert_eq!(m.len(), 1u64 << 30);
assert!(
alloc < (1u64 << 20),
"expected sparse allocation < 1 MiB, got {alloc}"
);
}
}
+40
View File
@@ -9,10 +9,50 @@
//! dist` names the dylib it installs `@rpath/libreims_vgpu.dylib` (`xtask/src/dist/macos.rs`).
//! Linux needs nothing: a cdylib built here has no soname, and a host linked to it records its
//! file name.
//!
//! On every host: stamps the library with the commit its tree is at (`src/build_stamp.rs`).
#[path = "src/build_stamp.rs"]
mod build_stamp;
/// The library's crates and the workspace's manifest, whose change the stamp is read again for
/// (`src/build_stamp.rs`): a tree changed since the last read is marked dirty.
const SOURCES: [&str; 7] = [
"Cargo.toml",
"crates/reims-vgpu",
"crates/reims-vgpu-c",
"crates/reims-vgpu-graphics",
"crates/reims-vgpu-video",
"crates/reims-vgpu-vulkan",
"crates/reims-vgpu-window",
];
fn main() {
println!("cargo:rerun-if-changed=build.rs");
stamp();
if std::env::var("CARGO_CFG_TARGET_OS").is_ok_and(|os| os == "macos") {
println!("cargo:rustc-cdylib-link-arg=-Wl,-install_name,@rpath/libreims_vgpu_c.dylib");
}
}
/// Stamps the library with the commit its tree is at (`src/build_stamp.rs`), as
/// `RVG_BUILD_STAMP`, read again where the checkout's HEAD or index moves or a source of the
/// library changes.
fn stamp() {
let crate_dir =
std::path::PathBuf::from(std::env::var_os("CARGO_MANIFEST_DIR").unwrap_or_default());
let root = crate_dir.join("../..");
println!(
"cargo:rustc-env=RVG_BUILD_STAMP={}",
build_stamp::read(&root)
);
for file in build_stamp::git_files(&root) {
println!("cargo:rerun-if-changed={}", file.display());
}
for source in SOURCES {
let path = root.join(source);
if path.exists() {
println!("cargo:rerun-if-changed={}", path.display());
}
}
}
+130 -53
View File
@@ -59,7 +59,8 @@
// The host refused the memory, a pipe, a thread or the GPU device the call needs: the graphics
// device's region, its threads, or its GPU device, where the host has none the library can use
// or its driver refused it (rvg_graphics_device_create).
// or its driver refused it, or the pool's host memory, which the GPU refused
// (rvg_graphics_device_create).
#define RVG_ERR_HOST_RESOURCES 5
// The left button, in an RvgWindowPointerFn's `buttons`.
@@ -195,21 +196,36 @@ typedef void (*RvgDestroyFn)(void *ctx);
// (`reims-vgpu.graphics-queue-<id>`) or one of its lane's threads, which walk and commit its
// command buffers (`reims-vgpu.graphics-lane-<id>`), a pipeline compile's thread
// (`reims-vgpu.graphics-compile-<n>`), a thread that makes IOSurfaces' and pages blocks' views
// (`reims-vgpu.graphics-surfaces-<i>`), a thread that makes indirect command buffers
// (`reims-vgpu.graphics-surfaces-<i>`, and `reims-vgpu.graphics-views-<i>` for a pages block's
// view made after its answer), a thread that makes indirect command buffers
// (`reims-vgpu.icb-create-<i>`), a thread that lets go of a closed process's objects and answers
// its close (`reims-vgpu.graphics-closes-<i>`), a thread that moves a staged copy of a surface's
// device cache into its pages and answers what waited for it
// (`reims-vgpu.graphics-into-pages-<i>`), a video session's picture landing thread, which posts
// a decode's completion as the decode is done (`reims-vgpu.graphics-video-land`), or the
// platform's thread that runs a command buffer's scheduled or completed handler; or the host's
// own, inside rvg_graphics_device_mmio_write_taking.
// (`reims-vgpu.graphics-into-pages-<i>`), the thread that paces releases' copies of their
// surfaces' device caches into their pages, which answers a BLOCK_RELEASE as its turn comes
// (`reims-vgpu.graphics-release-pace`), the thread that tries again the EVENT_SIGNALLED to a
// shared event's other holders that their rings had no room for
// (`reims-vgpu.graphics-shared-events`), a take worker of the guest's Shared pool or of its
// Private blocks, which answers a POOL_TAKE or a PRIVATE_TAKE
// (`reims-vgpu.graphics-pool-take`, `reims-vgpu.graphics-private-take`), the windows' UI thread,
// which tells the guest of the host's pointer and scrolling (POINTER_OVER, POINTER_MOTION and
// SCROLL; on macOS the process's main thread, on Linux and Windows `reims-vgpu.ui`), a video
// session's picture landing thread, which posts a decode's completion as the decode is done
// (`reims-vgpu.graphics-video-land`), or the platform's thread that runs a command buffer's
// scheduled or completed handler; or the host's own, inside
// rvg_graphics_device_mmio_write_taking or rvg_graphics_device_doorbell_write.
// Never inside another call of the host's into the library. The library may hold locks of its
// own around it (docs/api.md section 5 names them), but none that a function it may call waits
// for, directly or through a thread of the library's, so it may call them at once. It may wait
// for a lock the host holds while it calls the device (QEMU's BQL), but not for one the host
// holds while it calls rvg_graphics_device_mmio_write_taking. May call: rvg_status_message and
// the rvg_graphics_device_* functions, except the release of its own device. Without it the
// guest gets no interrupt.
// holds while it calls rvg_graphics_device_mmio_write_taking or
// rvg_graphics_device_doorbell_write, nor, on any thread, for one the host holds around
// rvg_graphics_device_reset or a write of 0 to STATUS: those wait for the platform's completed
// handlers while the GPU work before them completes, and at most 30 s for locks of the library's
// it may hold around this (docs/api.md section 5). May call: rvg_status_message and the
// rvg_graphics_device_* functions, except the release of its own device; a reset called here waits
// for none of the GPU work committed before it (rvg_graphics_device_reset). Without it the guest
// gets no interrupt.
typedef void (*RvgGraphicsRaiseFn)(void *ctx, uint32_t vector);
// A position or size in pixels.
@@ -340,7 +356,9 @@ typedef void (*RvgCursorMoveAtFn)(void *ctx, uint32_t display);
// Thread: the device's pool thread (`reims-vgpu.graphics-pool`), never inside a call of the
// host's, with no lock of the library's held. It must not wait for a lock the host holds while
// it calls the device (QEMU's BQL): QEMU queues the add for its main loop. One piece at a time,
// in the order the device places them, each before its pool_remove. May call: nothing of the
// in the order the device places them, each before its pool_remove. Not called once
// rvg_graphics_device_release has closed the pool, at its start; a call the pool thread began
// before that may still be running, and the release waits for it. May call: nothing of the
// library's. Needed with a pool.
typedef void (*RvgGraphicsPoolAddFn)(void *ctx,
uint64_t physical_address,
@@ -358,8 +376,9 @@ typedef void (*RvgGraphicsPoolAddFn)(void *ctx,
// block back, never inside a call of the host's, with no lock of the library's held. It must not
// wait for a lock the host holds while it calls the device (QEMU queues the remove for its main
// loop). Once a piece, after its pool_add. Not called once rvg_graphics_device_release has
// begun: the host removes every piece it added before it releases the device. May call: nothing
// of the library's. Needed with a pool.
// closed the pool, at its start; a call the pool thread began before that may still be running,
// and the release waits for it. The host removes every piece it added before it releases the
// device. May call: nothing of the library's. Needed with a pool.
typedef void (*RvgGraphicsPoolRemoveFn)(void *ctx, uint64_t physical_address, uint64_t length);
// The graphics device's callbacks.
@@ -590,13 +609,14 @@ typedef struct {
uint32_t struct_size;
// NULL is a table with every callback absent.
const RvgGraphicsCallbacks *callbacks;
// NULL is no window: the display offers 1920 x 1080 at 60 Hz and shows nothing. Otherwise
// the library opens a window for the display, with its input as the window's callbacks,
// sized for its mode (1920 x 1080 where it has none). The window keeps its size: the
// display offers the guest one mode, the window's size in pixels at the refresh rate of the
// host screen it opens on, and tells the guest when the person resizes it. The guest's
// scanout is blitted out of the region into the window's drawables on the GPU at each of the
// display's refreshes, at the screen's rate, while the display shows no presented surface.
// NULL is no window: the display offers its headless mode (`headless_modes`, else
// `headless_mode_width` x `headless_mode_height`) at 60 Hz and shows nothing. Otherwise the
// library opens a window for the display, with its input as the window's callbacks, sized
// for its mode (1920 x 1080 where it has none). The window keeps its size: the display
// offers the guest one mode, the window's size in pixels at the refresh rate of the host
// screen it opens on, and tells the guest when the person resizes it. The guest's scanout is
// blitted out of the region into the window's drawables on the GPU at each of the display's
// refreshes, at the screen's rate, while the display shows no presented surface.
const RvgWindowConfig *window;
// The guest's RAM, or NULL. With it, where the host's page is the guest's 4 KiB, or 16 KiB
// for a guest that lays its pages out in 16 KiB (`RGFX_FEATURE_PAGES_16K`), the GPU uses an
@@ -606,7 +626,8 @@ typedef struct {
// down to 16 KiB, or the host GPU's answer where that is less; with no map, and on a GPU of
// its own memory, the host GPU's. The map's pages stay the guest's RAM, mapped, until the
// process exits (`RvgMemoryRange`): a host that discards guest RAM (a balloon, virtio-mem,
// hot-unplug) passes NULL. Its ranges may not overlap.
// hot-unplug) passes NULL. Its ranges may not overlap: a map whose ranges overlap, or one
// of whose ranges runs past the address space, is refused (RVG_ERR_INVALID_ARGUMENT).
const RvgMemoryMap *memory_map;
// With `memory_map`: the files behind its ranges, NULL for none, one entry per range, each
// duplicated during the create. Refused (RVG_ERR_INVALID_ARGUMENT), in this order: files
@@ -670,6 +691,34 @@ typedef struct {
uint64_t pool_physical_address;
// The range's length in bytes, the most the pool may take: 0 for none.
uint64_t pool_physical_length;
// A fact of the host's, which it finds by asking its hypervisor and sets from nothing else:
// 1 where the hypervisor takes no cacheable mapping of the GPU's own memory as guest memory,
// as QEMU finds under Linux's KVM on arm64 where the VM does not answer
// KVM_CAP_ARM_CACHEABLE_PFNMAP_SUPPORTED (KVM then refuses a cacheable VM_PFNMAP mapping as a
// memory slot); 0 where it takes one, every other host, and a host built before this field.
// At 1 each of the pool's blocks is ordinary memory of the library's own (on Linux a memfd
// it maps shared) that the GPU imports as a dma-buf, which pool_add then maps; at 0 the
// GPU's own memory. Nothing without a pool. Refused (RVG_ERR_INVALID_ARGUMENT): any other
// value, and 1 on a platform that makes no such blocks (macOS and Windows); refused
// (RVG_ERR_HOST_RESOURCES): 1 where the GPU refuses host memory as a dma-buf (NVIDIA's
// driver, or a Linux host without udmabuf), which the create finds by importing one block.
uint32_t pool_host_memory;
// Where `window` is NULL, the mode each display offers the guest first, in pixels, as a
// window config's `mode_width` gives the mode its window opens for: its width rounded down
// to a multiple of 16 and its height to even, at 60 Hz (no host screen shows the display,
// so none sets its rate), sized to each display's scanout room on a device of several. 0 in
// either is 1920 x 1080, as a host built before this field, whose `struct_size` ends before
// it, has. Unread where `window` is given: the window's size is then the mode.
uint16_t headless_mode_width;
// As `headless_mode_width`.
uint16_t headless_mode_height;
// Where `window` is NULL, each display's own first mode, in place of `headless_mode_width`
// x `headless_mode_height` for every display: an array of `display_count` sizes (one where
// it is 0), display i's at i, its `x` the width and `y` the height, each taken as
// `headless_mode_width` and `headless_mode_height` are (a 0 in either is 1920 x 1080). NULL
// is those two for every display, as a host built before this field, whose `struct_size`
// ends before it, has. Unread where `window` is given.
const RvgDisplayCoord *headless_modes;
} RvgGraphicsDeviceConfig;
#ifdef __cplusplus
@@ -685,8 +734,9 @@ const char *rvg_status_message(RvgStatus status);
// tables, before any table is the library's: a struct_size refusal runs no destroy, and a later
// refusal runs each, the windows' first, display 0's first. Refusals: RVG_ERR_INVALID_ARGUMENT,
// RVG_ERR_UNSUPPORTED, RVG_ERR_HOST_RESOURCES (the host refused the region's memory, a pipe or
// a thread, or has no GPU device the library can use: none, or one its driver refused). Calls
// back: never, but a refusal's destroys.
// a thread, or has no GPU device the library can use: none, or one its driver refused; or
// the GPU refused the pool's host memory, `pool_host_memory`). Calls back: never, but a
// refusal's destroys.
//
// # Safety
// `config` is NULL or a live config; `device` is NULL or writable.
@@ -699,7 +749,7 @@ RvgStatus rvg_graphics_device_create(const RvgGraphicsDeviceConfig *config,
// host's lock (QEMU's BQL) held or not: waits for nothing. Calls back: never.
//
// # Safety
// `device` is a live graphics device handle.
// `device` is NULL or a live graphics device handle.
RvgStatus rvg_graphics_device_pool_added(RvgGraphicsDevice *device, uint64_t physical_address);
// The host took the pool's piece at `physical_address` out of the guest's address space, and no
@@ -710,7 +760,7 @@ RvgStatus rvg_graphics_device_pool_added(RvgGraphicsDevice *device, uint64_t phy
// Calls back: never.
//
// # Safety
// `device` is a live graphics device handle.
// `device` is NULL or a live graphics device handle.
RvgStatus rvg_graphics_device_pool_removed(RvgGraphicsDevice *device, uint64_t physical_address);
// Asks for at least `length` more bytes of the guest's Shared pool now, ahead of the guest's own
@@ -721,7 +771,7 @@ RvgStatus rvg_graphics_device_pool_removed(RvgGraphicsDevice *device, uint64_t p
// for nothing. Calls back: never.
//
// # Safety
// `device` is a live graphics device handle.
// `device` is NULL or a live graphics device handle.
RvgStatus rvg_graphics_device_pool_grow(RvgGraphicsDevice *device, uint64_t length);
// The range of guest physical addresses the device's Shared pool took, of those its config gave
@@ -738,17 +788,20 @@ RvgStatus rvg_graphics_device_pool_grow(RvgGraphicsDevice *device, uint64_t leng
// `device` is a live graphics device handle; `length` is NULL or writable.
uint64_t rvg_graphics_device_pool_range(const RvgGraphicsDevice *device, uint64_t *length);
// Drops the host's reference; the last one closes the window, waiting for nothing, and ends the
// device's threads without waiting for them: the callbacks' destroy runs once both have ended,
// possibly after this returns, and the region stays mapped until then and until the window's
// GPU work has let it go. The release of the process's last graphics device then waits, at most
// 5 s, for its threads, its objects and their GPU work to let go of the GPU device, and lets go
// of every GPU device the library keeps for the process, so that none is live as the process
// exits: on NVIDIA's driver an exit with one live can end in SIGSEGV inside the driver's exit
// handler. A device callback still running holds the wait up, one that waits for a lock the host
// holds around this call for the whole 5 s; past them the library keeps the GPU device for the
// process, and logs a warning saying what held it. A device created after it runs on a new GPU
// device. The host unmaps BAR 2 from the guest first. Calls back: never.
// Drops the host's reference; the last one closes the device's pool first, waiting for a pool_add
// or pool_remove the pool's thread began, then closes the window, waiting for nothing, and ends
// the device's threads without waiting for them: the callbacks' destroy runs once both have ended,
// possibly after this returns, and the region stays mapped until then and until the window's GPU
// work has let it go. The release of the process's last graphics device then waits, at most 5 s,
// for its threads, its objects and their GPU work to let go of the GPU device, and lets go of
// every GPU device the library keeps for the process, so that none is live as the process exits:
// on NVIDIA's driver an exit with one live can end in SIGSEGV inside the driver's exit handler. A
// device callback still running holds the wait up, one that waits for a lock the host holds around
// this call for the whole 5 s; past them the library keeps the GPU device for the process, and
// logs a warning saying what held it. A device created after it runs on a new GPU device. The host
// unmaps BAR 2 from the guest first. Calls back: the window table's destroy, on the calling
// thread unless a window callback is running then, and the device table's where this call drops
// the last of its closures, as it does for a table with no functions; no other callback.
//
// # Safety
// `device` is NULL or a live graphics device handle, not used again.
@@ -779,10 +832,15 @@ bool rvg_quiesce_for_exit(uint64_t timeout_ms);
// Writes the library's degradation counts on stderr now, as a device's reset and the process's
// exit do: `reims-vgpu: degradation counts: <code> <n>, ...`, every kind counted since the process
// began, where any was and where the line changed since the library last wrote it, then the log's
// count of its repeated lines. For a host asked for them while its guest runs, so that a log read
// then has them: QEMU calls it for its device's `x-write-counts` property, which `reims-ctl
// report` sets. It takes no handle: the counts are the process's. It waits for no thread of the
// library's. Calls back: never.
// count of its repeated lines. Then two lines only the ask writes: the library's build,
// `reims-vgpu: build <commit> on metal2vulkan <commit>`, and, where the ask before this one was 2
// to 60 s earlier, the pacing line of the span between the two: presents a second, the GPU's time
// a frame and the CPU time of the guest's vCPU threads, of the library's by role and of the rest
// of the process (docs/conventions.md). For a host asked for them while its guest runs, so that a
// log read then has them: QEMU calls it for its device's `x-write-counts` property, which
// `reims-ctl report` sets twice, 10 s apart. It takes no handle: the counts are the process's. It
// reads each of the process's threads' CPU time, and waits for no thread of the library's. Calls
// back: never.
void rvg_write_counts(void);
// The device's region: its first byte, page-aligned, and, through `size` where it is not NULL,
@@ -805,7 +863,8 @@ uint32_t rvg_graphics_device_mmio_read(RvgGraphicsDevice *device, uint64_t offse
// A 32-bit write of BAR 0 at `offset`, below RVG_GRAPHICS_MSIX_OFFSET: STATUS, and DOORBELL
// where the host's ioeventfd did not take the write; other offsets are ignored. A write of 0 to
// STATUS resets the device, and waits for the command the device is taking, which waits for
// nothing of the host's.
// nothing of the host's, and then for the GPU work committed before it, as
// rvg_graphics_device_reset does.
//
// A write to RVG_GRAPHICS_REG_DOORBELL of a command queue's ring (any value but
// RVG_GRAPHICS_DOORBELL_CONTROL) wakes the queue's thread, and may answer the queue's next
@@ -822,7 +881,10 @@ uint32_t rvg_graphics_device_mmio_read(RvgGraphicsDevice *device, uint64_t offse
// already and the control thread sleeps with every earlier message carried out (each lock
// tried, nothing allocated); else the control thread takes it. What the guest sees is the same
// either way but for when the event comes. On any thread, the vCPU's included. Calls back:
// raise_interrupt, as above.
// raise_interrupt, as above; and on the calling thread route_doorbell and route_doorbell_page,
// dropping the routes of the queues a STATUS write of 0 ends, and route_doorbell_page,
// dropping the routes on a doorbell page a DOORBELL_PAGE_BIND write binds to another
// context (docs/api.md section 5).
//
// # Safety
// `device` is a live graphics device handle.
@@ -854,7 +916,7 @@ void rvg_graphics_device_doorbell_write(RvgGraphicsDevice *device, uint64_t offs
// Calls back: never.
//
// # Safety
// `device` is a live graphics device handle.
// `device` is NULL or a live graphics device handle.
RvgStatus rvg_graphics_device_set_doorbell(RvgGraphicsDevice *device, int32_t fd);
#endif
@@ -868,16 +930,31 @@ RvgStatus rvg_graphics_device_set_doorbell(RvgGraphicsDevice *device, int32_t fd
// already. Calls back: never.
//
// # Safety
// `device` is a live graphics device handle.
// `device` is NULL or a live graphics device handle.
RvgStatus rvg_graphics_device_set_doorbell(RvgGraphicsDevice *device, void *event);
#endif
// The guest's bus reset: as a write of 0 to STATUS, the device is as one just made. It takes no
// command until the guest writes 1, its rings are as new, the display keeps its scanout but has
// no cursor image or VBLANK, its panel is on, and the device drops every object the guest's
// processes made, on its control thread before it takes the guest's next command. Waits for the
// command the device is taking, and for a take of a queue's ring or a post onto one under way.
// Calls back: never.
// command until the guest writes 1, its rings are as new, the display keeps its scanout but has no
// cursor image or VBLANK, its panel is on, and the device drops every object the guest's processes
// made, on its control thread before it takes the guest's next command. Waits for the command the
// device is taking, and for a take of a queue's ring or a post onto one under way. Then it waits,
// within 30 s, for each walk of a queue's command buffer begun before it to end, its work
// committed, and until every command buffer committed to the host's GPU before it has completed
// and run its completed handlers, so none of the guest's work from before the reset writes the
// guest's memory after this returns, as a GPU's reset stops its DMA: while that work completes,
// each command buffer within 30 s of the one before, and 10 min at most in all. Of the device's
// threads it waits only for those walks, which call back only raise_interrupt, and within 30 s
// for the locks of the library's it takes. Waiting 2 s on for the GPU, it writes a line on stderr
// that it waits, and one once it is done (docs/api.md, "The reset's lines"). A walk still running
// after 30 s, a GPU that completes none of that work for 30 s or runs it past 10 min, or such a
// lock still held after 30 s, is one no driver recovered, and the process ends there. Called
// inside raise_interrupt, it is the one reset that waits for none of that work,
// which may then write the guest's memory after it returns: the raise's thread may hold those
// locks, and the work it raises for began before the reset and ends only once this returns. QEMU's
// raise_interrupt never resets the device. Calls back: route_doorbell and route_doorbell_page, on
// the calling thread, dropping the routes of the queues it ends (docs/api.md section 5); no other
// callback.
//
// # Safety
// `device` is a live graphics device handle.
@@ -899,8 +976,8 @@ void rvg_graphics_device_reset(RvgGraphicsDevice *device);
// and the mode is only asked. One read runs at a time. On any thread. Calls back: never.
//
// # Safety
// `device` is a live graphics device handle; `dst` is NULL or holds `dst_length` writable bytes;
// `width` and `height` are each NULL or writable.
// `device` is NULL or a live graphics device handle; `dst` is NULL or holds `dst_length`
// writable bytes; `width` and `height` are each NULL or writable.
RvgStatus rvg_graphics_device_read_display(RvgGraphicsDevice *device,
uint8_t *dst,
size_t dst_length,
@@ -923,8 +1000,8 @@ RvgDisplayCoord rvg_graphics_device_cursor_position(const RvgGraphicsDevice *dev
// Reads of one display run one at a time. On any thread. Calls back: never.
//
// # Safety
// `device` is a live graphics device handle; `dst` is NULL or holds `dst_length` writable bytes;
// `width` and `height` are each NULL or writable.
// `device` is NULL or a live graphics device handle; `dst` is NULL or holds `dst_length`
// writable bytes; `width` and `height` are each NULL or writable.
RvgStatus rvg_graphics_device_read_display_at(RvgGraphicsDevice *device,
uint32_t display,
uint8_t *dst,
+124
View File
@@ -0,0 +1,124 @@
//! The library's build stamp, which the crate's build script reads at each build (`build.rs`) and
//! the library's first call hands on (`crate::ffi::export`, `reims_vgpu_vulkan::stamp`): the
//! commit the tree is at, `git rev-parse HEAD`, with `-dirty` where a tracked file of the tree
//! differs from it or git cannot say, and `unknown` for a build outside a checkout (no git, or no
//! commit), which never fails the build. Left aside as the tree is compared: submodules,
//! `crates/reims-ctl` (a workspace of its own, linking nothing of the library), and `Cargo.lock`,
//! which is committed without metal2vulkan's git `source` lines and which every build writes them
//! back into. A diagnostic: nothing decides on it.
use std::path::{Path, PathBuf};
use std::process::Command;
/// The stamp of a tree whose `git rev-parse HEAD` answered `head` and whose status
/// ([`STATUS`]) answered `status`, each `None` where git failed (the module doc).
pub fn stamp(head: Option<&str>, status: Option<&str>) -> String {
let Some(head) = head.map(str::trim).filter(|h| !h.is_empty()) else {
return "unknown".to_owned();
};
match status {
Some(status) if status.trim().is_empty() => head.to_owned(),
_ => format!("{head}-dirty"),
}
}
/// The status the stamp reads: the tracked files that differ from HEAD, but those the module doc
/// leaves aside.
pub const STATUS: [&str; 8] = [
"status",
"--porcelain",
"--untracked-files=no",
"--ignore-submodules",
"--",
".",
":(exclude)crates/reims-ctl",
":(exclude)Cargo.lock",
];
/// What `git -C <dir> <args>` writes on its stdout, where it runs and succeeds.
pub fn git(dir: &Path, args: &[&str]) -> Option<String> {
let out = Command::new("git")
.arg("-C")
.arg(dir)
.args(args)
.output()
.ok()?;
out.status
.success()
.then(|| String::from_utf8_lossy(&out.stdout).into_owned())
}
/// The stamp of the tree at `root`, read from git.
pub fn read(root: &Path) -> String {
let head = git(root, &["rev-parse", "HEAD"]);
let status = head.as_ref().and_then(|_| git(root, &STATUS));
stamp(head.as_deref(), status.as_deref())
}
/// The files of the checkout at `root` whose change moves HEAD or the index: its HEAD and index,
/// the branch's ref HEAD names, and the packed refs, those that exist (Cargo runs a build script
/// again at every build for a path that does not).
pub fn git_files(root: &Path) -> Vec<PathBuf> {
let dir = |args: &[&str]| git(root, args).map(|d| PathBuf::from(d.trim()));
let mut files = Vec::new();
if let Some(own) = dir(&["rev-parse", "--absolute-git-dir"]) {
files.push(own.join("HEAD"));
files.push(own.join("index"));
}
if let Some(common) = dir(&["rev-parse", "--path-format=absolute", "--git-common-dir"]) {
if let Some(branch) = git(root, &["symbolic-ref", "-q", "HEAD"]) {
files.push(common.join(branch.trim()));
}
files.push(common.join("packed-refs"));
}
files.retain(|f| f.exists());
files
}
#[cfg(test)]
mod tests {
use super::*;
const HEAD: &str = "41f0bba449c1e1f1b2e5d3c4a5b6c7d8e9f00112";
/// A clean tree's stamp is its commit.
#[test]
fn a_clean_tree_is_stamped_with_its_commit() {
assert_eq!(stamp(Some(&format!("{HEAD}\n")), Some("")), HEAD);
}
/// A tree with a tracked file changed, or whose status git could not give, is marked dirty.
#[test]
fn a_changed_tree_is_stamped_dirty() {
let dirty = format!("{HEAD}-dirty");
assert_eq!(
stamp(Some(HEAD), Some(" M crates/reims-vgpu/src/graphics.rs\n")),
dirty
);
assert_eq!(stamp(Some(HEAD), None), dirty);
}
/// A build outside a checkout, where git answers no commit, is stamped unknown.
#[test]
fn a_build_outside_a_checkout_is_unknown() {
assert_eq!(stamp(None, None), "unknown");
assert_eq!(stamp(Some("\n"), Some("")), "unknown");
let nowhere = std::env::temp_dir().join("reims-vgpu-c-no-checkout-here");
assert_eq!(git(&nowhere, &["rev-parse", "HEAD"]), None);
assert_eq!(read(&nowhere), "unknown");
assert!(git_files(&nowhere).is_empty());
}
/// The build stamped the library with this checkout's commit, the one the tests run at.
#[test]
fn the_library_carries_its_build_s_stamp() {
let built = env!("RVG_BUILD_STAMP");
// Read at run time, so the test names no worktree (docs/development.md).
let manifest = std::env::var_os("CARGO_MANIFEST_DIR").unwrap();
let root = Path::new(&manifest).join("../..");
match git(&root, &["rev-parse", "HEAD"]) {
Some(head) => assert!(built.starts_with(head.trim()), "{built} {head}"),
None => assert_eq!(built, "unknown"),
}
}
}
+5 -2
View File
@@ -2,8 +2,9 @@
//! and [`host_call`] around every call of a host function.
//!
//! **Into the library.** Every `rvg_` function is `extern "C"`: nothing unwinds out of it into
//! the host. Its body runs inside [`export`], which first installs the library's panic hook and
//! then marks the thread as the library's for the call, so a panic anywhere under an export ends
//! the host. Its body runs inside [`export`], which first installs the library's panic hook, hands
//! on the library's build stamp (`build.rs`, `reims_vgpu_vulkan::stamp`), and then marks the
//! thread as the library's for the call, so a panic anywhere under an export ends
//! the process in the hook, before any frame unwinds and before any drop runs (architecture 6.5).
//! The `extern "C"` frame is only the backstop: an unwind that reached it would end the process
//! too, but only after the frames in between had run their drops, a table's `destroy(ctx)` among
@@ -29,6 +30,8 @@ pub(crate) fn export<R>(body: impl FnOnce() -> R) -> R {
if !std::thread::panicking() {
reims_vgpu::singleton::install_panic_hook();
}
// The commit the library was built from, which its log lines name (`build.rs`).
reims_vgpu_vulkan::stamp::set_commit(env!("RVG_BUILD_STAMP"));
let _ours = enter_ours();
body()
}
+4
View File
@@ -126,6 +126,10 @@ fn a_panic_in_a_callback_of_the_first_export_ends_in_the_hook() {
display_windows: std::ptr::null(),
pool_physical_address: 0,
pool_physical_length: 0,
pool_host_memory: 0,
headless_mode_width: 0,
headless_mode_height: 0,
headless_modes: std::ptr::null(),
};
// SAFETY: a live config; a NULL out-pointer, which the create refuses.
let _ =
+177 -102
View File
@@ -124,21 +124,36 @@ const _: () = {
/// (`reims-vgpu.graphics-queue-<id>`) or one of its lane's threads, which walk and commit its
/// command buffers (`reims-vgpu.graphics-lane-<id>`), a pipeline compile's thread
/// (`reims-vgpu.graphics-compile-<n>`), a thread that makes IOSurfaces' and pages blocks' views
/// (`reims-vgpu.graphics-surfaces-<i>`), a thread that makes indirect command buffers
/// (`reims-vgpu.graphics-surfaces-<i>`, and `reims-vgpu.graphics-views-<i>` for a pages block's
/// view made after its answer), a thread that makes indirect command buffers
/// (`reims-vgpu.icb-create-<i>`), a thread that lets go of a closed process's objects and answers
/// its close (`reims-vgpu.graphics-closes-<i>`), a thread that moves a staged copy of a surface's
/// device cache into its pages and answers what waited for it
/// (`reims-vgpu.graphics-into-pages-<i>`), a video session's picture landing thread, which posts
/// a decode's completion as the decode is done (`reims-vgpu.graphics-video-land`), or the
/// platform's thread that runs a command buffer's scheduled or completed handler; or the host's
/// own, inside rvg_graphics_device_mmio_write_taking.
/// (`reims-vgpu.graphics-into-pages-<i>`), the thread that paces releases' copies of their
/// surfaces' device caches into their pages, which answers a BLOCK_RELEASE as its turn comes
/// (`reims-vgpu.graphics-release-pace`), the thread that tries again the EVENT_SIGNALLED to a
/// shared event's other holders that their rings had no room for
/// (`reims-vgpu.graphics-shared-events`), a take worker of the guest's Shared pool or of its
/// Private blocks, which answers a POOL_TAKE or a PRIVATE_TAKE
/// (`reims-vgpu.graphics-pool-take`, `reims-vgpu.graphics-private-take`), the windows' UI thread,
/// which tells the guest of the host's pointer and scrolling (POINTER_OVER, POINTER_MOTION and
/// SCROLL; on macOS the process's main thread, on Linux and Windows `reims-vgpu.ui`), a video
/// session's picture landing thread, which posts a decode's completion as the decode is done
/// (`reims-vgpu.graphics-video-land`), or the platform's thread that runs a command buffer's
/// scheduled or completed handler; or the host's own, inside
/// rvg_graphics_device_mmio_write_taking or rvg_graphics_device_doorbell_write.
/// Never inside another call of the host's into the library. The library may hold locks of its
/// own around it (docs/api.md section 5 names them), but none that a function it may call waits
/// for, directly or through a thread of the library's, so it may call them at once. It may wait
/// for a lock the host holds while it calls the device (QEMU's BQL), but not for one the host
/// holds while it calls rvg_graphics_device_mmio_write_taking. May call: rvg_status_message and
/// the rvg_graphics_device_* functions, except the release of its own device. Without it the
/// guest gets no interrupt.
/// holds while it calls rvg_graphics_device_mmio_write_taking or
/// rvg_graphics_device_doorbell_write, nor, on any thread, for one the host holds around
/// rvg_graphics_device_reset or a write of 0 to STATUS: those wait for the platform's completed
/// handlers while the GPU work before them completes, and at most 30 s for locks of the library's
/// it may hold around this (docs/api.md section 5). May call: rvg_status_message and the
/// rvg_graphics_device_* functions, except the release of its own device; a reset called here waits
/// for none of the GPU work committed before it (rvg_graphics_device_reset). Without it the guest
/// gets no interrupt.
pub type RvgGraphicsRaiseFn = Option<unsafe extern "C-unwind" fn(ctx: *mut c_void, vector: u32)>;
/// `route_doorbell(ctx, route, ring_id, bell)`: with `bell` 0 or more, route a command queue's
@@ -215,7 +230,9 @@ pub type RvgGraphicsRouteDoorbellPageFn = Option<
/// Thread: the device's pool thread (`reims-vgpu.graphics-pool`), never inside a call of the
/// host's, with no lock of the library's held. It must not wait for a lock the host holds while
/// it calls the device (QEMU's BQL): QEMU queues the add for its main loop. One piece at a time,
/// in the order the device places them, each before its pool_remove. May call: nothing of the
/// in the order the device places them, each before its pool_remove. Not called once
/// rvg_graphics_device_release has closed the pool, at its start; a call the pool thread began
/// before that may still be running, and the release waits for it. May call: nothing of the
/// library's. Needed with a pool.
pub type RvgGraphicsPoolAddFn = Option<
unsafe extern "C-unwind" fn(
@@ -237,8 +254,9 @@ pub type RvgGraphicsPoolAddFn = Option<
/// block back, never inside a call of the host's, with no lock of the library's held. It must not
/// wait for a lock the host holds while it calls the device (QEMU queues the remove for its main
/// loop). Once a piece, after its pool_add. Not called once rvg_graphics_device_release has
/// begun: the host removes every piece it added before it releases the device. May call: nothing
/// of the library's. Needed with a pool.
/// closed the pool, at its start; a call the pool thread began before that may still be running,
/// and the release waits for it. The host removes every piece it added before it releases the
/// device. May call: nothing of the library's. Needed with a pool.
pub type RvgGraphicsPoolRemoveFn =
Option<unsafe extern "C-unwind" fn(ctx: *mut c_void, physical_address: u64, length: u64)>;
@@ -325,13 +343,14 @@ pub struct RvgGraphicsDeviceConfig {
pub struct_size: u32,
/// NULL is a table with every callback absent.
pub callbacks: *const RvgGraphicsCallbacks,
/// NULL is no window: the display offers 1920 x 1080 at 60 Hz and shows nothing. Otherwise
/// the library opens a window for the display, with its input as the window's callbacks,
/// sized for its mode (1920 x 1080 where it has none). The window keeps its size: the
/// display offers the guest one mode, the window's size in pixels at the refresh rate of the
/// host screen it opens on, and tells the guest when the person resizes it. The guest's
/// scanout is blitted out of the region into the window's drawables on the GPU at each of the
/// display's refreshes, at the screen's rate, while the display shows no presented surface.
/// NULL is no window: the display offers its headless mode (`headless_modes`, else
/// `headless_mode_width` x `headless_mode_height`) at 60 Hz and shows nothing. Otherwise the
/// library opens a window for the display, with its input as the window's callbacks, sized
/// for its mode (1920 x 1080 where it has none). The window keeps its size: the display
/// offers the guest one mode, the window's size in pixels at the refresh rate of the host
/// screen it opens on, and tells the guest when the person resizes it. The guest's scanout is
/// blitted out of the region into the window's drawables on the GPU at each of the display's
/// refreshes, at the screen's rate, while the display shows no presented surface.
pub window: *const RvgWindowConfig,
/// The guest's RAM, or NULL. With it, where the host's page is the guest's 4 KiB, or 16 KiB
/// for a guest that lays its pages out in 16 KiB (`RGFX_FEATURE_PAGES_16K`), the GPU uses an
@@ -341,7 +360,8 @@ pub struct RvgGraphicsDeviceConfig {
/// down to 16 KiB, or the host GPU's answer where that is less; with no map, and on a GPU of
/// its own memory, the host GPU's. The map's pages stay the guest's RAM, mapped, until the
/// process exits (`RvgMemoryRange`): a host that discards guest RAM (a balloon, virtio-mem,
/// hot-unplug) passes NULL. Its ranges may not overlap.
/// hot-unplug) passes NULL. Its ranges may not overlap: a map whose ranges overlap, or one
/// of whose ranges runs past the address space, is refused (RVG_ERR_INVALID_ARGUMENT).
pub memory_map: *const RvgMemoryMap,
/// With `memory_map`: the files behind its ranges, NULL for none, one entry per range, each
/// duplicated during the create. Refused (RVG_ERR_INVALID_ARGUMENT), in this order: files
@@ -405,6 +425,34 @@ pub struct RvgGraphicsDeviceConfig {
pub pool_physical_address: u64,
/// The range's length in bytes, the most the pool may take: 0 for none.
pub pool_physical_length: u64,
/// A fact of the host's, which it finds by asking its hypervisor and sets from nothing else:
/// 1 where the hypervisor takes no cacheable mapping of the GPU's own memory as guest memory,
/// as QEMU finds under Linux's KVM on arm64 where the VM does not answer
/// KVM_CAP_ARM_CACHEABLE_PFNMAP_SUPPORTED (KVM then refuses a cacheable VM_PFNMAP mapping as a
/// memory slot); 0 where it takes one, every other host, and a host built before this field.
/// At 1 each of the pool's blocks is ordinary memory of the library's own (on Linux a memfd
/// it maps shared) that the GPU imports as a dma-buf, which pool_add then maps; at 0 the
/// GPU's own memory. Nothing without a pool. Refused (RVG_ERR_INVALID_ARGUMENT): any other
/// value, and 1 on a platform that makes no such blocks (macOS and Windows); refused
/// (RVG_ERR_HOST_RESOURCES): 1 where the GPU refuses host memory as a dma-buf (NVIDIA's
/// driver, or a Linux host without udmabuf), which the create finds by importing one block.
pub pool_host_memory: u32,
/// Where `window` is NULL, the mode each display offers the guest first, in pixels, as a
/// window config's `mode_width` gives the mode its window opens for: its width rounded down
/// to a multiple of 16 and its height to even, at 60 Hz (no host screen shows the display,
/// so none sets its rate), sized to each display's scanout room on a device of several. 0 in
/// either is 1920 x 1080, as a host built before this field, whose `struct_size` ends before
/// it, has. Unread where `window` is given: the window's size is then the mode.
pub headless_mode_width: u16,
/// As `headless_mode_width`.
pub headless_mode_height: u16,
/// Where `window` is NULL, each display's own first mode, in place of `headless_mode_width`
/// x `headless_mode_height` for every display: an array of `display_count` sizes (one where
/// it is 0), display i's at i, its `x` the width and `y` the height, each taken as
/// `headless_mode_width` and `headless_mode_height` are (a 0 in either is 1920 x 1080). NULL
/// is those two for every display, as a host built before this field, whose `struct_size`
/// ends before it, has. Unread where `window` is given.
pub headless_modes: *const RvgDisplayCoord,
}
// SAFETY: repr(C), a u32 first; pointers and u32s.
@@ -443,8 +491,9 @@ unsafe fn live<'a>(device: *const RvgGraphicsDevice, call: &'static str) -> &'a
/// tables, before any table is the library's: a struct_size refusal runs no destroy, and a later
/// refusal runs each, the windows' first, display 0's first. Refusals: RVG_ERR_INVALID_ARGUMENT,
/// RVG_ERR_UNSUPPORTED, RVG_ERR_HOST_RESOURCES (the host refused the region's memory, a pipe or
/// a thread, or has no GPU device the library can use: none, or one its driver refused). Calls
/// back: never, but a refusal's destroys.
/// a thread, or has no GPU device the library can use: none, or one its driver refused; or
/// the GPU refused the pool's host memory, `pool_host_memory`). Calls back: never, but a
/// refusal's destroys.
///
/// # Safety
/// `config` is NULL or a live config; `device` is NULL or writable.
@@ -553,6 +602,17 @@ unsafe fn create(
1 => true,
_ => return refuse(RVG_ERR_INVALID_ARGUMENT),
};
let pool_host_memory = match c.pool_host_memory {
0 => false,
1 => true,
_ => return refuse(RVG_ERR_INVALID_ARGUMENT),
};
// Each display's own headless mode, one for each of the `count` displays checked above.
let headless_modes = (window.is_none() && !c.headless_modes.is_null()).then(|| {
// SAFETY: the config's contract: `display_count` readable sizes, one where it is 0.
let modes = unsafe { std::slice::from_raw_parts(c.headless_modes, count as usize) };
modes.iter().map(|m| (m.x, m.y)).collect()
});
// SAFETY: the config's contract: NULL or a live map, and NULL or its files.
let memory_map = match unsafe { memory_map(c.memory_map, c.memory_files) } {
Ok(m) => m,
@@ -626,6 +686,9 @@ unsafe fn create(
guest_arch,
doorbell_pages,
pool,
pool_host_memory,
headless_mode: Some((c.headless_mode_width, c.headless_mode_height)),
headless_modes,
};
match GraphicsDevice::with_platform(<Plat as reims_vgpu::ApiPlatform>::process(), config) {
Ok(d) => {
@@ -673,7 +736,7 @@ fn pool_remove(table: &Arc<Table>, f: RvgGraphicsPoolRemoveFn) -> Option<PoolRem
/// host's lock (QEMU's BQL) held or not: waits for nothing. Calls back: never.
///
/// # Safety
/// `device` is a live graphics device handle.
/// `device` is NULL or a live graphics device handle.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rvg_graphics_device_pool_added(
device: *mut RvgGraphicsDevice,
@@ -681,11 +744,7 @@ pub unsafe extern "C" fn rvg_graphics_device_pool_added(
) -> RvgStatus {
ffi::export(|| {
// SAFETY: the caller's contract.
unsafe {
pool_call(device, "rvg_graphics_device_pool_added", |d| {
d.pool_added(physical_address)
})
}
unsafe { pool_call(device, |d| d.pool_added(physical_address)) }
})
}
@@ -697,7 +756,7 @@ pub unsafe extern "C" fn rvg_graphics_device_pool_added(
/// Calls back: never.
///
/// # Safety
/// `device` is a live graphics device handle.
/// `device` is NULL or a live graphics device handle.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rvg_graphics_device_pool_removed(
device: *mut RvgGraphicsDevice,
@@ -705,11 +764,7 @@ pub unsafe extern "C" fn rvg_graphics_device_pool_removed(
) -> RvgStatus {
ffi::export(|| {
// SAFETY: the caller's contract.
unsafe {
pool_call(device, "rvg_graphics_device_pool_removed", |d| {
d.pool_removed(physical_address)
})
}
unsafe { pool_call(device, |d| d.pool_removed(physical_address)) }
})
}
@@ -721,7 +776,7 @@ pub unsafe extern "C" fn rvg_graphics_device_pool_removed(
/// for nothing. Calls back: never.
///
/// # Safety
/// `device` is a live graphics device handle.
/// `device` is NULL or a live graphics device handle.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rvg_graphics_device_pool_grow(
device: *mut RvgGraphicsDevice,
@@ -729,11 +784,7 @@ pub unsafe extern "C" fn rvg_graphics_device_pool_grow(
) -> RvgStatus {
ffi::export(|| {
// SAFETY: the caller's contract.
unsafe {
pool_call(device, "rvg_graphics_device_pool_grow", |d| {
d.pool_grow(length)
})
}
unsafe { pool_call(device, |d| d.pool_grow(length)) }
})
}
@@ -765,34 +816,39 @@ pub unsafe extern "C" fn rvg_graphics_device_pool_range(
}
/// The body of the pool's functions inside their `ffi::export`: `call` on the device, its answer
/// as a status.
/// as a status; RVG_ERR_INVALID_ARGUMENT for a NULL `device`, as for every function that answers
/// a status.
///
/// # Safety
/// `device` is a live graphics device handle.
/// `device` is NULL or a live graphics device handle.
unsafe fn pool_call(
device: *mut RvgGraphicsDevice,
name: &'static str,
call: impl FnOnce(&GraphicsDevice<Plat>) -> Result<(), reims_vgpu::Error>,
) -> RvgStatus {
// SAFETY: the caller's contract.
let d = unsafe { live(device, name) };
let Some(d) = (unsafe { handle::get(device) }) else {
return RVG_ERR_INVALID_ARGUMENT;
};
match call(&d.device) {
Ok(()) => RVG_OK,
Err(e) => status(e),
}
}
/// Drops the host's reference; the last one closes the window, waiting for nothing, and ends the
/// device's threads without waiting for them: the callbacks' destroy runs once both have ended,
/// possibly after this returns, and the region stays mapped until then and until the window's
/// GPU work has let it go. The release of the process's last graphics device then waits, at most
/// 5 s, for its threads, its objects and their GPU work to let go of the GPU device, and lets go
/// of every GPU device the library keeps for the process, so that none is live as the process
/// exits: on NVIDIA's driver an exit with one live can end in SIGSEGV inside the driver's exit
/// handler. A device callback still running holds the wait up, one that waits for a lock the host
/// holds around this call for the whole 5 s; past them the library keeps the GPU device for the
/// process, and logs a warning saying what held it. A device created after it runs on a new GPU
/// device. The host unmaps BAR 2 from the guest first. Calls back: never.
/// Drops the host's reference; the last one closes the device's pool first, waiting for a pool_add
/// or pool_remove the pool's thread began, then closes the window, waiting for nothing, and ends
/// the device's threads without waiting for them: the callbacks' destroy runs once both have ended,
/// possibly after this returns, and the region stays mapped until then and until the window's GPU
/// work has let it go. The release of the process's last graphics device then waits, at most 5 s,
/// for its threads, its objects and their GPU work to let go of the GPU device, and lets go of
/// every GPU device the library keeps for the process, so that none is live as the process exits:
/// on NVIDIA's driver an exit with one live can end in SIGSEGV inside the driver's exit handler. A
/// device callback still running holds the wait up, one that waits for a lock the host holds around
/// this call for the whole 5 s; past them the library keeps the GPU device for the process, and
/// logs a warning saying what held it. A device created after it runs on a new GPU device. The host
/// unmaps BAR 2 from the guest first. Calls back: the window table's destroy, on the calling
/// thread unless a window callback is running then, and the device table's where this call drops
/// the last of its closures, as it does for a table with no functions; no other callback.
///
/// # Safety
/// `device` is NULL or a live graphics device handle, not used again.
@@ -802,8 +858,11 @@ pub unsafe extern "C" fn rvg_graphics_device_release(device: *mut RvgGraphicsDev
if device.is_null() {
return;
}
// A block's release that a display hold let go of here answers is posted, and raised
// for, by the device's control thread: the device's release calls nothing of the host's
// back.
// SAFETY: the caller's contract.
unsafe { handle::release(device) };
reims_vgpu_graphics::raise_elsewhere(|| unsafe { handle::release(device) });
// Where that ended the process's last device, the GPU devices go: the Rust API decides
// and logs (`GraphicsDevice::let_go_of_gpu`).
let _ = GraphicsDevice::<Plat>::let_go_of_gpu(reims_vgpu::LET_GO_BOUND);
@@ -840,10 +899,15 @@ pub extern "C" fn rvg_quiesce_for_exit(timeout_ms: u64) -> bool {
/// Writes the library's degradation counts on stderr now, as a device's reset and the process's
/// exit do: `reims-vgpu: degradation counts: <code> <n>, ...`, every kind counted since the process
/// began, where any was and where the line changed since the library last wrote it, then the log's
/// count of its repeated lines. For a host asked for them while its guest runs, so that a log read
/// then has them: QEMU calls it for its device's `x-write-counts` property, which `reims-ctl
/// report` sets. It takes no handle: the counts are the process's. It waits for no thread of the
/// library's. Calls back: never.
/// count of its repeated lines. Then two lines only the ask writes: the library's build,
/// `reims-vgpu: build <commit> on metal2vulkan <commit>`, and, where the ask before this one was 2
/// to 60 s earlier, the pacing line of the span between the two: presents a second, the GPU's time
/// a frame and the CPU time of the guest's vCPU threads, of the library's by role and of the rest
/// of the process (docs/conventions.md). For a host asked for them while its guest runs, so that a
/// log read then has them: QEMU calls it for its device's `x-write-counts` property, which
/// `reims-ctl report` sets twice, 10 s apart. It takes no handle: the counts are the process's. It
/// reads each of the process's threads' CPU time, and waits for no thread of the library's. Calls
/// back: never.
#[unsafe(no_mangle)]
pub extern "C" fn rvg_write_counts() {
ffi::export(|| {
@@ -894,7 +958,8 @@ pub unsafe extern "C" fn rvg_graphics_device_mmio_read(
/// A 32-bit write of BAR 0 at `offset`, below RVG_GRAPHICS_MSIX_OFFSET: STATUS, and DOORBELL
/// where the host's ioeventfd did not take the write; other offsets are ignored. A write of 0 to
/// STATUS resets the device, and waits for the command the device is taking, which waits for
/// nothing of the host's.
/// nothing of the host's, and then for the GPU work committed before it, as
/// rvg_graphics_device_reset does.
///
/// A write to RVG_GRAPHICS_REG_DOORBELL of a command queue's ring (any value but
/// RVG_GRAPHICS_DOORBELL_CONTROL) wakes the queue's thread, and may answer the queue's next
@@ -911,7 +976,10 @@ pub unsafe extern "C" fn rvg_graphics_device_mmio_read(
/// already and the control thread sleeps with every earlier message carried out (each lock
/// tried, nothing allocated); else the control thread takes it. What the guest sees is the same
/// either way but for when the event comes. On any thread, the vCPU's included. Calls back:
/// raise_interrupt, as above.
/// raise_interrupt, as above; and on the calling thread route_doorbell and route_doorbell_page,
/// dropping the routes of the queues a STATUS write of 0 ends, and route_doorbell_page,
/// dropping the routes on a doorbell page a DOORBELL_PAGE_BIND write binds to another
/// context (docs/api.md section 5).
///
/// # Safety
/// `device` is a live graphics device handle.
@@ -964,7 +1032,7 @@ pub unsafe extern "C" fn rvg_graphics_device_doorbell_write(
/// Calls back: never.
///
/// # Safety
/// `device` is a live graphics device handle.
/// `device` is NULL or a live graphics device handle.
#[cfg(not(windows))]
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rvg_graphics_device_set_doorbell(
@@ -986,7 +1054,7 @@ pub unsafe extern "C" fn rvg_graphics_device_set_doorbell(
/// already. Calls back: never.
///
/// # Safety
/// `device` is a live graphics device handle.
/// `device` is NULL or a live graphics device handle.
#[cfg(windows)]
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rvg_graphics_device_set_doorbell(
@@ -1000,13 +1068,16 @@ pub unsafe extern "C" fn rvg_graphics_device_set_doorbell(
}
/// The body of `rvg_graphics_device_set_doorbell` on each OS, inside its `ffi::export`:
/// `doorbell` is its `fd`, or on Windows its `event`.
/// `doorbell` is its `fd`, or on Windows its `event`; RVG_ERR_INVALID_ARGUMENT for a NULL
/// `device`, as for every function that answers a status.
///
/// # Safety
/// `device` is a live graphics device handle.
/// `device` is NULL or a live graphics device handle.
unsafe fn set_doorbell(device: *mut RvgGraphicsDevice, doorbell: RawDoorbell) -> RvgStatus {
// SAFETY: the caller's contract.
let d = unsafe { live(device, "rvg_graphics_device_set_doorbell") };
let Some(d) = (unsafe { handle::get(device) }) else {
return RVG_ERR_INVALID_ARGUMENT;
};
if d.device.set_doorbell(doorbell) {
RVG_OK
} else {
@@ -1015,11 +1086,26 @@ unsafe fn set_doorbell(device: *mut RvgGraphicsDevice, doorbell: RawDoorbell) ->
}
/// The guest's bus reset: as a write of 0 to STATUS, the device is as one just made. It takes no
/// command until the guest writes 1, its rings are as new, the display keeps its scanout but has
/// no cursor image or VBLANK, its panel is on, and the device drops every object the guest's
/// processes made, on its control thread before it takes the guest's next command. Waits for the
/// command the device is taking, and for a take of a queue's ring or a post onto one under way.
/// Calls back: never.
/// command until the guest writes 1, its rings are as new, the display keeps its scanout but has no
/// cursor image or VBLANK, its panel is on, and the device drops every object the guest's processes
/// made, on its control thread before it takes the guest's next command. Waits for the command the
/// device is taking, and for a take of a queue's ring or a post onto one under way. Then it waits,
/// within 30 s, for each walk of a queue's command buffer begun before it to end, its work
/// committed, and until every command buffer committed to the host's GPU before it has completed
/// and run its completed handlers, so none of the guest's work from before the reset writes the
/// guest's memory after this returns, as a GPU's reset stops its DMA: while that work completes,
/// each command buffer within 30 s of the one before, and 10 min at most in all. Of the device's
/// threads it waits only for those walks, which call back only raise_interrupt, and within 30 s
/// for the locks of the library's it takes. Waiting 2 s on for the GPU, it writes a line on stderr
/// that it waits, and one once it is done (docs/api.md, "The reset's lines"). A walk still running
/// after 30 s, a GPU that completes none of that work for 30 s or runs it past 10 min, or such a
/// lock still held after 30 s, is one no driver recovered, and the process ends there. Called
/// inside raise_interrupt, it is the one reset that waits for none of that work,
/// which may then write the guest's memory after it returns: the raise's thread may hold those
/// locks, and the work it raises for began before the reset and ends only once this returns. QEMU's
/// raise_interrupt never resets the device. Calls back: route_doorbell and route_doorbell_page, on
/// the calling thread, dropping the routes of the queues it ends (docs/api.md section 5); no other
/// callback.
///
/// # Safety
/// `device` is a live graphics device handle.
@@ -1049,8 +1135,8 @@ pub unsafe extern "C" fn rvg_graphics_device_reset(device: *mut RvgGraphicsDevic
/// and the mode is only asked. One read runs at a time. On any thread. Calls back: never.
///
/// # Safety
/// `device` is a live graphics device handle; `dst` is NULL or holds `dst_length` writable bytes;
/// `width` and `height` are each NULL or writable.
/// `device` is NULL or a live graphics device handle; `dst` is NULL or holds `dst_length`
/// writable bytes; `width` and `height` are each NULL or writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rvg_graphics_device_read_display(
device: *mut RvgGraphicsDevice,
@@ -1061,15 +1147,7 @@ pub unsafe extern "C" fn rvg_graphics_device_read_display(
) -> RvgStatus {
ffi::export(|| {
// SAFETY: the caller's contract.
unsafe {
read_display(
"rvg_graphics_device_read_display",
device,
0,
(dst, dst_length),
(width, height),
)
}
unsafe { read_display(device, 0, (dst, dst_length), (width, height)) }
})
}
@@ -1100,8 +1178,8 @@ pub unsafe extern "C" fn rvg_graphics_device_cursor_position(
/// Reads of one display run one at a time. On any thread. Calls back: never.
///
/// # Safety
/// `device` is a live graphics device handle; `dst` is NULL or holds `dst_length` writable bytes;
/// `width` and `height` are each NULL or writable.
/// `device` is NULL or a live graphics device handle; `dst` is NULL or holds `dst_length`
/// writable bytes; `width` and `height` are each NULL or writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rvg_graphics_device_read_display_at(
device: *mut RvgGraphicsDevice,
@@ -1113,33 +1191,33 @@ pub unsafe extern "C" fn rvg_graphics_device_read_display_at(
) -> RvgStatus {
ffi::export(|| {
// SAFETY: the caller's contract.
unsafe {
read_display(
"rvg_graphics_device_read_display_at",
device,
display,
(dst, dst_length),
(width, height),
)
}
unsafe { read_display(device, display, (dst, dst_length), (width, height)) }
})
}
/// The body of `rvg_graphics_device_read_display` and `rvg_graphics_device_read_display_at`
/// (`call`), inside their `ffi::export`: display `display` into `dst` and its length, its size
/// out through `size`'s width and height.
/// The body of `rvg_graphics_device_read_display` and `rvg_graphics_device_read_display_at`,
/// inside their `ffi::export`: display `display` into `dst` and its length, its size out through
/// `size`'s width and height. For a NULL `device`, RVG_ERR_INVALID_ARGUMENT, as for every
/// function that answers a status, with nothing written to `dst` and a size of 0 by 0, as for a
/// display past the device's count.
///
/// # Safety
/// As rvg_graphics_device_read_display_at's.
unsafe fn read_display(
call: &'static str,
device: *mut RvgGraphicsDevice,
display: u32,
(dst, dst_length): (*mut u8, usize),
(width, height): (*mut u32, *mut u32),
) -> RvgStatus {
// SAFETY: the caller's contract.
let d = unsafe { live(device, call) };
let Some(d) = (unsafe { handle::get(device) }) else {
// SAFETY: the caller's contract.
unsafe {
handle::write_out(width, 0);
handle::write_out(height, 0);
}
return RVG_ERR_INVALID_ARGUMENT;
};
let mut none: [u8; 0] = [];
let dst: &mut [u8] = if dst.is_null() {
&mut none
@@ -1180,7 +1258,6 @@ pub unsafe extern "C" fn rvg_graphics_device_cursor_position_at(
})
}
/// Quiesces the graphics device prior to VM RAM & state snapshotting: pauses VBLANK/rings,
/// drains pending compiles/workers, flushes dirty device-cached IOSurfaces back to Guest RAM,
/// and waits for GPU idle.
@@ -1188,9 +1265,7 @@ pub unsafe extern "C" fn rvg_graphics_device_cursor_position_at(
/// # Safety
/// `device` is a live graphics device handle.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rvg_graphics_device_quiesce(
device: *mut RvgGraphicsDevice,
) -> RvgStatus {
pub unsafe extern "C" fn rvg_graphics_device_quiesce(device: *mut RvgGraphicsDevice) -> RvgStatus {
ffi::export(|| {
// SAFETY: the caller's contract.
let d = unsafe { live(device, "rvg_graphics_device_quiesce") };
+185 -11
View File
@@ -43,6 +43,10 @@ fn config(callbacks: &RvgGraphicsCallbacks) -> RvgGraphicsDeviceConfig {
display_windows: std::ptr::null(),
pool_physical_address: 0,
pool_physical_length: 0,
pool_host_memory: 0,
headless_mode_width: 0,
headless_mode_height: 0,
headless_modes: std::ptr::null(),
}
}
@@ -120,6 +124,44 @@ fn a_headless_graphics_device_lives_and_ends() {
/// A config the library refuses for its size runs no destroy; NULL config and out-pointer are
/// refused
/// A NULL device is RVG_ERR_INVALID_ARGUMENT from every function that answers a status, as the
/// header's preamble says (a function without a status ends the process instead,
/// `c_harness_null_handle_aborts`): the pool's functions, the doorbell's, and the display reads,
/// which write nothing to the destination and a size of 0 by 0
#[test]
fn a_null_device_is_an_invalid_argument_where_a_status_answers() {
let d = std::ptr::null_mut();
let (_, open, _kept) = doorbells();
let mut dst = [0u8; 16];
// SAFETY: a NULL device, which each takes, and a live destination, sizes and doorbell.
unsafe {
assert_eq!(
rvg_graphics_device_pool_added(d, 0),
RVG_ERR_INVALID_ARGUMENT
);
assert_eq!(
rvg_graphics_device_pool_removed(d, 0),
RVG_ERR_INVALID_ARGUMENT
);
assert_eq!(
rvg_graphics_device_pool_grow(d, 1 << 21),
RVG_ERR_INVALID_ARGUMENT
);
assert_eq!(
rvg_graphics_device_set_doorbell(d, open),
RVG_ERR_INVALID_ARGUMENT
);
let (mut w, mut h) = (7, 7);
let read = rvg_graphics_device_read_display(d, dst.as_mut_ptr(), dst.len(), &mut w, &mut h);
assert_eq!((read, w, h), (RVG_ERR_INVALID_ARGUMENT, 0, 0));
let (mut w, mut h) = (7, 7);
let read =
rvg_graphics_device_read_display_at(d, 1, dst.as_mut_ptr(), dst.len(), &mut w, &mut h);
assert_eq!((read, w, h), (RVG_ERR_INVALID_ARGUMENT, 0, 0));
}
assert_eq!(dst, [0; 16]);
}
#[test]
fn refused_graphics_configs() {
let cb = callbacks();
@@ -146,14 +188,14 @@ fn refused_graphics_configs() {
rvg_graphics_device_create(&c, &mut device),
RVG_ERR_INVALID_ARGUMENT
);
let mut big = [0u8; 96];
std::ptr::copy_nonoverlapping(
std::ptr::from_ref(&config(&cb)).cast::<u8>(),
big.as_mut_ptr(),
size_of::<RvgGraphicsDeviceConfig>(),
);
big[0] = 96;
big[88] = 1;
// A config 8 bytes longer than the library's, aligned as the config is, with a byte set
// past the library's size.
let ours = size_of::<RvgGraphicsDeviceConfig>();
let mut big = [0u64; size_of::<RvgGraphicsDeviceConfig>() / 8 + 1];
let bytes = big.as_mut_ptr().cast::<u8>();
std::ptr::copy_nonoverlapping(std::ptr::from_ref(&config(&cb)).cast::<u8>(), bytes, ours);
bytes.cast::<u32>().write(u32::try_from(ours + 8).unwrap());
bytes.add(ours).write(1);
assert_eq!(
rvg_graphics_device_create(big.as_ptr().cast(), &mut device),
RVG_ERR_UNSUPPORTED
@@ -364,6 +406,71 @@ fn the_display_count_makes_the_displays() {
assert_eq!(reads[1], past);
}
/// A device with no window offers its config's headless mode, its width rounded down to a
/// multiple of 16 and its height to even, as each display's read answers it, a share of the
/// scanout's room on a device of several; 0 in either is 1920 x 1080, as it is for a config whose
/// `struct_size` ends before the fields
#[test]
fn a_headless_device_offers_the_configs_headless_mode() {
let cb = RvgGraphicsCallbacks {
destroy: None,
..callbacks()
};
let mut c = config(&cb);
let read = |c: &RvgGraphicsDeviceConfig| displays_of(c).1[0];
for ((w, h), size) in [
((2560, 1441), (2560, 1440)),
((1366, 768), (1360, 768)),
((3840, 0), (1920, 1080)),
((0, 0), (1920, 1080)),
] {
(c.headless_mode_width, c.headless_mode_height) = (w, h);
assert_eq!(
read(&c),
(RVG_ERR_INVALID_ARGUMENT, size.0, size.1),
"{w}x{h}"
);
}
// Two displays share the room, each offered the same mode where it fits.
(c.headless_mode_width, c.headless_mode_height) = (2560, 1440);
c.display_count = 2;
let (_, reads, _) = displays_of(&c);
assert_eq!(reads[0], reads[1]);
// A host built before the fields offers 1920 x 1080 whatever lies past its size.
c.display_count = 0;
c.struct_size = std::mem::offset_of!(RvgGraphicsDeviceConfig, headless_mode_width) as u32;
assert_eq!(read(&c), (RVG_ERR_INVALID_ARGUMENT, 1920, 1080));
}
/// Each display of a device without a window offers its own of the config's `headless_modes`, in
/// place of `headless_mode_width` x `headless_mode_height` for every display; NULL keeps those
/// for every display, as a config whose `struct_size` ends before the field does whatever lies
/// past its size
#[test]
fn each_headless_display_offers_its_own_of_the_configs_modes() {
let cb = RvgGraphicsCallbacks {
destroy: None,
..callbacks()
};
let mut c = config(&cb);
(c.headless_mode_width, c.headless_mode_height) = (2560, 1440);
c.display_count = 2;
let one = displays_of(&c).1;
let modes = [
RvgDisplayCoord { x: 1920, y: 1080 },
RvgDisplayCoord { x: 1366, y: 768 },
];
c.headless_modes = modes.as_ptr();
let reads = displays_of(&c).1;
assert_eq!(reads[0], (RVG_ERR_INVALID_ARGUMENT, 1920, 1080));
assert_eq!(reads[1], (RVG_ERR_INVALID_ARGUMENT, 1360, 768));
c.struct_size = std::mem::offset_of!(RvgGraphicsDeviceConfig, headless_modes) as u32;
assert_eq!(displays_of(&c).1, one);
// Past that size the field is not read: not even a pointer no array of sizes can start at.
c.headless_modes = std::ptr::without_provenance(1);
assert_eq!(displays_of(&c).1, one);
}
/// A display count past `RVG_GRAPHICS_DISPLAYS_MAX`, and display windows not given exactly where
/// display 0's window is, are refused once the tables are the library's, running their destroys
#[test]
@@ -564,6 +671,51 @@ unsafe extern "C-unwind" fn pool_remove(_ctx: *mut c_void, physical_address: u64
POOL_ASKS.lock().push((false, physical_address, length));
}
/// A host says its hypervisor takes no cacheable mapping of the GPU's own memory as guest memory
/// with `pool_host_memory` 1, and says nothing with 0, as a config whose `struct_size` ends before
/// the field does, whatever lies past it; any other value is refused. On the testkit's platform,
/// whose pool's blocks are the process's own memory, host memory already, a device with a pool
/// takes either, on every OS, the pool then answering its range; on the rt platform, which of the
/// pool's blocks the word picks is `reims_vgpu`'s (`graphics::pool_source`).
#[test]
fn a_pool_s_host_memory_blocks_are_the_host_s_ask() {
const BASE: u64 = 52 << 30;
let with_pool = RvgGraphicsCallbacks {
pool_add: Some(pool_add),
pool_remove: Some(pool_remove),
destroy: None,
..callbacks()
};
let config = |host_memory: u32, struct_size: usize| RvgGraphicsDeviceConfig {
struct_size: struct_size as u32,
pool_physical_address: BASE,
pool_physical_length: 2 << 20,
pool_host_memory: host_memory,
..config(&with_pool)
};
let whole = size_of::<RvgGraphicsDeviceConfig>();
let before = std::mem::offset_of!(RvgGraphicsDeviceConfig, pool_host_memory);
let made = |host_memory, size| {
let c = config(host_memory, size);
let mut device = std::ptr::null_mut();
// SAFETY: a live config and out-pointer; then a live device, released.
unsafe {
let status = rvg_graphics_device_create(&c, &mut device);
if status == RVG_OK {
let mut length = 0;
assert_eq!(rvg_graphics_device_pool_range(device, &mut length), BASE);
assert_eq!(length, 2 << 20);
rvg_graphics_device_release(device);
}
status
}
};
assert_eq!(made(0, whole), RVG_OK);
assert_eq!(made(7, before), RVG_OK, "a size before the field: 0");
assert_eq!(made(2, whole), RVG_ERR_INVALID_ARGUMENT);
assert_eq!(made(1, whole), RVG_OK);
}
/// A pool needs both of its callbacks and a range of whole 2 MiB; a device without one refuses
/// the pool's calls and answers no range; a device with one takes as much of the range as the
/// GPU's memory heaps hold, in whole 2 MiB, at most all of it, grows on the host's ask, on its
@@ -687,8 +839,9 @@ fn a_quiesce_ahead_of_the_exit_with_nothing_to_stop_answers_true() {
}
/// The write of the counts takes no handle and writes the process's degradation counts on stderr
/// before it returns, again only where they changed since: in a child, since the counts are the
/// process's
/// before it returns, again only where they changed since, and the library's build line at each
/// write; and the pacing line at a write from 2 to 60 s after the one before it, over the span
/// between the two, none sooner: in a child, since the counts are the process's
#[test]
fn a_write_of_the_counts_writes_their_line_before_it_returns() {
const CODE: &str = "test-c-api-write-counts";
@@ -702,6 +855,9 @@ fn a_write_of_the_counts_writes_their_line_before_it_returns() {
reims_vgpu_vulkan::answer::count_kind(CODE);
rvg_write_counts();
eprintln!("third write returned");
std::thread::sleep(std::time::Duration::from_millis(2_100));
rvg_write_counts();
eprintln!("fourth write returned");
return;
}
let test = "graphics::tests::a_write_of_the_counts_writes_their_line_before_it_returns";
@@ -719,9 +875,27 @@ fn a_write_of_the_counts_writes_their_line_before_it_returns() {
assert!(
matches!(
seen[..],
[one, "first write returned", "second write returned", two, "third write returned"]
[one, "first write returned", "second write returned", two, "third write returned",
"fourth write returned"]
if counted(one, 1) && counted(two, 2)
),
"{stderr}"
);
let builds = (stderr.lines())
.filter(|l| l.starts_with("reims-vgpu: build "))
.count();
assert_eq!(builds, 4, "{stderr}");
let pacing: Vec<&str> = (stderr.lines())
.filter(|l| l.starts_with("reims-vgpu: pacing") || l.ends_with("returned"))
.collect();
assert!(
matches!(
pacing[..],
[.., "third write returned", line, "fourth write returned"]
if line.starts_with("reims-vgpu: pacing over 2.")
&& line.contains(" s: presents 0.0/s; gpu ")
&& line.contains("; cpu vcpu 0% (no threads), ours ")
),
"{stderr}"
);
}
+2
View File
@@ -30,6 +30,8 @@ pub mod window;
pub mod graphics;
#[cfg(test)]
mod build_stamp;
mod ffi;
mod handle;
mod sized;
+2 -1
View File
@@ -34,7 +34,8 @@ pub const RVG_ERR_GPU: u32 = 4;
/// The host refused the memory, a pipe, a thread or the GPU device the call needs: the graphics
/// device's region, its threads, or its GPU device, where the host has none the library can use
/// or its driver refused it (rvg_graphics_device_create).
/// or its driver refused it, or the pool's host memory, which the GPU refused
/// (rvg_graphics_device_create).
pub const RVG_ERR_HOST_RESOURCES: u32 = 5;
/// The status of a Rust API error.
+3 -3
View File
@@ -138,7 +138,7 @@ static void check_graphics(void) {
NULL,
NULL};
RvgGraphicsDeviceConfig c = {
sizeof c, &cb, NULL, NULL, NULL, RVG_GUEST_ARCH_X86_64, 2, 0, NULL, 0, 0};
sizeof c, &cb, NULL, NULL, NULL, RVG_GUEST_ARCH_X86_64, 2, 0, NULL, 0, 0, 0, 0, 0, NULL};
RvgGraphicsDevice *d = NULL;
graphics_destroyed = 0;
graphics_raised = 0;
@@ -270,7 +270,7 @@ static void check_displays(void) {
cb.ctx = &displays_destroyed;
cb.destroy = on_graphics_destroy;
RvgGraphicsDeviceConfig c = {
sizeof c, &cb, NULL, NULL, NULL, RVG_GUEST_ARCH_X86_64, 0, 2, NULL, 0, 0};
sizeof c, &cb, NULL, NULL, NULL, RVG_GUEST_ARCH_X86_64, 0, 2, NULL, 0, 0, 0, 0, 0, NULL};
RvgGraphicsDevice *d = NULL;
displays_destroyed = 0;
CHECK_STATUS(rvg_graphics_device_create(&c, &d), RVG_OK);
@@ -409,7 +409,7 @@ static void check_memory_files(void) {
cb.ctx = &files_destroyed;
cb.destroy = on_graphics_destroy;
RvgGraphicsDeviceConfig c = {
sizeof c, &cb, NULL, &map, &file, RVG_GUEST_ARCH_X86_64, 0, 0, NULL, 0, 0};
sizeof c, &cb, NULL, &map, &file, RVG_GUEST_ARCH_X86_64, 0, 0, NULL, 0, 0, 0, 0, 0, NULL};
files_destroyed = 0;
RvgGraphicsDevice *d = NULL;
CHECK_STATUS(rvg_graphics_device_create(&c, &d), RVG_OK);
+8
View File
@@ -145,6 +145,7 @@ include = [
"RgfxHeapOverHostMemory",
"RgfxHeapOverPages",
"RgfxHeapTextureSizeAndAlign",
"RgfxHiddenPlaces",
"RgfxIcbBuffer",
"RgfxIcbBufferStride",
"RgfxIcbCreate",
@@ -286,6 +287,7 @@ include = [
"RgfxPipelineAnswersQuery",
"RgfxPipelineLibrary",
"RgfxPipelineReflection",
"RgfxPointerLook",
"RgfxPointerMotion",
"RgfxPointerOver",
"RgfxPoolBlock",
@@ -334,10 +336,16 @@ include = [
"RgfxSharedEventSetValue",
"RgfxSharedEventUnname",
"RgfxSharedEventValue",
"RgfxSharedTexture",
"RgfxSharedTextureCreate",
"RgfxSharedTextureImport",
"RgfxSharedTextureName",
"RgfxSharedTextureUnname",
"RgfxSizeAndAlign",
"RgfxStencilDescriptor",
"RgfxSurfaceDownload",
"RgfxSurfaceFacts",
"RgfxSurfaceHoldLowered",
"RgfxSurfaceOrderWait",
"RgfxSurfacePages",
"RgfxSurfacePagesCache",
@@ -1835,13 +1835,159 @@
// `POOL_LENGTH_HI`, RO: as [`RGFX_REG_POOL_LENGTH_LO`], its high 32 bits.
#define RGFX_REG_POOL_LENGTH_HI 80
// `GUEST_BUNDLE`, WO: what the guest's accelerator found of its Metal bundle as WindowServer
// opened the display, once a boot, so the host can tell its user why a desktop runs without
// Metal: in bits 0 to 7 an `RGFX_GUEST_BUNDLE_*` (ours, another version's, none, or RgfxGate's
// install still under way), in bits 8 to 15 the wire version another version's bundle's marker
// names (0 where it names none the kext knows), in bits 16 to 23 RgfxGate's install pass, an
// `RGFX_GATE_*`, and in bits 24 to 31 the error its failed write gave (`errno`, 0 for none). It
// reads 0. A host that does not know it ignores the write, as at any offset it does not know, and
// the guest acts on nothing of it, so it needs no feature: a kext built before it never writes
// it, and a host then says nothing of the bundle.
#define RGFX_REG_GUEST_BUNDLE 84
// `FEATURES_EXT`, RO: feature bits 64 to 95 the host offers. The guest uses each with no take,
// but those [`RGFX_REG_DRIVER_FEATURES_EXT`] takes ([`RGFX_FEATURE_EXT_SURFACE_HOLD`]): a guest
// that sees one of the others may send the messages it names, and the host carries out nothing
// else for a guest that does, so a guest that never reads it gets the wire it had before. It
// reads [`RGFX_FEATURE_EXT_SHARED_TEXTURE_NAMES`] and [`RGFX_FEATURE_EXT_SURFACE_HOLD`] where the
// host offers them; 0 from a host older than it, as at any offset a host does not know. A write
// is ignored. Bit 1 is offered by no host: hosts built before the hold word left the block's
// header offered `SURFACE_HOLD` there, with the word in the header, and kexts built before it
// take it; a write of it takes nothing, so such a kext and this host, or this kext and such a
// host, take no hold.
#define RGFX_REG_FEATURES_EXT 88
// `DRIVER_FEATURES_EXT`, RW: the feature bits 64 to 95 the guest's driver took of those
// `FEATURES_EXT` offers that are taken ([`RGFX_FEATURE_EXT_SURFACE_HOLD`]). A write takes the
// bits written that `FEATURES_EXT` offers and that are taken, and a read answers the bits taken.
// As at `DRIVER_FEATURES_LO`, a write while `STATUS` reads [`RGFX_STATUS_DRIVER_READY`] is
// ignored, and a reset clears it. A guest that never writes it (the option ROM, a kext built
// before it) gets the wire it had before; a host older than it reads 0 there and ignores a
// write, as at any offset it does not know.
#define RGFX_REG_DRIVER_FEATURES_EXT 92
// `FEATURES_EXT` bit 0, feature bit 64, `SHARED_TEXTURE_NAMES`: ring 0 carries
// [`RGFX_CMD_SHARED_TEXTURE_CREATE`], a process's texture another process may open
// (`newSharedTextureWithDescriptor:`), and the messages the accelerator kext posts for its handle:
// [`RGFX_CMD_SHARED_TEXTURE_NAME`], which names it device-wide, [`RGFX_CMD_SHARED_TEXTURE_IMPORT`],
// by which another process's new texture is the same host texture, and
// [`RGFX_CMD_SHARED_TEXTURE_UNNAME`]. Every host offers it.
#define RGFX_FEATURE_EXT_SHARED_TEXTURE_NAMES (1 << 0)
// `FEATURES_EXT` bit 2, feature bit 66, `SURFACE_HOLD`, taken in
// [`RGFX_REG_DRIVER_FEATURES_EXT`]. A host whose GPU's memory is its own (a device of one
// memory) may make an image in place over guest pages it imports by their pointer by copying the
// bytes under the image out and back around the image's first layout move, so a CPU write of
// those bytes between the two copies is lost. Where the guest took it:
// - **A cached surface's hold word.** The block of a surface with a device cache
// ([`RGFX_SURFACE_PAGES_CACHED`]) holds a 32-bit word in its own part, which no process maps:
// the first of the [`RGFX_SURFACE_HOLD_ROOM`] bytes right before its runs, at region offset
// `runs_offset - RGFX_SURFACE_HOLD_ROOM`, which the kext stores 0 into as it caches the block.
// So only the kext and the host write it. Before such a make over the block's pages the host
// raises it ([`RGFX_SURFACE_HOLD_RAISED`]), and after a full fence reads the surface's CPU
// generation in the block's header again: where it moved since the host decided on the make,
// the host lowers the word and makes nothing in place. Once the bytes are back it stores 0
// there. A block whose word would lie in its first [`RGFX_SURFACE_HOLD_ROOM`] bytes, where
// its header lies (its runs less than twice that past its start), has none, and gets no image
// made so over its pages. A read-write CPU lock stores the new generation, and after a full
// fence reads the word: while it is raised, the lock sets [`RGFX_SURFACE_HOLD_WAITED`] beside
// it and waits, looking again at the device's next vector or within 1 ms. So either the host
// reads the lock's generation and makes nothing in place, or the lock goes on once the bytes
// are back. A read-only lock waits for nothing.
// - **Answered creates over pages.** A [`RGFX_CMD_TEXTURE_FROM_BUFFER`] or
// [`RGFX_CMD_LINEAR_TEXTURE_FROM_BUFFER`] over a buffer a [`RGFX_CMD_BUFFER_OVER_PAGES`]
// made (the host's refusal of it among them) is answered by an [`RGFX_EVT_COMPLETE`] of
// [`RGFX_STATUS_OK`] once carried out, the texture made or refused, and the guest's create
// waits for that answer, so the creating thread writes the buffer only after the make. Every
// such create is answered: the host answers a pages block before it imports the block's
// pages, and on Linux the import alone finds whether it goes by the pages' pointer, the kind
// of import a make copies out and back.
//
// A guest that does not take it gets no image made so over a cached surface's pages, and no
// answer. The host offers it where its GPU's memory is its own. The x86-64 and arm64e kexts
// take it.
#define RGFX_FEATURE_EXT_SURFACE_HOLD (1 << 2)
// The bytes of a cached surface's block right before its runs that hold its hold word
// ([`RGFX_FEATURE_EXT_SURFACE_HOLD`]), a `u32` at their start: a page of the block's own part,
// past the part its processes map, which no process maps.
#define RGFX_SURFACE_HOLD_ROOM 4096
// The hold word's bit the host raises around a make that copies the pages' bytes out and back
// ([`RGFX_FEATURE_EXT_SURFACE_HOLD`]).
#define RGFX_SURFACE_HOLD_RAISED (1 << 0)
// The hold word's bit a read-write CPU lock sets beside [`RGFX_SURFACE_HOLD_RAISED`] while it
// waits ([`RGFX_FEATURE_EXT_SURFACE_HOLD`]), which the host counts.
#define RGFX_SURFACE_HOLD_WAITED (1 << 1)
// A [`RGFX_REG_GUEST_BUNDLE`] value's bundle field: the kext's own version's bundle is on disk,
// and the accelerator registered for it.
#define RGFX_GUEST_BUNDLE_OURS 1
// A [`RGFX_REG_GUEST_BUNDLE`] value's bundle field: the bundle's executable is there without the
// marker of the kext's version, so the accelerator stays unregistered for the boot.
#define RGFX_GUEST_BUNDLE_OTHER_VERSION 2
// A [`RGFX_REG_GUEST_BUNDLE`] value's bundle field: no bundle's executable is there, so the
// accelerator stays unregistered for the boot.
#define RGFX_GUEST_BUNDLE_ABSENT 3
// A [`RGFX_REG_GUEST_BUNDLE`] value's bundle field: RgfxGate's install pass had not ended, so the
// accelerator stays unregistered for the boot.
#define RGFX_GUEST_BUNDLE_GATE_BUSY 4
// Where a [`RGFX_REG_GUEST_BUNDLE`] value's other version starts: bits 8 to 15.
#define RGFX_GUEST_BUNDLE_VERSION_SHIFT 8
// Where a [`RGFX_REG_GUEST_BUNDLE`] value's `RGFX_GATE_*` starts: bits 16 to 23.
#define RGFX_GUEST_BUNDLE_GATE_SHIFT 16
// Where a [`RGFX_REG_GUEST_BUNDLE`] value's `errno` starts: bits 24 to 31.
#define RGFX_GUEST_BUNDLE_ERRNO_SHIFT 24
// RgfxGate's install pass, as [`RGFX_REG_GUEST_BUNDLE`] gives it: no RgfxGate published one.
#define RGFX_GATE_NONE 0
// RgfxGate's install pass: under way still.
#define RGFX_GATE_RUNNING 1
// RgfxGate's install pass: ended without saying how, as an RgfxGate built before
// `RgfxGateInstallResult` does.
#define RGFX_GATE_UNTOLD 2
// RgfxGate's install pass: its own bundle was there already, written and tagged.
#define RGFX_GATE_PRESENT 3
// RgfxGate's install pass: it wrote its own bundle and tagged it.
#define RGFX_GATE_INSTALLED 4
// RgfxGate's install pass: its own bundle was there, and it tagged it.
#define RGFX_GATE_TAGGED 5
// RgfxGate's install pass: a write or the rename of its bundle failed, with the `errno`.
#define RGFX_GATE_FAILED 6
// RgfxGate's install pass: the Data volume did not mount while it waited, about 60 s.
#define RGFX_GATE_NO_DATA_VOLUME 7
// RgfxGate's install pass: none, in the installer or Recovery.
#define RGFX_GATE_SKIPPED 8
// RgfxGate's install pass: it could not start one (no thread, no VFS context, or on arm64 a
// kernel whose vnode layout it does not know).
#define RGFX_GATE_REFUSED 9
// What `MAGIC` reads: "RGFX", little-endian.
#define RGFX_MAGIC 1481000786
// What `VERSION` reads: the wire's version, which every change a guest built before it would
// misread moves on (docs/graphics-kext/design.md, "The wire's version"). The kext and the option
// ROM leave a device of any other version.
#define RGFX_VERSION 2
// misread moves on, a record's size among them: `include/reims_graphics_wire_sizes.h` pins each
// record's size to it (docs/graphics-kext/design.md, "The wire's version"). The kext and the
// option ROM leave a device of any other version, and the kext registers its accelerator only for
// a bundle of its own.
#define RGFX_VERSION 3
// `STATUS`: the device is reset, and takes no message.
#define RGFX_STATUS_RESET 0
@@ -2032,6 +2178,10 @@
// [`RGFX_FEATURE_POINTER_MOTION`]: not answered.
#define RGFX_CMD_SCROLL_DEVICES 11
// Command `HIDDEN_PLACES` ([`RgfxHiddenPlaces`]), where the guest took
// [`RGFX_FEATURE_POINTER_MOTION`]: not answered.
#define RGFX_CMD_HIDDEN_PLACES 12
// Event `COMPLETE` ([`RgfxComplete`]): a command's answer, with its `seqno`.
#define RGFX_EVT_COMPLETE 256
@@ -2059,6 +2209,12 @@
// own devices scroll as far.
#define RGFX_EVT_SCROLL 262
// Event `POINTER_LOOK` ([`RgfxPointerLook`]), sent only to a guest whose last `HIDDEN_PLACES`
// since its last start ([`RGFX_CMD_HIDDEN_PLACES`]) said it reports them: the host's pointer
// moved the guest's tablet while the guest hides its cursor, and the guest reports where its
// hidden cursor goes.
#define RGFX_EVT_POINTER_LOOK 263
// `COMPLETE`'s status: the command was done.
#define RGFX_STATUS_OK 0
@@ -2469,6 +2625,48 @@
// buffer lies there. Makes nothing.
#define RGFX_CMD_PAGES_BUFFER_ADDRESS 573
// Command `SHARED_TEXTURE_CREATE` ([`RgfxSharedTextureCreate`]), where the host offers
// [`RGFX_FEATURE_EXT_SHARED_TEXTURE_NAMES`]: a texture of shape `desc` that other processes may
// open (`newSharedTextureWithDescriptor:`), with the guest-picked `resource_id`. The host makes
// the texture's storage itself, at an address and a resource index of its own, which no context
// holds, and the sender's texture `obj_id` over all of it at `resource_id`; each process that
// opens it later has its own texture over the same storage at its own index
// ([`RGFX_CMD_SHARED_TEXTURE_IMPORT`]). So the storage outlives the context that made it while
// another process's texture or a name holds it, and no context's addresses or indices are held
// past its close. Its storage mode is Private: a create of any other is refused. Not answered;
// a create the host refuses stands for a refused object, as a `TEXTURE_CREATE`'s does.
// `OBJECT_DESTROY` drops the sender's texture; the storage goes with its last texture and its
// last name.
#define RGFX_CMD_SHARED_TEXTURE_CREATE 574
// Command `SHARED_TEXTURE_NAME` ([`RgfxSharedTextureName`]), which the accelerator kext posts for
// a process's handle of its shared texture `obj_id` (`newSharedTextureHandle`), where the host
// offers [`RGFX_FEATURE_EXT_SHARED_TEXTURE_NAMES`]: the texture's storage is named `name`
// device-wide, so another process may open it ([`RGFX_CMD_SHARED_TEXTURE_IMPORT`]), until the kext
// lets go of the name ([`RGFX_CMD_SHARED_TEXTURE_UNNAME`]). A name holds the storage as a texture
// over it does. Answered by [`RGFX_EVT_COMPLETE`]: [`RGFX_STATUS_OK`], or
// [`RGFX_STATUS_NOT_FOUND`] where the sender holds no shared texture of that id (one whose
// create the host refused among them), and [`RGFX_STATUS_INVALID_ARGUMENT`] for a name of 0. The
// kext builds the message: `name` is the kext's, never the process's.
#define RGFX_CMD_SHARED_TEXTURE_NAME 575
// Command `SHARED_TEXTURE_IMPORT` ([`RgfxSharedTextureImport`]), which the accelerator kext posts
// for a process that opens a handle another process's `SHARED_TEXTURE_NAME` named
// (`newSharedTextureWithHandle:`), where the host offers
// [`RGFX_FEATURE_EXT_SHARED_TEXTURE_NAMES`]: the process's new texture `obj_id` lies over all of
// the storage `name` names, in the shape it was made in, at the guest-picked `resource_id`.
// Answered by [`RGFX_EVT_SHARED_TEXTURE`] with the shape, which the process's texture answers,
// or [`RGFX_STATUS_NOT_FOUND`] where the name was let go of or never given, and
// [`RGFX_STATUS_INVALID_ARGUMENT`] for another context's id or a resource index the sender does
// not hold; nothing is made then. `OBJECT_DESTROY` drops it, as any texture.
#define RGFX_CMD_SHARED_TEXTURE_IMPORT 576
// Command `SHARED_TEXTURE_UNNAME` ([`RgfxSharedTextureUnname`]), which the accelerator kext posts
// once nothing but the kext holds the handle a `SHARED_TEXTURE_NAME` named, where the host offers
// [`RGFX_FEATURE_EXT_SHARED_TEXTURE_NAMES`]: no process can open the name from then on, and the
// storage goes once no texture lies over it. Context 0's, which no process is. Not answered.
#define RGFX_CMD_SHARED_TEXTURE_UNNAME 577
// `CONTEXT_CLOSE` ([`RgfxContextClose`]), on ring 0 from the accelerator kext: the process that
// held context `context` closed the device or died. The host ends the context's command queues
// and drops every object whose id lies in its range ([`RGFX_CONTEXT_OBJ_ID_SHIFT`]), then answers
@@ -2838,6 +3036,18 @@
// `gpu_address` and `length`; otherwise each 0.
#define RGFX_EVT_PRIVATE_BLOCK 1041
// Event `SHARED_TEXTURE` ([`RgfxSharedTexture`], on the control completion ring), with a
// [`RGFX_CMD_SHARED_TEXTURE_IMPORT`]'s `seqno`: its answer. `status` [`RGFX_STATUS_OK`] with the
// shape the storage was made in; otherwise the shape is zeros.
#define RGFX_EVT_SHARED_TEXTURE 1042
// Event `SURFACE_HOLD_LOWERED` ([`RgfxSurfaceHoldLowered`], on the control completion ring,
// `seqno` 0), where the guest took [`RGFX_FEATURE_EXT_SURFACE_HOLD`]: the host lowered the hold
// word of the cached surface's block at `block_offset` after a read-write CPU lock set
// [`RGFX_SURFACE_HOLD_WAITED`] beside it, so the lock looks at the word again. Posted with no
// wait: one the ring has no room for is dropped, and the lock looks again within 1 ms.
#define RGFX_EVT_SURFACE_HOLD_LOWERED 1043
// A command buffer's status in [`RgfxCbComplete`]: finished with no error.
#define RGFX_CB_OK 0
@@ -5479,6 +5689,24 @@ typedef struct {
RgfxTextureDescriptor desc;
} RgfxHeapTextureSizeAndAlign;
// `HIDDEN_PLACES`: whether the guest reports where its hidden cursor goes (`reports` 1, else 0),
// which its driver sends once its mouse ([`RGFX_FEATURE_POINTER_MOTION`]) is up after each start.
// A guest that reports them is sent [`RGFX_EVT_POINTER_LOOK`] when the host's pointer moves its
// tablet while it hides its cursor, and answers with a `MOVE_CURSOR` of the cursor still hidden
// (`visible` 0) at each new place it reads for a while after; the device then counts a hide as a
// game's only once its hidden cursor has followed the tablet (docs/graphics-kext/design.md, "A
// pointer for games", "The hidden cursor's place"). A guest that sends none, or 0, is never sent
// `POINTER_LOOK`, and each hide of its counts as a game's as before, until the next reset. The
// x86-64 kext sends it; the arm64e kext, whose cursor is a layer of its swaps, sends none.
typedef struct {
// [`RGFX_CMD_HIDDEN_PLACES`].
RgfxMsgHeader header;
// 1 where the guest reports where its hidden cursor goes, else 0.
uint32_t reports;
// 0.
uint32_t reserved_14;
} RgfxHiddenPlaces;
// The body of a buffer's setter.
typedef struct {
// The buffer, 0 for nil.
@@ -7264,6 +7492,21 @@ typedef struct {
uint32_t flags;
} RgfxPipelineReflection;
// `POINTER_LOOK`: the host's pointer, over display `display`'s window, moved the guest's tablet
// while the guest hides its cursor on every display: the guest looks where its hidden cursor
// goes for a while, and reports each new place in a `MOVE_CURSOR` of the cursor still hidden
// (`visible` 0). Sent only to a guest whose [`RGFX_CMD_HIDDEN_PLACES`] said it reports them,
// while the hide has not shown its hidden cursor following the tablet, one at most every 50 ms;
// one that finds the ring held or full is not sent, and the next move sends it.
typedef struct {
// [`RGFX_EVT_POINTER_LOOK`], `seqno` 0.
RgfxMsgHeader header;
// The display whose window the host's pointer is over.
uint32_t display;
// 0.
uint32_t reserved_14;
} RgfxPointerLook;
// `POINTER_MOTION`: the host's pointing device moved by (`dx`, `dy`), right and down, in its own
// counts, as no acceleration has changed them, turned its wheel `wheel` notches up (away from the
// person), and holds the `RGFX_POINTER_BUTTON_*` `buttons` after it. The guest's driver hands it
@@ -8209,6 +8452,67 @@ typedef struct {
uint64_t value;
} RgfxSharedEventValue;
// `SHARED_TEXTURE`: a `SHARED_TEXTURE_IMPORT`'s answer, with its `seqno`: the shape the storage
// was made in, which the new texture answers.
typedef struct {
// [`RGFX_EVT_SHARED_TEXTURE`], with the import's `seqno`.
RgfxMsgHeader header;
// An `RGFX_STATUS_*`: [`RGFX_STATUS_OK`] where the texture is made.
uint32_t status;
// Pads to a multiple of 8; 0.
uint32_t reserved_14;
// The storage's shape; zeros where the texture was not made.
RgfxTextureDescriptor desc;
} RgfxSharedTexture;
// `SHARED_TEXTURE_CREATE`: the sender's texture `obj_id`, of shape `desc`, over storage the host
// makes for it, which other processes may open.
typedef struct {
// [`RGFX_CMD_SHARED_TEXTURE_CREATE`].
RgfxMsgHeader header;
// The new texture's guest-picked id.
uint64_t obj_id;
// The texture's guest-picked resource id.
uint64_t resource_id;
// The texture's shape: Private storage.
RgfxTextureDescriptor desc;
} RgfxSharedTextureCreate;
// `SHARED_TEXTURE_IMPORT`: the sender's new texture `obj_id` over the storage named `name`, at
// `resource_id`. The kext builds the message from the handle the process holds.
typedef struct {
// [`RGFX_CMD_SHARED_TEXTURE_IMPORT`].
RgfxMsgHeader header;
// The sender's new texture's guest-picked id.
uint64_t obj_id;
// The name the storage was given ([`RgfxSharedTextureName::name`]).
uint64_t name;
// The new texture's guest-picked resource id.
uint64_t resource_id;
} RgfxSharedTextureImport;
// `SHARED_TEXTURE_NAME`: the storage of the sender's shared texture `obj_id` named `name`
// device-wide. The kext builds the message: `name` is the kext's, never the process's.
typedef struct {
// [`RGFX_CMD_SHARED_TEXTURE_NAME`].
RgfxMsgHeader header;
// The sender's shared texture, or a texture it opened from another's name.
uint64_t obj_id;
// Its name, unique to the device from the kext's start: never 0.
uint64_t name;
} RgfxSharedTextureName;
// `SHARED_TEXTURE_UNNAME`: the name `name` is no longer the kext's to give out.
typedef struct {
// [`RGFX_CMD_SHARED_TEXTURE_UNNAME`].
RgfxMsgHeader header;
// 0: the message is context 0's, which no process is, so it waits for no process's
// messages.
uint64_t reserved_10;
// The name ([`RgfxSharedTextureName::name`]).
uint64_t name;
} RgfxSharedTextureUnname;
// `SIZE_AND_ALIGN`: a `HEAP_TEXTURE_SIZE_AND_ALIGN`'s answer. `status` is [`RGFX_STATUS_OK`]
// with the device's `size` and `align` (a size of 0 for a shape no texture has, as Metal answers
// it), or [`RGFX_STATUS_REFUSED`], with both 0, where the device gave no answer.
@@ -8265,6 +8569,15 @@ typedef struct {
uint32_t reserved_24;
} RgfxSurfaceFacts;
// `SURFACE_HOLD_LOWERED`: the host lowered a cached surface's hold word that a lock waited on
// ([`RGFX_EVT_SURFACE_HOLD_LOWERED`]).
typedef struct {
// [`RGFX_EVT_SURFACE_HOLD_LOWERED`], `seqno` 0.
RgfxMsgHeader header;
// The region offset of the surface's block.
uint64_t block_offset;
} RgfxSurfaceHoldLowered;
// One command buffer an [`RGFX_OP_SURFACE_ORDER`]'s buffer runs after, or an
// [`RGFX_OP_COMMIT_ORDER`]'s is committed after: the one at `seqno` on the submission ring of
// queue `queue_obj_id`, and the queue's buffers before it.
@@ -0,0 +1,405 @@
/*
* reims_graphics_wire_sizes.h: the size of each record of the reims-graphics device's wire
* (reims_graphics_wire.h) at the wire's version RGFX_WIRE_SIZES_VERSION, one
* RGFX_WIRE_SIZE(record, bytes) row a record, which the includer defines. The wire crate's tests
* (crates/reims-vgpu-graphics/tests/wire_sizes.rs) and the guest's (guest/kext/tests/
* wire_sizes_test.cpp) check each row against the header as each side compiles it, and that
* RGFX_WIRE_SIZES_VERSION is RGFX_VERSION.
*
* A record's size changes only with the version (docs/graphics-kext/design.md, "The wire's
* version"): a guest built at a version lays out and reads each record at the size this table
* gives it. A change that alters a size moves RGFX_VERSION on by one, and this table to the new
* version with the new sizes, in the same commit; a record that must carry more under the same
* version takes a record of its own after it, under a feature the guest takes. A new record adds
* its row at the version it lands in.
*
* The same holds for each register of BAR 0, one RGFX_WIRE_REGISTER(register, offset) row a
* register: a register that moves moves RGFX_VERSION on, and a new register, at an offset no
* register of an earlier version had, adds its row at the version it lands in.
*/
#define RGFX_WIRE_SIZES_VERSION 3
#ifdef RGFX_WIRE_SIZE
RGFX_WIRE_SIZE(RgfxArgumentDescriptor, 24)
RGFX_WIRE_SIZE(RgfxArgumentLayoutQuery, 80)
RGFX_WIRE_SIZE(RgfxArgumentLayoutRecord, 24)
RGFX_WIRE_SIZE(RgfxArgumentLayoutReply, 16)
RGFX_WIRE_SIZE(RgfxArgumentMemberRecord, 48)
RGFX_WIRE_SIZE(RgfxBlitOpCopyBufferToBuffer, 40)
RGFX_WIRE_SIZE(RgfxBlitOpCopyBufferToTexture, 104)
RGFX_WIRE_SIZE(RgfxBlitOpCopyBufferToTextureOptions, 112)
RGFX_WIRE_SIZE(RgfxBlitOpCopyIndirectCommandBuffer, 40)
RGFX_WIRE_SIZE(RgfxBlitOpCopyTextureRegion, 120)
RGFX_WIRE_SIZE(RgfxBlitOpCopyTextureRegionOptions, 128)
RGFX_WIRE_SIZE(RgfxBlitOpCopyTextureSlices, 64)
RGFX_WIRE_SIZE(RgfxBlitOpCopyTextureToBuffer, 104)
RGFX_WIRE_SIZE(RgfxBlitOpCopyTextureToBufferOptions, 112)
RGFX_WIRE_SIZE(RgfxBlitOpFillBuffer, 32)
RGFX_WIRE_SIZE(RgfxBlitOpFillBufferPattern4, 32)
RGFX_WIRE_SIZE(RgfxBlitOpFillTexture, 80)
RGFX_WIRE_SIZE(RgfxBlitOpFillTextureColor, 112)
RGFX_WIRE_SIZE(RgfxBlitOpGenerateMipmaps, 8)
RGFX_WIRE_SIZE(RgfxBlitOpInvalidateCompressedTexture, 8)
RGFX_WIRE_SIZE(RgfxBlitOpInvalidateCompressedTextureSlice, 24)
RGFX_WIRE_SIZE(RgfxBlitOpOptimizeForCpu, 8)
RGFX_WIRE_SIZE(RgfxBlitOpOptimizeForCpuSlice, 24)
RGFX_WIRE_SIZE(RgfxBlitOpOptimizeForGpu, 8)
RGFX_WIRE_SIZE(RgfxBlitOpOptimizeForGpuSlice, 24)
RGFX_WIRE_SIZE(RgfxBlitOpOptimizeIndirectCommandBuffer, 24)
RGFX_WIRE_SIZE(RgfxBlitOpResetCommandsInBuffer, 24)
RGFX_WIRE_SIZE(RgfxBlitOpSynchronizeResource, 16)
RGFX_WIRE_SIZE(RgfxBlitOpSynchronizeTexture, 24)
RGFX_WIRE_SIZE(RgfxBlitOpUpdateFence, 8)
RGFX_WIRE_SIZE(RgfxBlitOpWaitForFence, 8)
RGFX_WIRE_SIZE(RgfxBlockGrant, 40)
RGFX_WIRE_SIZE(RgfxBlockRelease, 40)
RGFX_WIRE_SIZE(RgfxBufferAtOffset, 56)
RGFX_WIRE_SIZE(RgfxBufferBinding, 16)
RGFX_WIRE_SIZE(RgfxBufferCreate, 48)
RGFX_WIRE_SIZE(RgfxBufferDidModifyRange, 40)
RGFX_WIRE_SIZE(RgfxBufferEscaped, 32)
RGFX_WIRE_SIZE(RgfxBufferManagedAtOffset, 64)
RGFX_WIRE_SIZE(RgfxBufferOverHostMemory, 56)
RGFX_WIRE_SIZE(RgfxBufferOverPages, 72)
RGFX_WIRE_SIZE(RgfxBufferOverSurfacePages, 56)
RGFX_WIRE_SIZE(RgfxBufferStrideBinding, 24)
RGFX_WIRE_SIZE(RgfxCbComplete, 48)
RGFX_WIRE_SIZE(RgfxCbScheduled, 24)
RGFX_WIRE_SIZE(RgfxCbSubmitted, 24)
RGFX_WIRE_SIZE(RgfxColorAttachmentDesc, 40)
RGFX_WIRE_SIZE(RgfxColorEntry, 16)
RGFX_WIRE_SIZE(RgfxCommandBuffer, 40)
RGFX_WIRE_SIZE(RgfxCommandBufferInRegion, 32)
RGFX_WIRE_SIZE(RgfxCommandBufferPart, 56)
RGFX_WIRE_SIZE(RgfxComplete, 24)
RGFX_WIRE_SIZE(RgfxComputeBufferBinding, 16)
RGFX_WIRE_SIZE(RgfxComputeBufferStrideBinding, 24)
RGFX_WIRE_SIZE(RgfxComputeHeapBinding, 8)
RGFX_WIRE_SIZE(RgfxComputeOpDispatchThreadgroups, 48)
RGFX_WIRE_SIZE(RgfxComputeOpDispatchThreadgroupsIndirect, 40)
RGFX_WIRE_SIZE(RgfxComputeOpDispatchThreads, 48)
RGFX_WIRE_SIZE(RgfxComputeOpDispatchThreadsIndirect, 16)
RGFX_WIRE_SIZE(RgfxComputeOpEncodeStartIf, 32)
RGFX_WIRE_SIZE(RgfxComputeOpEncodeStartWhile, 32)
RGFX_WIRE_SIZE(RgfxComputeOpExecuteCommandsInBuffer, 24)
RGFX_WIRE_SIZE(RgfxComputeOpExecuteCommandsIndirect, 24)
RGFX_WIRE_SIZE(RgfxComputeOpMemoryBarrierResources, 8)
RGFX_WIRE_SIZE(RgfxComputeOpMemoryBarrierScope, 8)
RGFX_WIRE_SIZE(RgfxComputeOpSetBufferOffset, 16)
RGFX_WIRE_SIZE(RgfxComputeOpSetBufferOffsetAttributeStride, 24)
RGFX_WIRE_SIZE(RgfxComputeOpSetBuffers, 16)
RGFX_WIRE_SIZE(RgfxComputeOpSetBuffersAttributeStrides, 16)
RGFX_WIRE_SIZE(RgfxComputeOpSetComputePipelineState, 8)
RGFX_WIRE_SIZE(RgfxComputeOpSetImageblockWidth, 16)
RGFX_WIRE_SIZE(RgfxComputeOpSetSamplerStates, 16)
RGFX_WIRE_SIZE(RgfxComputeOpSetSamplerStatesLodClamps, 16)
RGFX_WIRE_SIZE(RgfxComputeOpSetStageInRegion, 48)
RGFX_WIRE_SIZE(RgfxComputeOpSetStageInRegionIndirect, 16)
RGFX_WIRE_SIZE(RgfxComputeOpSetTexture, 16)
RGFX_WIRE_SIZE(RgfxComputeOpSetTextures, 16)
RGFX_WIRE_SIZE(RgfxComputeOpSetThreadgroupMemoryLength, 16)
RGFX_WIRE_SIZE(RgfxComputeOpSetVisibleFunctionTable, 16)
RGFX_WIRE_SIZE(RgfxComputeOpSetVisibleFunctionTables, 16)
RGFX_WIRE_SIZE(RgfxComputeOpUpdateFence, 8)
RGFX_WIRE_SIZE(RgfxComputeOpUseHeaps, 8)
RGFX_WIRE_SIZE(RgfxComputeOpUseResources, 16)
RGFX_WIRE_SIZE(RgfxComputeOpWaitForFence, 8)
RGFX_WIRE_SIZE(RgfxComputePassDesc, 8)
RGFX_WIRE_SIZE(RgfxComputePipelineCreate, 96)
RGFX_WIRE_SIZE(RgfxComputeResourceRef, 16)
RGFX_WIRE_SIZE(RgfxComputeSamplerBinding, 8)
RGFX_WIRE_SIZE(RgfxComputeSamplerLodBinding, 16)
RGFX_WIRE_SIZE(RgfxComputeTextureBinding, 8)
RGFX_WIRE_SIZE(RgfxComputeVisibleFunctionTableBinding, 8)
RGFX_WIRE_SIZE(RgfxContextClose, 24)
RGFX_WIRE_SIZE(RgfxCursorColor, 288)
RGFX_WIRE_SIZE(RgfxCursorCurve, 32)
RGFX_WIRE_SIZE(RgfxDepthStencilCreate, 80)
RGFX_WIRE_SIZE(RgfxDeviceInfo, 11672)
RGFX_WIRE_SIZE(RgfxDisplayBounds, 40)
RGFX_WIRE_SIZE(RgfxDisplayChanged, 24)
RGFX_WIRE_SIZE(RgfxDisplayColor, 40)
RGFX_WIRE_SIZE(RgfxDisplayEntry, 16)
RGFX_WIRE_SIZE(RgfxDisplayScale, 8)
RGFX_WIRE_SIZE(RgfxDisplays, 24)
RGFX_WIRE_SIZE(RgfxDynamicLibraryCreate, 32)
RGFX_WIRE_SIZE(RgfxEventSignalled, 32)
RGFX_WIRE_SIZE(RgfxFormatAnswers, 64)
RGFX_WIRE_SIZE(RgfxFunctionConstant, 40)
RGFX_WIRE_SIZE(RgfxFunctionHandleCreate, 80)
RGFX_WIRE_SIZE(RgfxFunctionPointerState, 48)
RGFX_WIRE_SIZE(RgfxFunctionTableCreate, 40)
RGFX_WIRE_SIZE(RgfxFunctionTableSet, 40)
RGFX_WIRE_SIZE(RgfxGetDisplays, 16)
RGFX_WIRE_SIZE(RgfxHeapBinding, 8)
RGFX_WIRE_SIZE(RgfxHeapCreate, 48)
RGFX_WIRE_SIZE(RgfxHeapOverHostMemory, 56)
RGFX_WIRE_SIZE(RgfxHeapOverPages, 64)
RGFX_WIRE_SIZE(RgfxHeapTextureSizeAndAlign, 72)
RGFX_WIRE_SIZE(RgfxHiddenPlaces, 24)
RGFX_WIRE_SIZE(RgfxIcbBuffer, 24)
RGFX_WIRE_SIZE(RgfxIcbBufferStride, 32)
RGFX_WIRE_SIZE(RgfxIcbComputeSlot, 88)
RGFX_WIRE_SIZE(RgfxIcbCreate, 88)
RGFX_WIRE_SIZE(RgfxIcbDispatch, 24)
RGFX_WIRE_SIZE(RgfxIcbDraw, 24)
RGFX_WIRE_SIZE(RgfxIcbDrawIndexed, 40)
RGFX_WIRE_SIZE(RgfxIcbDrawIndexedPatches, 72)
RGFX_WIRE_SIZE(RgfxIcbDrawPatches, 56)
RGFX_WIRE_SIZE(RgfxIcbImageblock, 8)
RGFX_WIRE_SIZE(RgfxIcbObject, 8)
RGFX_WIRE_SIZE(RgfxIcbRange, 8)
RGFX_WIRE_SIZE(RgfxIcbRecord, 8)
RGFX_WIRE_SIZE(RgfxIcbRegion, 24)
RGFX_WIRE_SIZE(RgfxIcbRenderSlot, 104)
RGFX_WIRE_SIZE(RgfxIcbSlotBuffer, 24)
RGFX_WIRE_SIZE(RgfxIcbSlotPagesRun, 48)
RGFX_WIRE_SIZE(RgfxIcbSlotRun, 32)
RGFX_WIRE_SIZE(RgfxIcbSlots, 32)
RGFX_WIRE_SIZE(RgfxIcbState, 32)
RGFX_WIRE_SIZE(RgfxIcbThreadgroupMemory, 8)
RGFX_WIRE_SIZE(RgfxIcbWrite, 24)
RGFX_WIRE_SIZE(RgfxLibraryCreate, 72)
RGFX_WIRE_SIZE(RgfxLibraryFromRegion, 112)
RGFX_WIRE_SIZE(RgfxLibraryLookup, 64)
RGFX_WIRE_SIZE(RgfxLinearTextureFromBuffer, 112)
RGFX_WIRE_SIZE(RgfxLinkedFunction, 48)
RGFX_WIRE_SIZE(RgfxManagedBufferCreate, 56)
RGFX_WIRE_SIZE(RgfxManagedBufferZero, 8)
RGFX_WIRE_SIZE(RgfxManagedTextureCreate, 112)
RGFX_WIRE_SIZE(RgfxMeshPipelineReflection, 24)
RGFX_WIRE_SIZE(RgfxMeshRenderPipelineCreate, 512)
RGFX_WIRE_SIZE(RgfxModeEntry, 12)
RGFX_WIRE_SIZE(RgfxMoveCursor, 32)
RGFX_WIRE_SIZE(RgfxMsgHeader, 16)
RGFX_WIRE_SIZE(RgfxObjectCreate, 24)
RGFX_WIRE_SIZE(RgfxObjectDestroy, 24)
RGFX_WIRE_SIZE(RgfxOpDispatchThreadsPerTile, 24)
RGFX_WIRE_SIZE(RgfxOpDispatchThreadsPerTileInRegion, 72)
RGFX_WIRE_SIZE(RgfxOpDispatchThreadsPerTileInRegionIndex, 80)
RGFX_WIRE_SIZE(RgfxOpDrawIndexedPatches, 72)
RGFX_WIRE_SIZE(RgfxOpDrawIndexedPatchesIndirect, 56)
RGFX_WIRE_SIZE(RgfxOpDrawIndexedPrimitives, 40)
RGFX_WIRE_SIZE(RgfxOpDrawIndexedPrimitivesBase, 64)
RGFX_WIRE_SIZE(RgfxOpDrawIndexedPrimitivesIndirect, 48)
RGFX_WIRE_SIZE(RgfxOpDrawIndexedPrimitivesInstances, 48)
RGFX_WIRE_SIZE(RgfxOpDrawMeshThreadgroups, 72)
RGFX_WIRE_SIZE(RgfxOpDrawMeshThreadgroupsIndirect, 64)
RGFX_WIRE_SIZE(RgfxOpDrawMeshThreads, 72)
RGFX_WIRE_SIZE(RgfxOpDrawPatches, 56)
RGFX_WIRE_SIZE(RgfxOpDrawPatchesIndirect, 40)
RGFX_WIRE_SIZE(RgfxOpDrawPrimitives, 24)
RGFX_WIRE_SIZE(RgfxOpDrawPrimitivesBase, 40)
RGFX_WIRE_SIZE(RgfxOpDrawPrimitivesIndirect, 24)
RGFX_WIRE_SIZE(RgfxOpDrawPrimitivesInstances, 32)
RGFX_WIRE_SIZE(RgfxOpEvent, 16)
RGFX_WIRE_SIZE(RgfxOpExecuteCommandsInBuffer, 24)
RGFX_WIRE_SIZE(RgfxOpExecuteCommandsIndirect, 24)
RGFX_WIRE_SIZE(RgfxOpGuestTimes, 24)
RGFX_WIRE_SIZE(RgfxOpHeader, 8)
RGFX_WIRE_SIZE(RgfxOpMemoryBarrierWithScope, 24)
RGFX_WIRE_SIZE(RgfxOpQueueBarrier, 16)
RGFX_WIRE_SIZE(RgfxOpSetAlphaTestReferenceValue, 8)
RGFX_WIRE_SIZE(RgfxOpSetBlendColorRed, 16)
RGFX_WIRE_SIZE(RgfxOpSetColorResolveTexture, 48)
RGFX_WIRE_SIZE(RgfxOpSetColorStoreAction, 16)
RGFX_WIRE_SIZE(RgfxOpSetColorStoreActionOptions, 16)
RGFX_WIRE_SIZE(RgfxOpSetCullMode, 8)
RGFX_WIRE_SIZE(RgfxOpSetDepthBias, 16)
RGFX_WIRE_SIZE(RgfxOpSetDepthClipModeSpi, 8)
RGFX_WIRE_SIZE(RgfxOpSetDepthResolveTexture, 40)
RGFX_WIRE_SIZE(RgfxOpSetDepthStencilState, 8)
RGFX_WIRE_SIZE(RgfxOpSetDepthStoreAction, 8)
RGFX_WIRE_SIZE(RgfxOpSetDepthStoreActionOptions, 8)
RGFX_WIRE_SIZE(RgfxOpSetFragmentBuffer, 24)
RGFX_WIRE_SIZE(RgfxOpSetFragmentBufferOffset, 16)
RGFX_WIRE_SIZE(RgfxOpSetFragmentBuffers, 16)
RGFX_WIRE_SIZE(RgfxOpSetFragmentSamplerStates, 16)
RGFX_WIRE_SIZE(RgfxOpSetFragmentSamplerStatesLodClamps, 16)
RGFX_WIRE_SIZE(RgfxOpSetFragmentTexture, 16)
RGFX_WIRE_SIZE(RgfxOpSetFragmentTextures, 16)
RGFX_WIRE_SIZE(RgfxOpSetFrontFacingWinding, 8)
RGFX_WIRE_SIZE(RgfxOpSetLineWidth, 8)
RGFX_WIRE_SIZE(RgfxOpSetMeshBufferOffset, 16)
RGFX_WIRE_SIZE(RgfxOpSetMeshBuffers, 16)
RGFX_WIRE_SIZE(RgfxOpSetMeshSamplerStates, 16)
RGFX_WIRE_SIZE(RgfxOpSetMeshSamplerStatesLodClamps, 16)
RGFX_WIRE_SIZE(RgfxOpSetMeshTextures, 16)
RGFX_WIRE_SIZE(RgfxOpSetObjectBufferOffset, 16)
RGFX_WIRE_SIZE(RgfxOpSetObjectBuffers, 16)
RGFX_WIRE_SIZE(RgfxOpSetObjectSamplerStates, 16)
RGFX_WIRE_SIZE(RgfxOpSetObjectSamplerStatesLodClamps, 16)
RGFX_WIRE_SIZE(RgfxOpSetObjectTextures, 16)
RGFX_WIRE_SIZE(RgfxOpSetObjectThreadgroupMemoryLength, 16)
RGFX_WIRE_SIZE(RgfxOpSetPointSize, 8)
RGFX_WIRE_SIZE(RgfxOpSetPrimitiveRestartEnabled, 16)
RGFX_WIRE_SIZE(RgfxOpSetProvokingVertexMode, 8)
RGFX_WIRE_SIZE(RgfxOpSetRenderPipelineState, 8)
RGFX_WIRE_SIZE(RgfxOpSetScissorRect, 32)
RGFX_WIRE_SIZE(RgfxOpSetScissorRects, 8)
RGFX_WIRE_SIZE(RgfxOpSetStencilFrontReferenceValue, 8)
RGFX_WIRE_SIZE(RgfxOpSetStencilResolveTexture, 40)
RGFX_WIRE_SIZE(RgfxOpSetStencilStoreAction, 8)
RGFX_WIRE_SIZE(RgfxOpSetStencilStoreActionOptions, 8)
RGFX_WIRE_SIZE(RgfxOpSetTessellationFactorBuffer, 24)
RGFX_WIRE_SIZE(RgfxOpSetTessellationFactorScale, 8)
RGFX_WIRE_SIZE(RgfxOpSetThreadgroupMemoryLength, 24)
RGFX_WIRE_SIZE(RgfxOpSetTileBufferOffset, 16)
RGFX_WIRE_SIZE(RgfxOpSetTileBuffers, 16)
RGFX_WIRE_SIZE(RgfxOpSetTileSamplerStates, 16)
RGFX_WIRE_SIZE(RgfxOpSetTileSamplerStatesLodClamps, 16)
RGFX_WIRE_SIZE(RgfxOpSetTileTextures, 16)
RGFX_WIRE_SIZE(RgfxOpSetTriangleFillMode, 8)
RGFX_WIRE_SIZE(RgfxOpSetVertexAmplificationCount, 8)
RGFX_WIRE_SIZE(RgfxOpSetVertexAmplificationMode, 16)
RGFX_WIRE_SIZE(RgfxOpSetVertexBuffer, 24)
RGFX_WIRE_SIZE(RgfxOpSetVertexBufferOffset, 16)
RGFX_WIRE_SIZE(RgfxOpSetVertexBufferOffsetAttributeStride, 24)
RGFX_WIRE_SIZE(RgfxOpSetVertexBuffers, 16)
RGFX_WIRE_SIZE(RgfxOpSetVertexBuffersAttributeStrides, 16)
RGFX_WIRE_SIZE(RgfxOpSetVertexSamplerStates, 16)
RGFX_WIRE_SIZE(RgfxOpSetVertexSamplerStatesLodClamps, 16)
RGFX_WIRE_SIZE(RgfxOpSetVertexTextures, 16)
RGFX_WIRE_SIZE(RgfxOpSetViewport, 48)
RGFX_WIRE_SIZE(RgfxOpSetViewportTransformEnabled, 8)
RGFX_WIRE_SIZE(RgfxOpSetViewports, 8)
RGFX_WIRE_SIZE(RgfxOpSetVisibilityResultMode, 16)
RGFX_WIRE_SIZE(RgfxOpSurfaceUse, 24)
RGFX_WIRE_SIZE(RgfxOpUpdateFence, 16)
RGFX_WIRE_SIZE(RgfxOpUseHeaps, 8)
RGFX_WIRE_SIZE(RgfxOpUseHeapsStages, 16)
RGFX_WIRE_SIZE(RgfxOpUseResources, 16)
RGFX_WIRE_SIZE(RgfxOpUseResourcesStages, 24)
RGFX_WIRE_SIZE(RgfxOpVideoPass, 8)
RGFX_WIRE_SIZE(RgfxOpWaitForFence, 16)
RGFX_WIRE_SIZE(RgfxPageRun, 16)
RGFX_WIRE_SIZE(RgfxPagesAnswer, 32)
RGFX_WIRE_SIZE(RgfxPagesBufferAddress, 24)
RGFX_WIRE_SIZE(RgfxPipelineAnswersQuery, 24)
RGFX_WIRE_SIZE(RgfxPipelineLibrary, 16)
RGFX_WIRE_SIZE(RgfxPipelineReflection, 80)
RGFX_WIRE_SIZE(RgfxPointerLook, 24)
RGFX_WIRE_SIZE(RgfxPointerMotion, 32)
RGFX_WIRE_SIZE(RgfxPointerOver, 32)
RGFX_WIRE_SIZE(RgfxPoolBlock, 48)
RGFX_WIRE_SIZE(RgfxPoolGive, 40)
RGFX_WIRE_SIZE(RgfxPoolTake, 32)
RGFX_WIRE_SIZE(RgfxPresentSurface, 32)
RGFX_WIRE_SIZE(RgfxPresentSurfaceGen, 8)
RGFX_WIRE_SIZE(RgfxPrivateBlock, 40)
RGFX_WIRE_SIZE(RgfxPrivateGive, 40)
RGFX_WIRE_SIZE(RgfxPrivateTake, 32)
RGFX_WIRE_SIZE(RgfxQueueCreate, 56)
RGFX_WIRE_SIZE(RgfxQueueCreateFlags, 8)
RGFX_WIRE_SIZE(RgfxRateMapAnswer, 48)
RGFX_WIRE_SIZE(RgfxRateMapCreate, 64)
RGFX_WIRE_SIZE(RgfxRateMapLayer, 16)
RGFX_WIRE_SIZE(RgfxRateMapQuery, 56)
RGFX_WIRE_SIZE(RgfxRateMapState, 104)
RGFX_WIRE_SIZE(RgfxRenderPassColorAttachment, 88)
RGFX_WIRE_SIZE(RgfxRenderPassDepthAttachment, 64)
RGFX_WIRE_SIZE(RgfxRenderPassDesc, 152)
RGFX_WIRE_SIZE(RgfxRenderPassRateMap, 8)
RGFX_WIRE_SIZE(RgfxRenderPassSamplePositions, 136)
RGFX_WIRE_SIZE(RgfxRenderPassStencilAttachment, 64)
RGFX_WIRE_SIZE(RgfxRenderPassVisibility, 16)
RGFX_WIRE_SIZE(RgfxRenderPipelineCreate, 496)
RGFX_WIRE_SIZE(RgfxRenderPipelinePrivateState, 24)
RGFX_WIRE_SIZE(RgfxResourceBinding, 16)
RGFX_WIRE_SIZE(RgfxResourceIdChunk, 24)
RGFX_WIRE_SIZE(RgfxRingHeader, 256)
RGFX_WIRE_SIZE(RgfxSamplerBinding, 8)
RGFX_WIRE_SIZE(RgfxSamplerCreate, 72)
RGFX_WIRE_SIZE(RgfxSamplerCreateExt, 8)
RGFX_WIRE_SIZE(RgfxSamplerLodBinding, 16)
RGFX_WIRE_SIZE(RgfxSamplerState, 32)
RGFX_WIRE_SIZE(RgfxScheduledAsk, 32)
RGFX_WIRE_SIZE(RgfxScissorRectElem, 32)
RGFX_WIRE_SIZE(RgfxScroll, 32)
RGFX_WIRE_SIZE(RgfxScrollDevices, 24)
RGFX_WIRE_SIZE(RgfxSetCursor, 48)
RGFX_WIRE_SIZE(RgfxSetDisplayPower, 24)
RGFX_WIRE_SIZE(RgfxSetScanout, 40)
RGFX_WIRE_SIZE(RgfxSetVblank, 24)
RGFX_WIRE_SIZE(RgfxSharedEventCreate, 32)
RGFX_WIRE_SIZE(RgfxSharedEventImport, 40)
RGFX_WIRE_SIZE(RgfxSharedEventName, 40)
RGFX_WIRE_SIZE(RgfxSharedEventSetValue, 32)
RGFX_WIRE_SIZE(RgfxSharedEventUnname, 32)
RGFX_WIRE_SIZE(RgfxSharedEventValue, 32)
RGFX_WIRE_SIZE(RgfxSharedTexture, 72)
RGFX_WIRE_SIZE(RgfxSharedTextureCreate, 80)
RGFX_WIRE_SIZE(RgfxSharedTextureImport, 40)
RGFX_WIRE_SIZE(RgfxSharedTextureName, 32)
RGFX_WIRE_SIZE(RgfxSharedTextureUnname, 32)
RGFX_WIRE_SIZE(RgfxSizeAndAlign, 40)
RGFX_WIRE_SIZE(RgfxStencilDescriptor, 24)
RGFX_WIRE_SIZE(RgfxSurfaceDownload, 24)
RGFX_WIRE_SIZE(RgfxSurfaceFacts, 40)
RGFX_WIRE_SIZE(RgfxSurfaceHoldLowered, 24)
RGFX_WIRE_SIZE(RgfxSurfaceOrderWait, 16)
RGFX_WIRE_SIZE(RgfxSurfacePages, 56)
RGFX_WIRE_SIZE(RgfxSurfacePagesCache, 8)
RGFX_WIRE_SIZE(RgfxSurfacePagesLayout, 136)
RGFX_WIRE_SIZE(RgfxSurfacePlaneLayout, 32)
RGFX_WIRE_SIZE(RgfxSurfaceWriter, 16)
RGFX_WIRE_SIZE(RgfxSurfaceWriters, 64)
RGFX_WIRE_SIZE(RgfxTextureBinding, 8)
RGFX_WIRE_SIZE(RgfxTextureCreate, 104)
RGFX_WIRE_SIZE(RgfxTextureDescriptor, 48)
RGFX_WIRE_SIZE(RgfxTextureDidModifyData, 24)
RGFX_WIRE_SIZE(RgfxTextureFromBuffer, 104)
RGFX_WIRE_SIZE(RgfxTextureFromIOSurface, 120)
RGFX_WIRE_SIZE(RgfxTextureReplaceRegion, 56)
RGFX_WIRE_SIZE(RgfxTextureView, 72)
RGFX_WIRE_SIZE(RgfxUploadWritten, 16)
RGFX_WIRE_SIZE(RgfxVblank, 40)
RGFX_WIRE_SIZE(RgfxVertexAttribute, 16)
RGFX_WIRE_SIZE(RgfxVertexBufferLayout, 16)
RGFX_WIRE_SIZE(RgfxVideoCaps, 1552)
RGFX_WIRE_SIZE(RgfxVideoCodecCaps, 48)
RGFX_WIRE_SIZE(RgfxVideoDecodeCaps, 16)
RGFX_WIRE_SIZE(RgfxVideoEncodeCaps, 16)
RGFX_WIRE_SIZE(RgfxVideoEncodeResult, 32)
RGFX_WIRE_SIZE(RgfxVideoEncodeSettings, 96)
RGFX_WIRE_SIZE(RgfxVideoOpDecodeH264, 48)
RGFX_WIRE_SIZE(RgfxVideoOpDecodeH265, 48)
RGFX_WIRE_SIZE(RgfxVideoOpEncode, 72)
RGFX_WIRE_SIZE(RgfxVideoOutputLayout, 16)
RGFX_WIRE_SIZE(RgfxVideoSessionCreate, 32)
RGFX_WIRE_SIZE(RgfxViewMapping, 8)
RGFX_WIRE_SIZE(RgfxViewportElem, 48)
RGFX_WIRE_SIZE(RgfxVtHostMessage, 24)
RGFX_WIRE_SIZE(RgfxVtMessage, 72)
RGFX_WIRE_SIZE(RgfxVtRing, 24)
RGFX_WIRE_SIZE(RgfxVtStatus, 24)
RGFX_WIRE_SIZE(RgfxVtSurface, 88)
RGFX_WIRE_SIZE(RgfxVtSurfacePlane, 24)
#endif
#ifdef RGFX_WIRE_REGISTER
RGFX_WIRE_REGISTER(RGFX_REG_MAGIC, 0x000)
RGFX_WIRE_REGISTER(RGFX_REG_VERSION, 0x004)
RGFX_WIRE_REGISTER(RGFX_REG_FEATURES_LO, 0x008)
RGFX_WIRE_REGISTER(RGFX_REG_FEATURES_HI, 0x00c)
RGFX_WIRE_REGISTER(RGFX_REG_STATUS, 0x010)
RGFX_WIRE_REGISTER(RGFX_REG_REGION_SIZE_LO, 0x014)
RGFX_WIRE_REGISTER(RGFX_REG_REGION_SIZE_HI, 0x018)
RGFX_WIRE_REGISTER(RGFX_REG_DOORBELL, 0x020)
RGFX_WIRE_REGISTER(RGFX_REG_DRIVER_FEATURES_LO, 0x024)
RGFX_WIRE_REGISTER(RGFX_REG_DRIVER_FEATURES_HI, 0x028)
RGFX_WIRE_REGISTER(RGFX_REG_CONSUMED, 0x02c)
RGFX_WIRE_REGISTER(RGFX_REG_DEFERRED_BUDGET_LO, 0x030)
RGFX_WIRE_REGISTER(RGFX_REG_DEFERRED_BUDGET_HI, 0x034)
RGFX_WIRE_REGISTER(RGFX_REG_HOST_TIME_LO, 0x038)
RGFX_WIRE_REGISTER(RGFX_REG_HOST_TIME_HI, 0x03c)
RGFX_WIRE_REGISTER(RGFX_REG_DOORBELL_PAGE_BIND, 0x040)
RGFX_WIRE_REGISTER(RGFX_REG_POOL_BASE_LO, 0x044)
RGFX_WIRE_REGISTER(RGFX_REG_POOL_BASE_HI, 0x048)
RGFX_WIRE_REGISTER(RGFX_REG_POOL_LENGTH_LO, 0x04c)
RGFX_WIRE_REGISTER(RGFX_REG_POOL_LENGTH_HI, 0x050)
RGFX_WIRE_REGISTER(RGFX_REG_GUEST_BUNDLE, 0x054)
RGFX_WIRE_REGISTER(RGFX_REG_FEATURES_EXT, 0x058)
RGFX_WIRE_REGISTER(RGFX_REG_DRIVER_FEATURES_EXT, 0x05c)
#endif
+44 -21
View File
@@ -11,7 +11,7 @@ use zerocopy::{FromBytes, IntoBytes};
use crate::device::{CursorShape, Shared};
use crate::display::cursor_color::CursorColor;
use crate::display::{CursorImage, Scanout, straight_rgba};
use crate::display::{CursorImage, Scanout, offered_modes, straight_rgba};
use crate::ring::{Message, set_size, sized};
use crate::wire::*;
@@ -32,11 +32,12 @@ pub(crate) fn answer(shared: &Shared, message: &Message) -> Option<Vec<u8>> {
&& let Some(display) = shared.seen_display(command.display)
{
// The device knows first, so a window the move reaches asks it of a cursor
// shown or hidden already.
shared.cursor_visible(command.display, command.visible != 0);
display
.screen
.cursor_moved(command.x, command.y, command.visible != 0);
// shown or hidden already. A move of a cursor hidden already, which shows
// nothing, is the device's alone (`Shared::cursor_visible`).
let visible = command.visible != 0;
if !shared.cursor_visible(command.display, command.x, command.y, visible) {
display.screen.cursor_moved(command.x, command.y, visible);
}
if command.visible != 0 {
shared.cursor_shown_on(command.display, command.x, command.y);
}
@@ -59,6 +60,12 @@ pub(crate) fn answer(shared: &Shared, message: &Message) -> Option<Vec<u8>> {
}
return None;
}
RGFX_CMD_HIDDEN_PLACES => {
if let Some(command) = read::<RgfxHiddenPlaces>(message) {
shared.hidden_places(command.reports != 0);
}
return None;
}
RGFX_CMD_SET_VBLANK => read(message).map_or(RGFX_STATUS_INVALID_ARGUMENT, |command| {
set_vblank(shared, &command)
}),
@@ -186,7 +193,9 @@ fn lifecycle(shared: &Shared, message: &Message, epoch: u64) -> Option<Vec<u8>>
}
RGFX_CMD_VT_MESSAGE => {
// A guest that took no VT_MESSAGES sends none; one it sends anyway is answered as
// one the device could not read, as is one whose runs or length do not hold.
// one the device could not read, as is one whose runs or length do not hold. The
// lends such a message names go back first, where the guest took VT_MESSAGES: the
// kext holds each lend of a message it posted until a `rels` names it.
let read = shared
.driver_took(RGFX_FEATURE_VT_MESSAGES)
.then(|| crate::device::vt_read(message))
@@ -200,7 +209,12 @@ fn lifecycle(shared: &Shared, message: &Message, epoch: u64) -> Option<Vec<u8>>
);
None
}
None => Some(crate::device::vt_status(seqno, RGFX_VT_STATUS_MALFORMED)),
None => {
if let Some(release) = crate::device::vt_unread_release(message) {
shared.vt_link(epoch).send(&release);
}
Some(crate::device::vt_status(seqno, RGFX_VT_STATUS_MALFORMED))
}
}
}
RGFX_CMD_SURFACE_DOWNLOAD => match read::<RgfxSurfaceDownload>(message) {
@@ -378,9 +392,11 @@ pub(crate) fn complete(seqno: u64, status: u32) -> Vec<u8> {
/// `GET_DISPLAYS`' answer: each display the guest sees (`Shared::displays_seen`: display 0
/// alone where it did not take [`RGFX_FEATURE_MULTI_DISPLAY`]), in order of id, connected, with
/// the mode it offers (`Shared::offered_mode`) as its one mode, which it prefers, and, where the
/// guest took [`RGFX_FEATURE_DISPLAY_SCALE`], its screen's scale between the display's record and
/// its mode. The guest is told each display's mode from now on (`device`'s refresh).
/// the modes it offers ([`offered_modes`]): first the mode `Shared::offered_mode` gives, which it
/// prefers, then its smaller modes; and, where the guest took [`RGFX_FEATURE_DISPLAY_SCALE`], its
/// screen's scale between the display's record and its modes. The record's count is the modes
/// that follow it. The guest is told each display's first mode from now on (`device`'s
/// refresh), which the smaller modes follow.
fn displays(shared: &Shared, seqno: u64) -> Vec<u8> {
let seen = shared.displays_seen();
let mut bytes = RgfxMsgHeader {
@@ -392,28 +408,35 @@ fn displays(shared: &Shared, seqno: u64) -> Vec<u8> {
.to_vec();
bytes.extend_from_slice(&seen.to_le_bytes());
for (id, display) in (0..seen).zip(shared.displays.iter()) {
let mode = shared.offered_mode(display);
display.state.lock().told = Some(mode);
let modes = offered_modes(display.screen.mode(), shared.display_count());
let first = modes[0];
display.state.lock().told = Some(first);
let mut records = Vec::new();
let mut mode_count = 0;
for mode in &modes {
let record = RgfxModeEntry {
width: mode.width,
height: mode.height,
refresh_mhz: mode.refresh_mhz,
};
records.extend_from_slice(record.as_bytes());
mode_count += 1;
}
let entry = RgfxDisplayEntry {
id,
connected: 1,
preferred_mode: 0,
mode_count: 1,
mode_count,
};
bytes.extend_from_slice(entry.as_bytes());
if shared.driver_took(RGFX_FEATURE_DISPLAY_SCALE) {
let scale = RgfxDisplayScale {
scale_120ths: mode.scale_120ths,
scale_120ths: first.scale_120ths,
reserved_4: 0,
};
bytes.extend_from_slice(scale.as_bytes());
}
let mode = RgfxModeEntry {
width: mode.width,
height: mode.height,
refresh_mhz: mode.refresh_mhz,
};
bytes.extend_from_slice(mode.as_bytes());
bytes.extend_from_slice(&records);
}
bytes.resize(bytes.len().next_multiple_of(8), 0);
set_size(&mut bytes);
+479 -76
View File
@@ -82,14 +82,17 @@
//! with no lock held that a call of the device's waits for, directly or through a thread of the
//! device's ([`Host`]), so a callback may call the device at once, and may wait for something the
//! host holds while it calls the device (QEMU's BQL). [`Device::mmio_write`]'s reset waits only
//! for the message the control thread is taking, which never waits for the host. A completion
//! for the message the control thread is taking, which never waits for the host, and for the
//! host's settle ([`Host::reset_settles`]), which waits for no thread of the device's, and which a
//! reset made inside the device's raise does not ask for. A completion
//! record a thread that may not raise hands over ([`CompletionPoster::post_elsewhere`]), and one a
//! thread that may not wait finds no room for, or finds records handed over before
//! ([`CompletionPoster::post_unwaiting`]), is posted, and raised for, by its queue's service thread,
//! or by the next thread of the device's that posts onto that ring, which posts it first. A
//! command's answer the host gives off the control thread ([`CompleteAnswer::answer`]) waits for no
//! room either: one the control completion ring has no room for, or that finds answers handed over
//! before it, is posted by the control thread, ahead of its own posts.
//! room either: one the control completion ring has no room for, that finds answers handed over
//! before it, or that is given where its thread may not raise ([`raise_elsewhere`]), is posted by
//! the control thread, ahead of its own posts.
//!
//! **An answer on the doorbell's thread.** A `DOORBELL` write of a command queue's ring through
//! [`Device::mmio_write_taking`] offers the queue's next `COMMAND_BUFFER` to the host on the
@@ -161,7 +164,8 @@
//!
//! The device's functions a host calls under its lock wait at most for ring 0's message the
//! control thread holds (a display message, which waits for no thread of the device's), for a
//! take of a queue's ring or a post onto one under way, and, in a reset, for the queues' table:
//! take of a queue's ring or a post onto one under way, and, in a reset, for the queues' table and
//! for the host's settle ([`Host::reset_settles`]), which waits for no thread of the device's:
//! none of these is held across a route call, and none waits for a lane. The release of the
//! process's last device waits for the device's threads, a route call among them, at most 5 s
//! (docs/api.md, "The process's exit"). Tested by
@@ -205,7 +209,10 @@
//! it has returned; a lane's message not yet begun is dropped). Nothing begun before the reset
//! reaches
//! the guest after it: its answers and events are dropped, and a queue made before it hands the
//! host nothing more, not even its own destroy, which the host's reset stands for.
//! host nothing more, not even its own destroy, which the host's reset stands for. Last, on the
//! thread that resets, the host waits for the guest's work it committed to the GPU before the
//! reset ([`Host::reset_settles`]), so none of it writes the guest's memory after the reset
//! returns, as a GPU's reset stops its DMA.
//! What the guest wrote in its allocations stays.
//!
//! **The scanout across a reset.** A reset leaves the display's scanout as the last `SET_SCANOUT`
@@ -248,16 +255,20 @@ use crate::ring::{Consumer, Message, Posted, Producer, RingAt, sized};
use crate::trip;
use crate::wake::{self, Doorbell, RawDoorbell, Wake};
use crate::wire::*;
pub use guest_drivers::GuestBundle;
mod backlog;
mod desktop;
mod gate;
mod guest_drivers;
mod guest_times;
mod lanes;
mod vt;
pub use vt::{VtAnswer, VtLink, VtMessage, VtSurface};
pub(crate) use vt::{read_message as vt_read, vt_status};
pub(crate) use vt::{
read_message as vt_read, unread_lends_release as vt_unread_release, vt_status,
};
/// How many of ring 0's messages a doorbell's take reads ([`Backlog::read`]) before it leaves the
/// buffer to its queue's thread.
@@ -346,6 +357,10 @@ impl Room {
/// ring.
const MIN_QUEUE_RING_DATA: u64 = 4096;
/// The feature bits 64 to 95 a `DRIVER_FEATURES_EXT` write may take, of those `FEATURES_EXT`
/// offers: the `RGFX_FEATURE_EXT_*` that are taken, where the others are used with no take.
pub(crate) const TAKEN_EXT_FEATURES: u32 = RGFX_FEATURE_EXT_SURFACE_HOLD;
/// The feature bits whose meaning the host knows, which a `DRIVER_FEATURES` write may take:
/// `RGFX_FEATURE_*`, bits 0 to 9 and 11 to 63.
const KNOWN_FEATURES: u64 = (RGFX_FEATURE_SURFACE_PAGES
@@ -519,13 +534,14 @@ pub trait Host: Send + Sync + 'static {
fn pool_taken(&self) {}
/// The guest's driver wrote `STATUS` `DRIVER_READY`: `taken` is the feature bits it took
/// (`DRIVER_FEATURES`), which hold from now to the next reset, for the host's decoder to
/// carry out those whose messages it reads differently where they are taken
/// ([`RGFX_FEATURE_MANAGED_AT_COPY`]). Called on the writing thread, inside the write, before
/// (`DRIVER_FEATURES`), and `taken_ext` those of bits 64 to 95 (`DRIVER_FEATURES_EXT`), which
/// hold from now to the next reset, for the host's decoder to carry out those whose messages
/// it reads differently where they are taken ([`RGFX_FEATURE_MANAGED_AT_COPY`],
/// [`RGFX_FEATURE_EXT_SURFACE_HOLD`]). Called on the writing thread, inside the write, before
/// the device takes any message after it, at each write that makes the driver ready: once a
/// boot, and again after a reset. It waits for nothing. The default does nothing.
fn driver_ready(&self, taken: u64) {
let _ = taken;
fn driver_ready(&self, taken: u64, taken_ext: u32) {
let _ = (taken, taken_ext);
}
/// `POOL_TAKE`, where the guest took [`RGFX_FEATURE_POOL`]: context `take.context` asks for a
@@ -597,6 +613,19 @@ pub trait Host: Send + Sync + 'static {
/// nothing, for a host with no stage-3 decoder.
fn device_reset(&self) {}
/// The device was reset ([`Device::reset`], or the guest's `STATUS` 0): before the reset
/// returns, the host waits until none of the guest's work it committed to the GPU before the
/// reset can write the guest's memory any more, as a GPU's reset stops its DMA. Called on the
/// thread that resets the device, last, once its queues have ended and their routes are
/// dropped, with no lock of the device's held; it must not wait for ring 0's threads or the
/// control thread, since the host may hold a lock around the reset that a route callback on
/// one of them waits for (QEMU's BQL). Before [`Host::device_reset`] or after it. Never for a
/// reset made inside a raise of the device's ([`Host::raise_interrupt`]) on the thread that
/// raises: the host may hold around the raise what this takes, and the work the raise is part
/// of began before the reset and ends only once the reset returns. The default does nothing,
/// for a host that commits nothing to a GPU.
fn reset_settles(&self) {}
/// The device's feature bits, which `FEATURES_LO` and `FEATURES_HI` read: the
/// `RGFX_FEATURE_*` the host carries out. The default is none, for a host with no stage-3
/// decoder.
@@ -604,6 +633,14 @@ pub trait Host: Send + Sync + 'static {
0
}
/// The feature bits 64 to 95 the host carries out, which `FEATURES_EXT` reads: the
/// `RGFX_FEATURE_EXT_*` a guest uses with no take, and those it takes in
/// `DRIVER_FEATURES_EXT` ([`TAKEN_EXT_FEATURES`]). The default is none, for a host with no
/// stage-3 decoder.
fn features_ext(&self) -> u32 {
0
}
/// The feature bits the host offers only to a guest whose driver took
/// [`RGFX_FEATURE_PAGES_16K`], which [`Host::features`] then offers: from the
/// `DRIVER_FEATURES` write that takes it to the next reset, `FEATURES_LO` and `_HI` read them
@@ -962,6 +999,21 @@ pub trait Host: Send + Sync + 'static {
fn answer_slow(&self, kind: u32, took_ns: u64) {
let _ = (kind, took_ns);
}
/// A driver of the guest read `VERSION` while the device was started (`STATUS` 1, as the
/// option ROM or Ambrosia's module leaves it), and read or wrote no other register in the 60 s
/// after: it left the device at its version check, as a kext of another wire version does, so
/// the guest runs on the firmware's framebuffer, without Metal (docs/graphics-kext/design.md,
/// "The guest's bundle, told to the host"). Called at most once a reset, on display 0's
/// refresh thread. The default does nothing.
fn guest_driver_left(&self) {}
/// The guest's accelerator wrote `GUEST_BUNDLE`: what it found of its Metal bundle as
/// WindowServer opened the display, and RgfxGate's install pass, once a boot. Called on the
/// writing thread, inside the write; it waits for nothing. The default does nothing.
fn guest_bundle(&self, bundle: GuestBundle) {
let _ = bundle;
}
}
/// How long after its make a ring-0 answer given through a [`CompleteAnswer`], a [`PoolAnswer`] or
@@ -1096,12 +1148,17 @@ pub(crate) struct Shared {
/// `DRIVER_FEATURES`: the feature bits the guest's driver took, each one the host offers and
/// knows ([`KNOWN_FEATURES`]); 0 from a reset to the driver's write.
driver_features: AtomicU64,
/// `DRIVER_FEATURES_EXT`: the feature bits 64 to 95 the guest's driver took, each one the host
/// offers that is taken ([`TAKEN_EXT_FEATURES`]); 0 from a reset to the driver's write.
driver_features_ext: AtomicU32,
/// Moved on at each reset: work begun before one drops what it would send.
epoch: AtomicU64,
/// A reset the host has not been told of yet ([`Host::device_reset`]): set with the control
/// submission ring held, so the control thread sees it before any message published after
/// the reset.
reset_owed: AtomicBool,
/// A driver that leaves the device at `VERSION` ([`Host::guest_driver_left`]).
version_watch: guest_drivers::VersionWatch,
/// Set at the device's end.
ending: AtomicBool,
/// Set while quiesced for checkpointing.
@@ -1214,6 +1271,9 @@ struct Queues {
by_obj: HashMap<u64, Arc<QueueShared>>,
/// By the queue's ring id (its submission ring's region offset).
by_ring: HashMap<u64, Arc<QueueShared>>,
/// Every queue whose service thread has not yet handed its `OBJECT_DESTROY`, ended ones
/// among them: a `CONTEXT_CLOSE` marks those of its context ([`QueueShared::context_closed`]).
serving: Vec<Arc<QueueShared>>,
}
impl Queues {
@@ -1260,6 +1320,30 @@ const CROSSING_HOLD_NS: u64 = 1_000_000_000;
/// a64ptr, potluck jobs m3-max-36283, m3-max-36434 and m3-max-36435).
const CROSSING_HIDE_NS: u64 = 1_000_000_000;
/// How often, at most, the device sends `POINTER_LOOK` in one hide ([`Shared::look_at_hidden`]),
/// in nanoseconds: the guest looks for 150 ms after each, so a tablet that keeps moving keeps it
/// looking.
const LOOK_EVERY_NS: u64 = 50_000_000;
/// What the hidden cursor of a guest that reports its places ([`RGFX_CMD_HIDDEN_PLACES`]) did in
/// one hide ([`Shared::cursor_hidden_for`]). macOS hides the hardware cursor for as long as the
/// guest's screen is recorded and draws the cursor into the picture itself, and then leaves the
/// hidden cursor's place in the framebuffer's shared cursor state where it was, whatever moves
/// the cursor; while a game hides it, the tablet's positions move that place. Measured on x86-64
/// macOS 26.7.2 (lane sharecur): a game's hidden cursor, disassociated from the mouse, associated,
/// warped and on a captured display, moved under the tablet (potluck jobs m3-max-78716 and
/// m3-max-78811); a system recording's stayed where the recording hid it while the tablet and
/// the guest's mouse moved the cursor (m3-max-78811). So a hide is a game's once the guest
/// reports its hidden cursor at a new place: a `MOVE_CURSOR` of a cursor hidden already, which
/// the guest sends where it reads one after a `POINTER_LOOK`.
#[derive(Clone, Copy, Debug, Default)]
struct HiddenPlace {
/// The guest reported its hidden cursor at a new place in this hide.
followed: bool,
/// When this hide's last `POINTER_LOOK` went, on the device's clock.
looked_at: Option<u64>,
}
/// The most `POINTER_MOTION`s owed at once ([`Pointer::motion`]): each press or release makes
/// one, and motion joins the last. A guest that takes none for that long has the last take the
/// next buttons too, so that what it is sent once it takes them again ends where the host's
@@ -1268,7 +1352,7 @@ const MOTION_OWED_MAX: usize = 64;
/// What `POINTER_OVER` follows ([`Shared::pointer_at`]): the display the guest's cursor last
/// showed on, what the guest was told, the displays' places in the guest's desktop, and where a
/// captured pointer that went past its window's edge is ([`Away`]), each of one reset count. A
/// drag's pointer that went past its window's edge is ([`Away`]), each of one reset count. A
/// reset makes it new: the cursor on display 0, the guest told nothing, no display placed.
#[derive(Default)]
struct Pointer {
@@ -1291,7 +1375,7 @@ struct Pointer {
buttons: u32,
/// Each display's rectangle in the guest's desktop, as its last `DISPLAY_BOUNDS` gave it.
bounds: [Option<Bounds>; RGFX_DISPLAYS_MAX as usize],
/// The captured pointer gone past its window's edge, while it is.
/// A drag's pointer gone past its window's edge, while it is.
away: Option<Away>,
/// Each display's cursor as the guest's last `MOVE_CURSOR` of it left it: shown, hidden, or
/// `None` before the guest moved it ([`Shared::cursor_hidden_for`]).
@@ -1304,6 +1388,12 @@ struct Pointer {
/// Since when, on the device's clock, the guest has hidden its cursor on every display it
/// sees, while it has.
hidden_since: Option<u64>,
/// Each display's cursor's place as the guest's last `MOVE_CURSOR` of it put it.
places: [Option<(i32, i32)>; RGFX_DISPLAYS_MAX as usize],
/// Whether the guest reports where its hidden cursor goes, as its last `HIDDEN_PLACES` said.
hidden_places: bool,
/// What its hidden cursor did in this hide, where it reports that.
place: HiddenPlace,
/// The `POINTER_MOTION`s not posted yet, oldest first: one that found the ring held by
/// another thread, full, or behind answers handed over goes at the next motion or the next
/// refresh of any display ([`Shared::pointer_motion`]).
@@ -1365,7 +1455,7 @@ impl CursorShape {
}
}
/// A window's captured pointer gone past the image's edge onto the guest's desktop
/// A window's pointer, in a drag, gone past the image's edge onto the guest's desktop
/// ([`PointerLink::leave`]): where it is, and how its moves are scaled.
#[derive(Clone, Copy, Debug)]
struct Away {
@@ -1378,7 +1468,7 @@ struct Away {
on: u32,
}
/// Where a window's captured pointer is on the guest's desktop ([`PointerLink::away_moved`]): a
/// Where a drag's pointer is on the guest's desktop ([`PointerLink::away_moved`]): a
/// display, and the pixel of its scanout, which is `width` by `height`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Spot {
@@ -1439,9 +1529,22 @@ impl PointerLink {
.is_none_or(|shared| shared.pointer_at(display, x, y, buttons))
}
/// The host's pointer over display `display`'s window moved the guest's tablet: where the
/// guest reports where its hidden cursor goes (`HIDDEN_PLACES`) and hides its cursor, in a
/// hide that has yet to show its hidden cursor following the tablet, it is sent
/// `POINTER_LOOK` ([`RgfxPointerLook`]), one at most every 50 ms, so that it reads where that
/// cursor goes. Call it for each event of a window's pointer that goes on to the guest's
/// tablet, on a device of any number of displays. Waits for no other thread, and does nothing
/// once the device has ended.
pub fn tablet_moved(&self, display: u32) {
if let Some(shared) = self.shared.upgrade() {
shared.look_at_hidden(display);
}
}
/// Whether the guest's desktop puts another display past display `display`'s edge toward
/// `outward` (each of across and down -1, 0 or 1; both for the corner), at the row or column
/// of its pixel `at` of the window's `mode`: where the window's captured pointer, moving
/// of its pixel `at` of the window's `mode`: where the window's pointer, in a drag moving
/// toward its image's edge there, goes on onto that display ([`Self::leave`]). False where the
/// guest did not take [`RGFX_FEATURE_POINTER_OVER`] and [`RGFX_FEATURE_DISPLAY_BOUNDS`] or
/// gave no rectangle of the displays, and on a device of one display.
@@ -1457,7 +1560,7 @@ impl PointerLink {
.is_some_and(|shared| shared.adjoins(display, at, mode, outward))
}
/// The captured pointer of display `display`'s window, at its pixel `at` of the window's
/// The pointer, in a drag, of display `display`'s window, at its pixel `at` of the window's
/// `mode`, leaves the window for the guest's desktop, from that pixel: its moves go on there
/// ([`Self::away_moved`]) until [`Self::come_back`]. False, and nothing done, where the
/// desktop has no place for the display ([`Self::adjoins`]).
@@ -1485,7 +1588,7 @@ impl PointerLink {
/// How long, in nanoseconds, the guest has hidden its cursor on every display it sees (its
/// last `MOVE_CURSOR` of each that it moved said hidden), where it took
/// [`RGFX_FEATURE_POINTER_MOTION`]: a window's captured pointer then drives the guest's
/// [`RGFX_FEATURE_POINTER_MOTION`]: a window's pointer then drives the guest's
/// relative pointing device ([`Self::motion`]), as a game that hides the cursor reads its
/// motion. While a `POINTER_OVER` has yet to show the cursor on the pointer's display, it is
/// counted from a second after that at the earliest: the guest hides it on the display it
@@ -1589,6 +1692,12 @@ pub(crate) struct QueueShared {
route_page: AtomicU32,
/// Set when the queue is destroyed, or at a reset or the device's end.
ending: AtomicBool,
/// Whether its context's `CONTEXT_CLOSE` was carried out ([`Shared::close_context`]) before
/// its service thread handed the host its `OBJECT_DESTROY`, which the thread hands holding
/// this lock, and does not hand once it is set: the host dropped the queue with the context's
/// objects then, and a destroy handed after the close could reach the host once the kext has
/// given the context's number to another process, ending that process's queue of the same id.
context_closed: Mutex<bool>,
/// Its part of the timed trip ([`trip`]), a diagnostic.
trip: trip::Queue,
}
@@ -1873,8 +1982,10 @@ impl Device {
region,
status: AtomicU32::new(RGFX_STATUS_RESET),
driver_features: AtomicU64::new(0),
driver_features_ext: AtomicU32::new(0),
epoch: AtomicU64::new(0),
reset_owed: AtomicBool::new(false),
version_watch: guest_drivers::VersionWatch::default(),
ending: AtomicBool::new(false),
quiesced: AtomicBool::new(false),
wake: Wake::new()?,
@@ -1920,7 +2031,10 @@ impl Device {
let control = Arc::clone(&shared);
std::thread::Builder::new()
.name("reims-vgpu.graphics-control".to_owned())
.spawn(move || control.control_thread())
.spawn(move || {
crate::threads::started();
control.control_thread();
})
.ok()?;
for display in 0..shared.display_count() {
let refresh = Arc::clone(&shared);
@@ -1928,9 +2042,10 @@ impl Device {
0 => "reims-vgpu.graphics-refresh".to_owned(),
_ => format!("reims-vgpu.graphics-refresh-{display}"),
};
let started = std::thread::Builder::new()
.name(name)
.spawn(move || refresh.refresh_thread(display));
let started = std::thread::Builder::new().name(name).spawn(move || {
crate::threads::started();
refresh.refresh_thread(display);
});
if started.is_err() {
shared.end();
return None;
@@ -1962,6 +2077,13 @@ impl Device {
self.shared.queues.lock().by_obj.len()
}
/// How many queues' service threads have not yet passed their queue's `OBJECT_DESTROY`
/// ([`Queues::serving`]), ended queues' among them.
#[cfg(test)]
pub(crate) fn queues_serving(&self) -> usize {
self.shared.queues.lock().serving.len()
}
/// Whether the control thread sleeps with no wake pending ([`Wake::parked`]): it takes no lock
/// until it is woken.
#[cfg(test)]
@@ -2005,7 +2127,17 @@ impl Device {
(0, 0)
}
};
match u32::try_from(offset).unwrap_or(u32::MAX) {
let at = u32::try_from(offset).unwrap_or(u32::MAX);
match at {
RGFX_REG_MAGIC => {}
RGFX_REG_VERSION => self.shared.version_watch.version_read(
self.shared.started(),
self.shared.epoch.load(Ordering::Acquire),
now_ns(),
),
_ => self.shared.other_access(),
}
match at {
RGFX_REG_MAGIC => RGFX_MAGIC,
RGFX_REG_VERSION => RGFX_VERSION,
RGFX_REG_FEATURES_LO => (self.shared.offered() & 0xffff_ffff) as u32,
@@ -2028,6 +2160,8 @@ impl Device {
RGFX_REG_POOL_BASE_HI => (pool().0 >> 32) as u32,
RGFX_REG_POOL_LENGTH_LO => (pool().1 & 0xffff_ffff) as u32,
RGFX_REG_POOL_LENGTH_HI => (pool().1 >> 32) as u32,
RGFX_REG_FEATURES_EXT => self.shared.host.features_ext(),
RGFX_REG_DRIVER_FEATURES_EXT => self.shared.driver_features_ext.load(Ordering::Acquire),
_ => 0,
}
}
@@ -2036,20 +2170,29 @@ impl Device {
/// commands; `DRIVER_FEATURES_LO` and `_HI` take, before `STATUS` 1, the bits written that the
/// host offers and knows; `DOORBELL` with a ring's id wakes its consumer;
/// `DOORBELL_PAGE_BIND` binds a doorbell page to a context where the driver took
/// [`RGFX_FEATURE_DOORBELL_PAGES`]. Other values and offsets (`CONSUMED` among them) are
/// ignored. A reset waits for the message the control
/// thread is taking from the ring, and no write waits for the host's decoder.
/// [`RGFX_FEATURE_DOORBELL_PAGES`]; `GUEST_BUNDLE` tells the host what the accelerator found
/// of its Metal bundle ([`Host::guest_bundle`]). Other values and offsets (`CONSUMED` among
/// them) are ignored. A reset waits for the message the control thread is taking from the
/// ring, and for the host's settle of the GPU work committed before it
/// ([`Host::reset_settles`]); no write waits for the host's decoder.
pub fn mmio_write(&self, offset: u64, value: u32) {
self.shared.other_access();
match u32::try_from(offset).unwrap_or(u32::MAX) {
RGFX_REG_STATUS if value == RGFX_STATUS_RESET => self.reset(),
RGFX_REG_GUEST_BUNDLE => self
.shared
.host
.guest_bundle(GuestBundle::from_register(value)),
RGFX_REG_DRIVER_FEATURES_LO => self.shared.take_driver_features(0, value),
RGFX_REG_DRIVER_FEATURES_HI => self.shared.take_driver_features(32, value),
RGFX_REG_DRIVER_FEATURES_EXT => self.shared.take_driver_features_ext(value),
RGFX_REG_STATUS if value == RGFX_STATUS_DRIVER_READY => {
// The features are fixed from here (`take_driver_features`): the host has them
// before the first message the device takes.
if !self.shared.started() {
let taken = self.shared.driver_features.load(Ordering::Acquire);
self.shared.host.driver_ready(taken);
let taken_ext = self.shared.driver_features_ext.load(Ordering::Acquire);
self.shared.host.driver_ready(taken, taken_ext);
}
self.shared
.status
@@ -2077,7 +2220,10 @@ impl Device {
/// allocates nothing.
pub fn mmio_write_taking(&self, offset: u64, value: u32) {
match u32::try_from(offset).unwrap_or(u32::MAX) {
RGFX_REG_DOORBELL => self.shared.ring_taking(u64::from(value)),
RGFX_REG_DOORBELL => {
self.shared.other_access();
self.shared.ring_taking(u64::from(value));
}
_ => self.mmio_write(offset, value),
}
}
@@ -2110,6 +2256,14 @@ impl Device {
true
}
/// The handle the host wakes the guest's CPU locks waiting on a surface's hold word through
/// ([`HoldWaker::lowered`]).
pub fn hold_waker(&self) -> HoldWaker {
HoldWaker {
shared: Arc::downgrade(&self.shared),
}
}
/// The handle a display's window tells the guest of the host's pointer through
/// ([`PointerLink::pointer_at`]).
pub fn pointer_link(&self) -> PointerLink {
@@ -2139,11 +2293,40 @@ impl Device {
}
/// Restores device state on a freshly created device (after QEMU restored BAR2).
pub fn import_snapshot(&self, snap: &crate::snapshot::DeviceSnapshot) -> Result<(), &'static str> {
pub fn import_snapshot(
&self,
snap: &crate::snapshot::DeviceSnapshot,
) -> Result<(), &'static str> {
self.shared.import_snapshot(snap)
}
}
/// What tells the guest's CPU locks that the host lowered a cached surface's hold word they wait
/// on ([`RGFX_FEATURE_EXT_SURFACE_HOLD`]), from any library thread that makes an image in place.
#[derive(Clone)]
pub struct HoldWaker {
shared: Weak<Shared>,
}
impl HoldWaker {
/// Posts a [`RGFX_EVT_SURFACE_HOLD_LOWERED`] of the block at `block_offset` onto the control
/// completion ring, which raises its vector, waiting for nothing: where another thread posts
/// onto the ring, an answer is handed over before it, or the ring has no room, nothing is
/// posted, and the lock looks at the word again within 1 ms. Nothing where the device has
/// ended or is not started.
pub fn lowered(&self, block_offset: u64) {
let Some(shared) = self.shared.upgrade() else {
return;
};
let event = RgfxSurfaceHoldLowered {
header: event_header(RGFX_EVT_SURFACE_HOLD_LOWERED),
block_offset,
};
let epoch = shared.epoch.load(Ordering::Acquire);
let _ = shared.post_on(&sized(&event), epoch, false);
}
}
/// The `COMPLETE` a ring-0 command owes, which the host gives from any thread once it has carried
/// the command out: a `PRESENT_SURFACE` once the display shows the surface
/// ([`Host::present_surface`]), a `CONTEXT_CLOSE` and a `BLOCK_RELEASE` once the command buffers
@@ -2336,10 +2519,11 @@ impl CompleteAnswer {
/// Posts the `COMPLETE` with `status` onto the control completion ring, waiting for nothing,
/// on whichever thread gives it: the platform's that run a command buffer's handlers, where a
/// drain's or a display hold's answer is given as the buffer completes, hold up every queue's
/// work behind them while they wait. Where the ring has room and no answer is handed over
/// before it, it is posted here, and the control vector raised here; otherwise it is handed to
/// the control thread, which posts the answers in their order before its own posts, waiting
/// for room, and every post onto the ring that waits goes behind them.
/// work behind them while they wait. Where the ring has room, no answer is handed over before
/// it and the thread may raise ([`raise_elsewhere`]), it is posted here, and the control
/// vector raised here; otherwise it is handed to the control thread, which posts the answers
/// in their order before its own posts, waiting for room, and every post onto the ring that
/// waits goes behind them.
pub fn answer(self, status: u32) {
self.answer_at(status, 0);
}
@@ -2531,6 +2715,57 @@ impl CompletionPoster {
}
}
thread_local! {
/// How many [`raise_elsewhere`] scopes this thread is in.
static RAISE_ELSEWHERE: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
/// How many of the device's raises ([`Host::raise_interrupt`]) this thread is inside.
static RAISING: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
}
/// Raises `vector` through `host` ([`Host::raise_interrupt`]), this thread counted inside the
/// raise until it returns or unwinds ([`raising`]).
fn raise_through(host: &dyn Host, vector: u32) {
/// Leaves the raise, at its return or unwind.
struct Inside;
impl Drop for Inside {
fn drop(&mut self) {
RAISING.with(|depth| depth.set(depth.get().saturating_sub(1)));
}
}
RAISING.with(|depth| depth.set(depth.get().saturating_add(1)));
let _inside = Inside;
host.raise_interrupt(vector);
}
/// Whether this thread is inside a raise of the device's ([`raise_through`]): a call the host's
/// raise makes into the device runs here.
fn raising() -> bool {
RAISING.with(|depth| depth.get() != 0)
}
/// Runs `f` where this thread may not raise the device's vectors: the host's, inside a call of
/// its into the library that calls nothing of the host's back (its read of a display, its release
/// of the device), or a thread of the library's the host's raise is not named for (a window's
/// draw). An answer given inside it ([`CompleteAnswer::answer`]) is handed to the control thread,
/// which posts it and raises the control vector, as one that finds the ring full is.
pub fn raise_elsewhere<T>(f: impl FnOnce() -> T) -> T {
/// Leaves the scope, at `f`'s return or unwind.
struct Scope;
impl Drop for Scope {
fn drop(&mut self) {
RAISE_ELSEWHERE.with(|depth| depth.set(depth.get().saturating_sub(1)));
}
}
RAISE_ELSEWHERE.with(|depth| depth.set(depth.get().saturating_add(1)));
let _scope = Scope;
f()
}
/// Whether this thread may raise the device's vectors here: it is in no [`raise_elsewhere`].
fn raises_here() -> bool {
RAISE_ELSEWHERE.with(|depth| depth.get() == 0)
}
/// Whether a message of `type` on a queue's submission ring is a command buffer, which the host
/// carries out: a `COMMAND_BUFFER`, or a `COMMAND_BUFFER_IN_REGION`.
fn is_command_buffer(r#type: u32) -> bool {
@@ -2597,15 +2832,40 @@ impl Shared {
self.status.load(Ordering::Acquire) == RGFX_STATUS_DRIVER_READY
}
/// The reset (the module doc). It waits for the message the control thread is taking, and
/// for a take of a queue's ring or a post onto one under way, none of which waits for the
/// host; the host is told on the control thread ([`Self::tell_reset`]).
/// A register access other than a read of `MAGIC` or `VERSION`: a driver that read `VERSION`
/// went on ([`guest_drivers::VersionWatch`]). Where it ends a watched read, it says at info how
/// long after that read it came, which bounds [`guest_drivers::LEFT_AFTER`]'s margin.
fn other_access(&self) {
if let Some(gap) = self.version_watch.other_access(now_ns) {
log::info!(
target: "reims_vgpu_graphics",
"the guest's driver went on {} us after its read of VERSION",
gap / 1000
);
}
}
/// At `now`, on display 0's refresh: tells the host once a reset of a driver that left the
/// device at its read of `VERSION` ([`Host::guest_driver_left`]).
fn watch_version_leave(&self, now: u64) {
let epoch = self.epoch.load(Ordering::Acquire);
if self.version_watch.left(self.started(), epoch, now) {
log::info!(
target: "reims_vgpu_graphics",
"the guest's driver read VERSION and touched no other register for {} s: it left \
the device",
guest_drivers::LEFT_AFTER.as_secs()
);
self.host.guest_driver_left();
}
}
/// Wait for active graphics operations before taking a snapshot.
fn quiesce(&self) {
self.quiesced.store(true, Ordering::Release);
self.wake.wake();
let active_queues: Vec<Arc<QueueShared>> = {
self.queues.lock().by_obj.values().cloned().collect()
};
let active_queues: Vec<Arc<QueueShared>> =
{ self.queues.lock().by_obj.values().cloned().collect() };
for q in &active_queues {
q.wake.wake();
}
@@ -2630,9 +2890,8 @@ impl Shared {
fn unquiesce(&self) {
self.quiesced.store(false, Ordering::Release);
self.wake.wake();
let active_queues: Vec<Arc<QueueShared>> = {
self.queues.lock().by_obj.values().cloned().collect()
};
let active_queues: Vec<Arc<QueueShared>> =
{ self.queues.lock().by_obj.values().cloned().collect() };
for q in &active_queues {
q.wake.wake();
}
@@ -2649,7 +2908,11 @@ impl Shared {
};
let control_completion_count = self.completion.lock().produced();
let vt_ring_count = self.vt_ring.lock().produced();
let pages: Vec<u32> = self.pages.iter().map(|p| p.load(Ordering::Acquire)).collect();
let pages: Vec<u32> = self
.pages
.iter()
.map(|p| p.load(Ordering::Acquire))
.collect();
let displays: Vec<DisplaySnapshot> = self
.displays
.iter()
@@ -2689,6 +2952,7 @@ impl Shared {
DeviceSnapshot {
status,
driver_features,
driver_features_ext: self.driver_features_ext.load(Ordering::Acquire),
control_done,
control_submit_count,
control_submit_broken,
@@ -2704,9 +2968,13 @@ impl Shared {
fn import_snapshot(&self, snap: &crate::snapshot::DeviceSnapshot) -> Result<(), &'static str> {
self.quiesced.store(true, Ordering::Release);
self.region.import_blocks(&snap.region_blocks);
self.driver_features.store(snap.driver_features, Ordering::Release);
if snap.driver_features != 0 {
self.host.driver_ready(snap.driver_features);
self.driver_features
.store(snap.driver_features, Ordering::Release);
self.driver_features_ext
.store(snap.driver_features_ext, Ordering::Release);
if snap.driver_features != 0 || snap.driver_features_ext != 0 {
self.host
.driver_ready(snap.driver_features, snap.driver_features_ext);
}
let mut any_page = false;
for (dst, &val) in self.pages.iter().zip(snap.pages.iter()) {
@@ -2724,8 +2992,11 @@ impl Shared {
submit.broken = snap.control_submit_broken;
submit.backlog.clear();
}
self.control_done.store(snap.control_done, Ordering::Release);
self.completion.lock().set_count(snap.control_completion_count);
self.control_done
.store(snap.control_done, Ordering::Release);
self.completion
.lock()
.set_count(snap.control_completion_count);
self.vt_ring.lock().set_count(snap.vt_ring_count);
self.reset_owed.store(false, Ordering::Release);
for (display, ds) in self.displays.iter().zip(snap.displays.iter()) {
@@ -2795,6 +3066,7 @@ impl Shared {
route: AtomicU64::new(0),
route_page: AtomicU32::new(u32::MAX),
ending: AtomicBool::new(false),
context_closed: Mutex::new(false),
trip: trip::Queue::default(),
});
{
@@ -2813,9 +3085,13 @@ impl Shared {
Ok(())
}
/// Reset waits for the current control and queue ring operations and settles the host.
/// The host is told on the control thread ([`Self::tell_reset`]).
fn reset(&self) {
self.status.store(RGFX_STATUS_RESET, Ordering::Release);
self.driver_features.store(0, Ordering::Release);
self.driver_features_ext.store(0, Ordering::Release);
self.version_watch.reset();
// No page is any context's: the kext binds them again as its contexts open.
for page in &self.pages {
page.store(0, Ordering::Release);
@@ -2883,6 +3159,14 @@ impl Shared {
display.screen.power(true);
}
}
// Last, with no lock held: the guest's work on the host's GPU from before the reset writes
// its memory no more once this returns. Not for a reset the host's raise makes on this
// thread: the host may hold around the raise what its settle takes (`reims-vgpu`'s
// decoder's locks, at a command buffer's `CB_SUBMITTED`), and the work the raise is part
// of began before the reset and ends only once the reset returns.
if !raising() {
self.host.reset_settles();
}
}
/// The feature bits the device offers a guest whose driver took `taken`: the host's
@@ -3009,7 +3293,7 @@ impl Shared {
}
}
/// Whether the window's captured pointer may go past its image's edge onto the guest's
/// Whether the window's pointer, in a drag, may go past its image's edge onto the guest's
/// desktop: the guest sees several displays, took `POINTER_OVER`, which moves its cursor
/// there, and `DISPLAY_BOUNDS`, which places them, and runs the device.
fn carries_beyond(&self) -> bool {
@@ -3141,30 +3425,95 @@ impl Shared {
}
/// The guest's `MOVE_CURSOR` showed (`visible`) or hid its cursor on display `id`, one it
/// sees: where that leaves it hidden on every display it moved it on, and shown on none, the
/// cursor is hidden from now ([`Self::cursor_hidden_for`]).
pub(crate) fn cursor_visible(&self, id: u32, visible: bool) {
/// sees, at (`x`, `y`): where that leaves it hidden on every display it moved it on, and shown
/// on none, the cursor is hidden from now ([`Self::cursor_hidden_for`]). Whether it moved a
/// cursor hidden already on that display, and leaves it hidden: nothing of it shows, and the
/// display's screen is not told. Such a move to a new place is the guest's report of its
/// hidden cursor ([`HiddenPlace`]).
pub(crate) fn cursor_visible(&self, id: u32, x: i32, y: i32, visible: bool) -> bool {
let epoch = self.epoch.load(Ordering::Acquire);
let seen = self.displays_seen() as usize;
let mut pointer = self.pointer.lock();
let pointer = pointer.at(epoch);
let Some(slot) = pointer.shown.get_mut(id as usize) else {
return;
return false;
};
let hidden_move = !visible && *slot == Some(false);
*slot = Some(visible);
let moved = pointer.places[id as usize].replace((x, y)) != Some((x, y));
let hidden = pointer.shown[..seen.min(pointer.shown.len())]
.iter()
.all(|shown| *shown != Some(true));
if !hidden {
pointer.hidden_since = None;
pointer.place = HiddenPlace::default();
} else if pointer.hidden_since.is_none() {
pointer.hidden_since = Some(now_ns());
pointer.place = HiddenPlace::default();
} else if hidden_move && moved {
pointer.place.followed = true;
}
hidden_move
}
/// `HIDDEN_PLACES`: the guest reports where its hidden cursor goes (`reports`), or does not,
/// until the next reset.
pub(crate) fn hidden_places(&self, reports: bool) {
let epoch = self.epoch.load(Ordering::Acquire);
self.pointer.lock().at(epoch).hidden_places = reports;
}
/// [`PointerLink::tablet_moved`]: the host's pointer over display `id`'s window moved the
/// guest's tablet. Where the guest reports its hidden cursor's places and hides its cursor, in
/// a hide that has not shown its hidden cursor following the tablet, it is sent
/// `POINTER_LOOK` ([`RgfxPointerLook`]), one at most every [`LOOK_EVERY_NS`]: it reads where
/// its hidden cursor goes for a while, and reports each new place. Waits for no other thread:
/// one that finds the ring held, full or behind answers handed over is not sent, and the
/// next move sends it.
pub(crate) fn look_at_hidden(&self, id: u32) {
if !self.driver_took(RGFX_FEATURE_POINTER_MOTION) || !self.started() {
return;
}
let epoch = self.epoch.load(Ordering::Acquire);
let now = now_ns();
{
let mut pointer = self.pointer.lock();
let pointer = pointer.at(epoch);
let due = pointer
.place
.looked_at
.is_none_or(|at| now.saturating_sub(at) >= LOOK_EVERY_NS);
if !pointer.hidden_places
|| pointer.hidden_since.is_none()
|| pointer.place.followed
|| !due
{
return;
}
}
if self.control_handing.load(Ordering::Acquire) {
return;
}
let look = RgfxPointerLook {
header: event_header(RGFX_EVT_POINTER_LOOK),
display: id,
reserved_14: 0,
};
if matches!(self.post_on(&sized(&look), epoch, false), Post::Done) {
let mut pointer = self.pointer.lock();
let pointer = pointer.at(epoch);
if pointer.hidden_since.is_some() {
pointer.place.looked_at = Some(now);
}
}
}
/// [`PointerLink::cursor_hidden_for`]: counted from the hide, or, while a `POINTER_OVER` told
/// has yet to show the cursor on the pointer's display, from [`CROSSING_HIDE_NS`] after it at
/// the earliest, the cursor hidden as it goes from one display to the next.
/// the earliest, the cursor hidden as it goes from one display to the next. For a guest that
/// reports its hidden cursor's places, `None` until it has reported one in this hide
/// ([`HiddenPlace`]): a hide whose cursor stays where it was as the tablet moves is a
/// recording's, not a game's.
pub(crate) fn cursor_hidden_for(&self) -> Option<u64> {
if !self.driver_took(RGFX_FEATURE_POINTER_MOTION) || !self.started() {
return None;
@@ -3173,6 +3522,9 @@ impl Shared {
let mut pointer = self.pointer.lock();
let pointer = pointer.at(epoch);
let mut since = pointer.hidden_since?;
if pointer.hidden_places && !pointer.place.followed {
return None;
}
if pointer.told.is_some() {
since = since.max(pointer.told_at.saturating_add(CROSSING_HIDE_NS));
}
@@ -3459,6 +3811,17 @@ impl Shared {
}
}
/// `DRIVER_FEATURES_EXT` written `value`: the bits of it the host offers in `FEATURES_EXT`
/// that are taken ([`TAKEN_EXT_FEATURES`]), in place of those taken before. Ignored once the
/// driver is ready, as [`Self::take_driver_features`] is.
fn take_driver_features_ext(&self, value: u32) {
if self.status.load(Ordering::Acquire) == RGFX_STATUS_DRIVER_READY {
return;
}
let taken = value & self.host.features_ext() & TAKEN_EXT_FEATURES;
self.driver_features_ext.store(taken, Ordering::Release);
}
/// The `RGFX_QUEUE_*` flags a `QUEUE_CREATE` may ask for: those the host carries out
/// ([`QUEUE_FLAGS`]) whose feature the guest's driver took.
fn queue_flags_allowed(&self) -> u32 {
@@ -3716,7 +4079,10 @@ impl Shared {
let shared = self.weak_self.get().cloned().unwrap_or_default();
let started = std::thread::Builder::new()
.name(lanes::thread_name(index))
.spawn(move || serve_ring0(&lanes, &shared, index, key));
.spawn(move || {
crate::threads::started();
serve_ring0(&lanes, &shared, index, key);
});
if let Err(e) = started {
log::warn!(
target: "reims_vgpu_graphics",
@@ -3855,7 +4221,7 @@ impl Shared {
(self.host).trace("r0post", &[u64::from(header.r#type), header.seqno, raised]);
}
if raise {
self.host.raise_interrupt(RGFX_CONTROL_VECTOR);
raise_through(&*self.host, RGFX_CONTROL_VECTOR);
}
Post::Done
}
@@ -3863,7 +4229,7 @@ impl Shared {
/// `CONTEXT_CLOSE` of `context` (the module doc), on its lane: its queues end, then
/// the host drops its objects and gives `answer` once its command buffers have finished.
pub(crate) fn close_context(&self, context: u32, answer: CompleteAnswer) {
let ended: Vec<Arc<QueueShared>> = {
let (ended, serving): (Vec<Arc<QueueShared>>, Vec<Arc<QueueShared>>) = {
let mut queues = self.queues.lock();
let ended: Vec<Arc<QueueShared>> = queues
.by_obj
@@ -3874,8 +4240,20 @@ impl Shared {
for queue in &ended {
queues.remove(queue);
}
ended
let serving = (queues.serving.iter())
.filter(|q| q.context == context)
.cloned()
.collect();
(ended, serving)
};
// Each of its queues' threads that has not handed the host its destroy (a queue the
// guest destroyed before the close among them) hands none from here, or has handed it
// already: the host drops the queues with the context's objects below, and a destroy
// handed after the close could reach a later process's queue of the same id once the
// kext gives the number out again.
for queue in &serving {
*queue.context_closed.lock() = true;
}
// No ended queue's thread reads or writes its rings past this, so the kext may give
// their blocks out again once the close is answered.
for queue in &ended {
@@ -4271,7 +4649,7 @@ impl Shared {
}
};
if raise {
self.host.raise_interrupt(RGFX_CONTROL_VECTOR);
raise_through(&*self.host, RGFX_CONTROL_VECTOR);
}
}
@@ -4480,6 +4858,7 @@ impl Shared {
route: AtomicU64::new(0),
route_page: AtomicU32::new(u32::MAX),
ending: AtomicBool::new(false),
context_closed: Mutex::new(false),
trip: trip::Queue::default(),
});
let ended: Vec<Arc<QueueShared>> = {
@@ -4501,6 +4880,7 @@ impl Shared {
}
queues.by_obj.insert(q.obj_id, Arc::clone(&queue));
queues.by_ring.insert(q.submit_offset, Arc::clone(&queue));
queues.serving.push(Arc::clone(&queue));
ended
};
for old in &ended {
@@ -4513,9 +4893,16 @@ impl Shared {
let service = Arc::clone(&queue);
let started = std::thread::Builder::new()
.name(format!("reims-vgpu.graphics-queue-{:#x}", q.obj_id))
.spawn(move || me.queue_service(&service));
.spawn(move || {
crate::threads::started();
me.queue_service(&service);
});
if started.is_err() {
self.queues.lock().remove(&queue);
{
let mut queues = self.queues.lock();
queues.remove(&queue);
queues.serving.retain(|q| !Arc::ptr_eq(q, &queue));
}
self.unroute(&queue);
log::error!(
target: "reims_vgpu_graphics",
@@ -4704,18 +5091,30 @@ impl Shared {
self.close_handed(queue);
// A closed queue's handle goes with it (a process's other objects go at its context's
// close). Nothing is posted for it: the queue has ended. A reset's queue's goes with the
// host's reset ([`Host::device_reset`]).
if !self.ending() && self.epoch.load(Ordering::Acquire) == queue.epoch {
let destroy = RgfxObjectDestroy {
header: RgfxMsgHeader {
r#type: RGFX_CMD_OBJECT_DESTROY,
size: size_of::<RgfxObjectDestroy>() as u32,
seqno: 0,
},
obj_id: queue.obj_id,
};
self.host.stage3_message(&poster, destroy.as_bytes());
// host's reset ([`Host::device_reset`]), and one whose context's close was carried out
// first went with the context's objects: its destroy is handed before that close reaches
// the host, or not at all ([`QueueShared::context_closed`]).
{
let context_closed = queue.context_closed.lock();
if !*context_closed
&& !self.ending()
&& self.epoch.load(Ordering::Acquire) == queue.epoch
{
let destroy = RgfxObjectDestroy {
header: RgfxMsgHeader {
r#type: RGFX_CMD_OBJECT_DESTROY,
size: size_of::<RgfxObjectDestroy>() as u32,
seqno: 0,
},
obj_id: queue.obj_id,
};
self.host.stage3_message(&poster, destroy.as_bytes());
}
}
self.queues
.lock()
.serving
.retain(|q| !Arc::ptr_eq(q, queue));
}
/// The loop of a queue's service thread: take, then sleep, until the queue or the device ends.
@@ -5294,10 +5693,10 @@ impl Shared {
/// (`qraise`, [`Host::trace`]).
fn raise_queue(&self, queue: &QueueShared) {
if !self.host.times_posts_here() {
return self.host.raise_interrupt(queue.vector);
return raise_through(&*self.host, queue.vector);
}
let began = now_ns();
self.host.raise_interrupt(queue.vector);
raise_through(&*self.host, queue.vector);
let ns = now_ns().saturating_sub(began);
self.host.trace("qraise", &[queue.obj_id, ns]);
}
@@ -5341,6 +5740,9 @@ impl Shared {
let Some(display) = self.displays.get(id as usize) else {
return;
};
if id == 0 {
self.watch_version_leave(now);
}
let epoch = self.epoch.load(Ordering::Acquire);
let mode = self.offered_mode(display);
let seen = id < self.displays_seen();
@@ -5510,10 +5912,11 @@ fn carry_out_job(lanes: &Lanes, shared: &Shared, key: Key, job: lanes::Job) {
impl Shared {
/// Posts `message`, for work begun at reset count `epoch`, onto the control completion ring,
/// waiting for nothing ([`CompleteAnswer::answer`]): here where no answer is handed over before
/// it and the ring has room, else handed to the control thread behind those, which it wakes
/// unless a thread is posting them already.
/// it, the ring has room and this thread may raise ([`raise_elsewhere`]), else handed to the
/// control thread behind those, which it wakes unless a thread is posting them already.
fn post_unwaiting(&self, message: &[u8], epoch: u64) {
if !self.control_handing.load(Ordering::Acquire)
&& raises_here()
&& self.post_telling(message, epoch, true, false) != Post::NoRoom
{
return;
@@ -1,4 +1,4 @@
//! The guest's desktop as the host's captured pointer crosses it (docs/graphics-kext/design.md,
//! The guest's desktop as a drag of the host's pointer crosses it (docs/graphics-kext/design.md,
//! "Multiple displays", "A drag across displays"): each display's rectangle in WindowServer's
//! global space, in points, as the guest's `DISPLAY_BOUNDS` gave it, beside the display's
//! scanout, whose pixels lie over that rectangle as the kext places `POINTER_OVER`'s point
@@ -0,0 +1,114 @@
//! What the device sees of the guest's drivers being of another build than the host
//! (docs/graphics-kext/design.md, "The guest's bundle, told to the host"), which it tells the host
//! once a boot, so the host can tell its user why the guest's desktop runs without Metal:
//! - A kext of another wire version leaves the device at `VERSION`. Every kext since the version
//! check reads `MAGIC` and `VERSION` first, and on another version reads `VERSION` once more for
//! its log line and writes nothing; a kext of the host's version reads `REGION_SIZE_HI` right
//! after (`guest/kext/tests/start_order_test.cpp` holds that order). The option ROM and
//! Ambrosia's module read `VERSION` before they reset the device. So a read of `VERSION` while
//! the device is started, which no other register access follows in [`LEFT_AFTER`], is a driver
//! that left at its version check ([`VersionWatch`]).
//! - The accelerator of a kext of the host's version writes `GUEST_BUNDLE` once a boot, with what
//! it found of its Metal bundle and RgfxGate's install pass ([`GuestBundle`]).
use crate::wire::{
RGFX_GUEST_BUNDLE_ERRNO_SHIFT, RGFX_GUEST_BUNDLE_GATE_SHIFT, RGFX_GUEST_BUNDLE_VERSION_SHIFT,
};
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;
/// How long after a read of `VERSION` while the device is started no other register access must
/// come for the reader to count as a driver that left the device at its version check. A kext of
/// the host's version touches `REGION_SIZE_HI` next, with no wait between in its start
/// (`start_order_test.cpp`); each boot logs the gap at info ([`VersionWatch::other_access`]).
/// Measured in seven healthy boots of x86-64 macOS 26.7.2 under KVM (docs/qemu.md, "x86-64
/// macOS guests: drivers of another build"): 65 ms at most, the framebuffer's, whose PAT
/// rendezvous runs between the two reads, and 8 us at most for the accelerator's; under TCG, in a
/// boot of arm64 macOS 26 on Ambrosia, 38 and 35 us, the kexts starting 70 s in. The margin is
/// wide on purpose: a driver called old on a healthy guest is worse than none called, and the
/// line comes a minute into a boot whose desktop takes longer to show.
pub(crate) const LEFT_AFTER: Duration = Duration::from_secs(60);
/// The watch for a driver that leaves at `VERSION` (the module doc).
#[derive(Default)]
pub(crate) struct VersionWatch {
/// The device's clock at a read of `VERSION` while the device was started, which no other
/// register access has followed since; 0 for none.
read_at: AtomicU64,
/// The reset count at which a leave was told, plus 1; 0 for none.
told: AtomicU64,
}
impl VersionWatch {
/// A read of `VERSION` at `now`, the device `started` (`STATUS` 1) or not: one while started
/// begins the watch, unless a leave was told since the last reset (`epoch`).
pub(crate) fn version_read(&self, started: bool, epoch: u64, now: u64) {
if started && self.told.load(Ordering::Acquire) != epoch + 1 {
self.read_at.store(now.max(1), Ordering::Release);
}
}
/// Any other register access, a read but of `MAGIC` and `VERSION`, or any write, at `now()`,
/// which is asked only where a read is watched: the reader did not leave. The time since a
/// watched read of `VERSION` where this ends one. Where none is watched it costs a load.
pub(crate) fn other_access(&self, now: impl FnOnce() -> u64) -> Option<u64> {
if self.read_at.load(Ordering::Relaxed) == 0 {
return None;
}
let at = self.read_at.swap(0, Ordering::AcqRel);
(at != 0).then(|| now().saturating_sub(at))
}
/// Whether, at `now`, a watched read of `VERSION` has had no other register access for
/// [`LEFT_AFTER`] while the device stayed `started` at reset count `epoch`: true once, and
/// then not again until a reset.
pub(crate) fn left(&self, started: bool, epoch: u64, now: u64) -> bool {
let at = self.read_at.load(Ordering::Acquire);
let after = u64::try_from(LEFT_AFTER.as_nanos()).unwrap_or(u64::MAX);
if at == 0 || !started || now.saturating_sub(at) < after {
return false;
}
if self
.read_at
.compare_exchange(at, 0, Ordering::AcqRel, Ordering::Acquire)
.is_err()
{
return false;
}
self.told.swap(epoch + 1, Ordering::AcqRel) != epoch + 1
}
/// The device's reset: a watched read ends with it.
pub(crate) fn reset(&self) {
self.read_at.store(0, Ordering::Release);
}
}
/// A `GUEST_BUNDLE` write: what the guest's accelerator found of its Metal bundle as WindowServer
/// opened the display, and RgfxGate's install pass (`RGFX_REG_GUEST_BUNDLE`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct GuestBundle {
/// What it found: an `RGFX_GUEST_BUNDLE_*`.
pub found: u32,
/// The wire version another version's bundle's marker names; 0 where it names none the kext
/// knows.
pub version: u32,
/// RgfxGate's install pass: an `RGFX_GATE_*`.
pub gate: u32,
/// The `errno` of RgfxGate's failed write or rename; 0 for none.
pub errno: u32,
}
impl GuestBundle {
/// The fields of a `GUEST_BUNDLE` write of `value`.
#[must_use]
pub fn from_register(value: u32) -> GuestBundle {
let byte = |shift: u32| (value >> shift) & 0xff;
GuestBundle {
found: byte(0),
version: byte(RGFX_GUEST_BUNDLE_VERSION_SHIFT),
gate: byte(RGFX_GUEST_BUNDLE_GATE_SHIFT),
errno: byte(RGFX_GUEST_BUNDLE_ERRNO_SHIFT),
}
}
}
+462 -12
View File
@@ -605,10 +605,12 @@ fn present_surface_asks_the_host_and_answers_its_word() {
}
/// A host whose interrupt resets the device, as a host's `raise_interrupt` may (it may call the
/// device), and which answers a present at once, inside [`Host::present_surface`].
/// device), and which answers a present at once, inside [`Host::present_surface`]; it counts the
/// settles the device's resets ask of it ([`Host::reset_settles`]).
struct ResettingHost {
shared: Arc<OnceLock<Weak<Shared>>>,
resets: Arc<AtomicU32>,
settles: Arc<AtomicU32>,
}
impl Host for ResettingHost {
@@ -618,6 +620,9 @@ impl Host for ResettingHost {
self.resets.fetch_add(1, Ordering::SeqCst);
}
}
fn reset_settles(&self) {
self.settles.fetch_add(1, Ordering::SeqCst);
}
fn present_surface(
&self,
_display: u32,
@@ -638,6 +643,7 @@ fn a_present_answered_at_once_raises_with_no_lock_held() {
let mut rig = Rig::with_host(Box::new(ResettingHost {
shared: Arc::clone(&shared),
resets: Arc::clone(&resets),
settles: Arc::default(),
}));
shared.set(Arc::downgrade(&rig.device.shared)).unwrap();
rig.start();
@@ -655,15 +661,47 @@ fn a_present_answered_at_once_raises_with_no_lock_held() {
);
}
/// A reset made inside the device's raise asks the host for no settle ([`Host::reset_settles`]):
/// the host may hold around its raise what its settle takes, and the work the raise is part of
/// began before the reset and ends only once the reset returns. A reset made outside one, the
/// host's and the guest's `STATUS` 0, asks for it, once each
#[test]
fn a_reset_inside_a_raise_asks_for_no_settle() {
let shared = Arc::new(OnceLock::new());
let resets = Arc::new(AtomicU32::new(0));
let settles = Arc::new(AtomicU32::new(0));
let mut rig = Rig::with_host(Box::new(ResettingHost {
shared: Arc::clone(&shared),
resets: Arc::clone(&resets),
settles: Arc::clone(&settles),
}));
shared.set(Arc::downgrade(&rig.device.shared)).unwrap();
rig.start();
rig.arm();
rig.send(present_surface(0, HELD_SURFACE));
eventually(|| resets.load(Ordering::SeqCst) != 0);
assert_eq!(resets.load(Ordering::SeqCst), 1);
assert_eq!(
settles.load(Ordering::SeqCst),
0,
"the reset inside the raise asked for a settle"
);
rig.device.reset();
assert_eq!(settles.load(Ordering::SeqCst), 1);
rig.device.mmio_write(RGFX_REG_STATUS.into(), 0);
assert_eq!(settles.load(Ordering::SeqCst), 2);
}
/// The registers read as the wire says, and `STATUS` follows the guest's writes
#[test]
fn the_registers_read_as_the_wire_says() {
let rig = Rig::new();
let read = |offset: u32| rig.device.mmio_read(offset.into());
assert_eq!(read(RGFX_REG_MAGIC), 0x5846_4752);
assert_eq!(read(RGFX_REG_VERSION), 2);
assert_eq!(read(RGFX_REG_VERSION), 3);
assert_eq!(read(RGFX_REG_FEATURES_LO), 0);
assert_eq!(read(RGFX_REG_FEATURES_HI), 0);
assert_eq!(read(RGFX_REG_FEATURES_EXT), 0, "a host that offers none");
assert_eq!(read(RGFX_REG_STATUS), 0);
assert_eq!(
read(RGFX_REG_REGION_SIZE_LO),
@@ -683,25 +721,109 @@ fn the_registers_read_as_the_wire_says() {
assert_eq!(read(RGFX_REG_STATUS), 0);
}
/// `GET_DISPLAYS` answers display 0, connected, with the screen's mode as its one, preferred
/// mode; the interrupt is raised only where the guest armed the ring, and clears `armed`
/// `FEATURES_EXT` reads the host's bits 64 to 95 with no take, before the driver starts and
/// after, across a reset, and a write there changes nothing
#[test]
fn features_ext_reads_the_host_s_bits_with_no_take() {
struct Ext;
impl Host for Ext {
fn raise_interrupt(&self, _vector: u32) {}
fn features_ext(&self) -> u32 {
RGFX_FEATURE_EXT_SHARED_TEXTURE_NAMES
}
}
let rig = Rig::with_host(Box::new(Ext));
let read = || rig.device.mmio_read(RGFX_REG_FEATURES_EXT.into());
assert_eq!(read(), RGFX_FEATURE_EXT_SHARED_TEXTURE_NAMES);
rig.device.mmio_write(RGFX_REG_FEATURES_EXT.into(), 0);
assert_eq!(read(), RGFX_FEATURE_EXT_SHARED_TEXTURE_NAMES);
rig.device
.mmio_write(RGFX_REG_STATUS.into(), RGFX_STATUS_DRIVER_READY);
assert_eq!(read(), RGFX_FEATURE_EXT_SHARED_TEXTURE_NAMES);
rig.device
.mmio_write(RGFX_REG_STATUS.into(), RGFX_STATUS_RESET);
assert_eq!(read(), RGFX_FEATURE_EXT_SHARED_TEXTURE_NAMES);
}
/// A guest built before `FEATURES_EXT`, which never reads it, meets a host that offers shared
/// textures there as it meets one that offers nothing there: every register it reads, and every
/// feature it takes, read the same on both, before its start, after it and after a reset
#[test]
fn an_old_guest_reads_the_same_device_where_features_ext_offers_more() {
struct Ext;
impl Host for Ext {
fn raise_interrupt(&self, _vector: u32) {}
fn features_ext(&self) -> u32 {
RGFX_FEATURE_EXT_SHARED_TEXTURE_NAMES
}
}
struct Plain;
impl Host for Plain {
fn raise_interrupt(&self, _vector: u32) {}
}
// An old guest's start: its reads of the registers it knows, its take of every offered bit,
// then the reads again after the device starts and after a reset.
let walk = |rig: &Rig| -> Vec<u32> {
let read = |at: u32| rig.device.mmio_read(at.into());
let known = [
RGFX_REG_MAGIC,
RGFX_REG_VERSION,
RGFX_REG_FEATURES_LO,
RGFX_REG_FEATURES_HI,
RGFX_REG_STATUS,
RGFX_REG_REGION_SIZE_LO,
RGFX_REG_REGION_SIZE_HI,
RGFX_REG_DRIVER_FEATURES_LO,
RGFX_REG_DRIVER_FEATURES_HI,
];
let mut seen: Vec<u32> = known.iter().map(|&at| read(at)).collect();
rig.device.mmio_write(
RGFX_REG_DRIVER_FEATURES_LO.into(),
read(RGFX_REG_FEATURES_LO),
);
rig.device.mmio_write(
RGFX_REG_DRIVER_FEATURES_HI.into(),
read(RGFX_REG_FEATURES_HI),
);
rig.start();
seen.extend(known.iter().map(|&at| read(at)));
rig.device
.mmio_write(RGFX_REG_STATUS.into(), RGFX_STATUS_RESET);
seen.extend(known.iter().map(|&at| read(at)));
seen
};
let ext = Rig::with_host(Box::new(Ext));
let plain = Rig::with_host(Box::new(Plain));
assert_eq!(walk(&ext), walk(&plain));
assert_eq!(plain.device.mmio_read(RGFX_REG_FEATURES_EXT.into()), 0);
}
/// `GET_DISPLAYS` answers display 0, connected, with the screen's mode first, which it prefers,
/// then its smaller modes (`display::offered_modes`), each at the screen's rate; the interrupt is
/// raised only where the guest armed the ring, and clears `armed`
#[test]
fn get_displays_answers_the_screen_s_mode() {
let mut rig = Rig::new();
rig.start();
let seqno = rig.send(get_displays());
let bytes = rig.event().unwrap();
assert_eq!(bytes.len(), 48);
assert_eq!(bytes.len(), 88);
let header = RgfxMsgHeader::read_from_prefix(&bytes).unwrap().0;
assert_eq!(
(header.r#type, header.size, header.seqno),
(RGFX_EVT_DISPLAYS, 48, seqno)
(RGFX_EVT_DISPLAYS, 88, seqno)
);
let words: Vec<u32> = bytes[16..]
.chunks(4)
.map(|c| u32::from_le_bytes(c.try_into().unwrap()))
.collect();
assert_eq!(words, [1, 0, 1, 0, 1, 1280, 800, NEVER_MHZ]);
let n = NEVER_MHZ;
assert_eq!(
words,
[
1, 0, 1, 0, 4, 1280, 800, n, 1120, 700, n, 992, 620, n, 960, 600, n, 0
]
);
assert_eq!(rig.interrupts.load(Ordering::SeqCst), 0, "not armed");
rig.arm();
rig.send(get_displays());
@@ -715,7 +837,7 @@ fn get_displays_answers_the_screen_s_mode() {
}
/// A guest that took `DISPLAY_SCALE` is told the screen's scale between the display's record and
/// its mode; one that did not gets the answer without it (`get_displays_answers_the_screen_s_mode`)
/// its modes; one that did not gets the answer without it (`get_displays_answers_the_screen_s_mode`)
#[test]
fn a_guest_that_took_display_scale_is_told_the_screen_s_scale() {
struct Scales;
@@ -736,13 +858,19 @@ fn a_guest_that_took_display_scale_is_told_the_screen_s_scale() {
let header = RgfxMsgHeader::read_from_prefix(&bytes).unwrap().0;
assert_eq!(
(header.r#type, header.size, header.seqno),
(RGFX_EVT_DISPLAYS, 56, seqno)
(RGFX_EVT_DISPLAYS, 96, seqno)
);
let words: Vec<u32> = bytes[16..56]
let words: Vec<u32> = bytes[16..92]
.chunks(4)
.map(|c| u32::from_le_bytes(c.try_into().unwrap()))
.collect();
assert_eq!(words, [1, 0, 1, 0, 1, 240, 0, 1280, 800, NEVER_MHZ]);
let n = NEVER_MHZ;
assert_eq!(
words,
[
1, 0, 1, 0, 4, 240, 0, 1280, 800, n, 1120, 700, n, 992, 620, n, 960, 600, n
]
);
}
/// A post whose guest took the record and armed the ring again before the post cleared `armed`
@@ -1982,6 +2110,88 @@ fn a_command_queue_gets_its_own_ring_loop() {
assert_eq!(*seen.closed.lock(), vec![7]);
}
/// A host that records, in order, the messages it is handed, each with the id at its offset 16
/// (an object's, or a command buffer's queue), and the contexts it closes, and holds a
/// `COMMAND_BUFFER` while its gate is shut.
#[derive(Default)]
struct CloseOrderHost {
log: Arc<Mutex<Vec<(u32, u64)>>>,
gate: Arc<AtomicBool>,
in_buffer: Arc<AtomicBool>,
}
impl Host for CloseOrderHost {
fn raise_interrupt(&self, _vector: u32) {}
fn context_closed(&self, context: u32, answer: CompleteAnswer) {
self.log
.lock()
.push((RGFX_CMD_CONTEXT_CLOSE, u64::from(context)));
answer.answer(RGFX_STATUS_OK);
}
fn stage3_message(&self, _completion: &CompletionPoster, message: &[u8]) {
let (header, _) = RgfxMsgHeader::read_from_prefix(message).unwrap();
let id = RgfxObjectDestroy::read_from_prefix(message).map_or(0, |(m, _)| m.obj_id);
self.log.lock().push((header.r#type, id));
if header.r#type == RGFX_CMD_COMMAND_BUFFER {
self.in_buffer.store(true, Ordering::SeqCst);
while !self.gate.load(Ordering::SeqCst) {
std::thread::sleep(Duration::from_millis(1));
}
}
}
}
/// A queue's service thread hands the host the queue's `OBJECT_DESTROY` before its context's
/// `CONTEXT_CLOSE` reaches the host, or not at all: a thread held in a command buffer while the
/// guest destroys the queue and its process closes hands none after the close, which the host
/// carries out dropping the queue with the context's objects. So no late destroy reaches a later
/// process's queue of the same id once the kext gives the context's number out again
#[test]
fn a_closed_context_s_queue_hands_no_destroy_after_the_close() {
let host = CloseOrderHost::default();
let (log, gate, in_buffer) = (
Arc::clone(&host.log),
Arc::clone(&host.gate),
Arc::clone(&host.in_buffer),
);
let mut rig = Rig::with_host(Box::new(host));
rig.start();
const QUEUE: u64 = (7 << RGFX_CONTEXT_OBJ_ID_SHIFT) | 1;
let seqno = send_queue_create(&mut rig, QUEUE);
assert_eq!(rig.complete(), (seqno, RGFX_STATUS_OK));
wait_queue_idle(&rig);
// Its thread in a command buffer the host holds.
publish_command_buffer(&rig, QUEUE, 100, 55, true);
assert!(
eventually(|| in_buffer.load(Ordering::SeqCst)),
"the buffer never reached the host"
);
// The guest destroys the queue, and its process closes: the close is carried out, and
// answered, while the queue's thread is still in the buffer.
rig.send(object_message(RGFX_CMD_OBJECT_DESTROY, QUEUE));
let seqno = rig.send(context_close(7));
assert_eq!(rig.complete(), (seqno, RGFX_STATUS_OK));
assert_eq!(
rig.device.queues_serving(),
1,
"the queue's thread is still in the buffer"
);
// The thread goes on, and ends.
gate.store(true, Ordering::SeqCst);
assert!(
eventually(|| rig.device.queues_serving() == 0),
"the queue's thread never ended"
);
let log = log.lock().clone();
let closed = (log.iter())
.position(|&e| e == (RGFX_CMD_CONTEXT_CLOSE, 7))
.expect("the context closed");
assert!(
!log[closed..].contains(&(RGFX_CMD_OBJECT_DESTROY, QUEUE)),
"a destroy handed after the close: {log:?}"
);
}
/// A `COMMAND_BUFFER_IN_REGION` hands the host the whole `COMMAND_BUFFER` message in the block it
/// names, with the reference's seqno, and the completion names that seqno; a reference to no
/// block its process holds (none granted, another process's, its own once released), or to bytes
@@ -5693,6 +5903,7 @@ fn the_host_is_told_each_time_the_driver_takes_the_pool() {
#[derive(Clone, Default)]
struct ReadyHost {
ready: Arc<Mutex<Vec<u64>>>,
ready_ext: Arc<Mutex<Vec<u32>>>,
}
impl Host for ReadyHost {
@@ -5700,8 +5911,12 @@ impl Host for ReadyHost {
fn features(&self) -> u64 {
RGFX_FEATURE_MANAGED_AT_COPY | RGFX_FEATURE_POOL
}
fn driver_ready(&self, taken: u64) {
fn driver_ready(&self, taken: u64, taken_ext: u32) {
self.ready.lock().push(taken);
self.ready_ext.lock().push(taken_ext);
}
fn features_ext(&self) -> u32 {
RGFX_FEATURE_EXT_SHARED_TEXTURE_NAMES | RGFX_FEATURE_EXT_SURFACE_HOLD
}
}
@@ -5738,6 +5953,84 @@ fn the_host_is_told_the_driver_s_features_as_it_becomes_ready() {
);
}
/// `DRIVER_FEATURES_EXT` takes, before the driver is ready, the bits written that
/// `FEATURES_EXT` offers and that are taken (`SURFACE_HOLD`, bit 2), never one used with no take
/// (`SHARED_TEXTURE_NAMES`) nor one the host does not offer (bit 1, `SURFACE_HOLD` with its word
/// in the block's header, which kexts built before the word moved take); a read answers the bits
/// taken; a write while ready is ignored; the host is told them as the driver becomes ready
/// ([`Host::driver_ready`]); a reset clears them
#[test]
fn driver_features_ext_takes_the_offered_taken_bits() {
let host = ReadyHost::default();
let rig = Rig::with_host(Box::new(host.clone()));
let read = || rig.device.mmio_read(RGFX_REG_DRIVER_FEATURES_EXT.into());
let write = |bits: u32| {
rig.device
.mmio_write(RGFX_REG_DRIVER_FEATURES_EXT.into(), bits);
};
assert_eq!(read(), 0);
write(u32::MAX);
assert_eq!(read(), RGFX_FEATURE_EXT_SURFACE_HOLD, "the taken bit alone");
write(RGFX_FEATURE_EXT_SHARED_TEXTURE_NAMES);
assert_eq!(read(), 0, "a bit used with no take is not taken");
assert_eq!(RGFX_FEATURE_EXT_SURFACE_HOLD, 1 << 2);
write(1 << 1);
assert_eq!(
read(),
0,
"the hold in the block's header, which an older kext takes: none"
);
write(RGFX_FEATURE_EXT_SURFACE_HOLD);
rig.start();
assert_eq!(*host.ready_ext.lock(), vec![RGFX_FEATURE_EXT_SURFACE_HOLD]);
write(0);
assert_eq!(read(), RGFX_FEATURE_EXT_SURFACE_HOLD, "fixed while ready");
rig.device
.mmio_write(RGFX_REG_STATUS.into(), RGFX_STATUS_RESET);
assert_eq!(read(), 0, "a reset clears it");
rig.start();
assert_eq!(
*host.ready_ext.lock(),
vec![RGFX_FEATURE_EXT_SURFACE_HOLD, 0]
);
// A host that offers nothing there takes nothing.
let plain = Rig::new();
plain
.device
.mmio_write(RGFX_REG_DRIVER_FEATURES_EXT.into(), u32::MAX);
assert_eq!(
plain.device.mmio_read(RGFX_REG_DRIVER_FEATURES_EXT.into()),
0
);
}
/// The hold's waker posts a `SURFACE_HOLD_LOWERED` of the block onto the control completion
/// ring, `seqno` 0, once the driver is ready, and nothing before (`HoldWaker::lowered`)
#[test]
fn the_hold_waker_posts_the_block_s_lowered_hold() {
let mut rig = Rig::new();
let waker = rig.device.hold_waker();
waker.lowered(0x4000);
rig.start();
waker.lowered(0x8000);
let event = rig.event().expect("a SURFACE_HOLD_LOWERED");
let lowered = RgfxSurfaceHoldLowered::read_from_bytes(&event).unwrap();
assert_eq!(
(
lowered.header.r#type,
lowered.header.size,
lowered.header.seqno
),
(RGFX_EVT_SURFACE_HOLD_LOWERED, 24, 0)
);
assert_eq!(
lowered.block_offset, 0x8000,
"the one posted once ready alone"
);
assert!(rig.quiet_for(200));
}
/// A `POOL_TAKE`'s `POOL_BLOCK` on `rig`: its status, offset, length and GPU address.
fn pool_block(rig: &mut Rig, bytes: Vec<u8>) -> (u32, u64, u64, u64) {
let seqno = rig.send(bytes);
@@ -6013,3 +6306,160 @@ fn private_messages_go_to_the_decoder_where_the_driver_did_not_take_private_bloc
[(RGFX_CMD_PRIVATE_TAKE, 0, 0), (RGFX_CMD_PRIVATE_GIVE, 0, 0)]
);
}
/// A host that records what the device tells it of the guest's drivers: how many drivers left at
/// `VERSION` ([`Host::guest_driver_left`]) and each `GUEST_BUNDLE` ([`Host::guest_bundle`]).
#[derive(Clone, Default)]
struct DriversHost {
left: Arc<AtomicU32>,
bundles: Arc<Mutex<Vec<GuestBundle>>>,
}
impl Host for DriversHost {
fn raise_interrupt(&self, _vector: u32) {}
fn guest_driver_left(&self) {
self.left.fetch_add(1, Ordering::SeqCst);
}
fn guest_bundle(&self, bundle: GuestBundle) {
self.bundles.lock().push(bundle);
}
}
/// `secs` seconds after now, on the device's clock.
fn secs_on(secs: u64) -> u64 {
now_ns() + secs * 1_000_000_000
}
/// A driver that reads `VERSION` after the firmware started the device (`STATUS` 1), and reads
/// or writes no other register in the 60 s after, left at its version check, as a kext of another
/// wire version does: it reads `MAGIC`, `VERSION`, and `VERSION` again for its log line. The host
/// is told on display 0's refresh once those 60 s have passed, not before, and once a reset: the
/// next boot's, after the host's reset of the device and the firmware's start, is told again.
#[test]
fn a_driver_that_leaves_at_version_is_told_once_a_reset() {
let host = DriversHost::default();
let rig = Rig::with_host(Box::new(host.clone()));
let left = || host.left.load(Ordering::SeqCst);
let read = |offset: u32| rig.device.mmio_read(offset.into());
let refresh = |secs: u64| rig.device.shared.refresh(0, secs_on(secs));
// The option ROM: its reads come before its reset and start.
read(RGFX_REG_MAGIC);
read(RGFX_REG_VERSION);
read(RGFX_REG_REGION_SIZE_LO);
rig.start();
// The old kext's framebuffer and accelerator.
for _ in 0..2 {
read(RGFX_REG_MAGIC);
read(RGFX_REG_VERSION);
read(RGFX_REG_VERSION);
}
refresh(59);
assert_eq!(left(), 0, "not before 60 s");
refresh(61);
assert_eq!(left(), 1);
refresh(200);
read(RGFX_REG_VERSION);
refresh(61);
assert_eq!(left(), 1, "once a reset");
// The guest's reboot: QEMU resets the device, and the firmware starts it again.
rig.device.reset();
rig.start();
read(RGFX_REG_MAGIC);
read(RGFX_REG_VERSION);
refresh(61);
assert_eq!(left(), 2);
assert!(host.bundles.lock().is_empty());
}
/// A driver of the host's version goes on after `VERSION`, its framebuffer reading
/// `REGION_SIZE_HI` and its accelerator `REGION_SIZE_HI` too, as each one's start does
/// (`start_order_test.cpp`), and is never told as one that left, however long the refreshes run;
/// nor is a read of `VERSION` while the device is not started, as the option ROM's and Ambrosia's
/// module's are, before their reset, nor one the host's reset of the device ends.
#[test]
fn a_driver_that_goes_on_after_version_is_not_told() {
let host = DriversHost::default();
let rig = Rig::with_host(Box::new(host.clone()));
let left = || host.left.load(Ordering::SeqCst);
let read = |offset: u32| rig.device.mmio_read(offset.into());
let refresh = |secs: u64| rig.device.shared.refresh(0, secs_on(secs));
// Not started: the firmware's reads.
read(RGFX_REG_MAGIC);
read(RGFX_REG_VERSION);
refresh(120);
assert_eq!(left(), 0);
rig.start();
// The framebuffer: on at once to the region's size, then its reset and start.
read(RGFX_REG_MAGIC);
read(RGFX_REG_VERSION);
read(RGFX_REG_REGION_SIZE_HI);
rig.device
.mmio_write(RGFX_REG_STATUS.into(), RGFX_STATUS_RESET);
rig.start();
// The accelerator, after the framebuffer's start.
read(RGFX_REG_MAGIC);
read(RGFX_REG_VERSION);
read(RGFX_REG_REGION_SIZE_HI);
refresh(120);
assert_eq!(left(), 0);
// A write after the read counts as going on as well, and so does a doorbell.
read(RGFX_REG_VERSION);
rig.device
.mmio_write(RGFX_REG_GUEST_BUNDLE.into(), RGFX_GUEST_BUNDLE_OURS);
read(RGFX_REG_VERSION);
rig.device
.mmio_write_taking(RGFX_REG_DOORBELL.into(), RGFX_CONTROL_RING_ID);
refresh(120);
assert_eq!(left(), 0);
// The host's reset ends a watched read: the device is no longer started.
read(RGFX_REG_VERSION);
rig.device.reset();
refresh(120);
assert_eq!(left(), 0);
}
/// `GUEST_BUNDLE` hands the host what the accelerator found, each field from its bits, at each
/// write, and reads 0.
#[test]
fn guest_bundle_tells_the_host_what_the_accelerator_found() {
let host = DriversHost::default();
let rig = Rig::with_host(Box::new(host.clone()));
let write = |value: u32| {
rig.device.mmio_write(RGFX_REG_GUEST_BUNDLE.into(), value);
};
write(
RGFX_GUEST_BUNDLE_OTHER_VERSION
| 2 << RGFX_GUEST_BUNDLE_VERSION_SHIFT
| RGFX_GATE_NO_DATA_VOLUME << RGFX_GUEST_BUNDLE_GATE_SHIFT,
);
write(
RGFX_GUEST_BUNDLE_OTHER_VERSION
| RGFX_GATE_FAILED << RGFX_GUEST_BUNDLE_GATE_SHIFT
| 28 << RGFX_GUEST_BUNDLE_ERRNO_SHIFT,
);
write(RGFX_GUEST_BUNDLE_OURS | RGFX_GATE_PRESENT << RGFX_GUEST_BUNDLE_GATE_SHIFT);
assert_eq!(
*host.bundles.lock(),
[
GuestBundle {
found: RGFX_GUEST_BUNDLE_OTHER_VERSION,
version: 2,
gate: RGFX_GATE_NO_DATA_VOLUME,
errno: 0,
},
GuestBundle {
found: RGFX_GUEST_BUNDLE_OTHER_VERSION,
version: 0,
gate: RGFX_GATE_FAILED,
errno: 28,
},
GuestBundle {
found: RGFX_GUEST_BUNDLE_OURS,
version: 0,
gate: RGFX_GATE_PRESENT,
errno: 0,
},
]
);
assert_eq!(rig.device.mmio_read(RGFX_REG_GUEST_BUNDLE.into()), 0);
}
@@ -191,8 +191,14 @@ fn a_guest_that_did_not_take_multi_display_sees_display_0_alone() {
rig.start();
rig.send(get_displays());
let bytes = rig.event().unwrap();
assert_eq!(bytes.len(), 48);
assert_eq!(words(&bytes), [1, 0, 1, 0, 1, 1280, 800, NEVER_MHZ]);
assert_eq!(bytes.len(), 88);
let n = NEVER_MHZ;
assert_eq!(
words(&bytes),
[
1, 0, 1, 0, 4, 1280, 800, n, 1120, 700, n, 992, 620, n, 960, 600, n, 0
]
);
let room = scanout_room(3);
let image = RGFX_ALLOCATIONS_OFFSET + 0x1000;
rig.region().write(image, &[0, 0, 0, 255]);
@@ -244,7 +250,8 @@ fn a_guest_that_did_not_take_multi_display_sees_display_0_alone() {
}
/// A guest that took `MULTI_DISPLAY` is told every display, ids 0 up, each connected, with the
/// mode its own screen offers as its one, preferred mode
/// modes its own screen offers: its screen's first, preferred, then its smaller modes, at its
/// own screen's rate
#[test]
fn a_guest_that_took_multi_display_is_told_every_display_s_own_mode() {
let mut rig = Rig::of_displays(3);
@@ -263,16 +270,136 @@ fn a_guest_that_took_multi_display_is_told_every_display_s_own_mode() {
rig.start();
rig.send(get_displays());
let bytes = rig.event().unwrap();
assert_eq!(bytes.len(), 104);
assert_eq!(bytes.len(), 248);
let n = NEVER_MHZ;
let m = 60_000;
assert_eq!(
words(&bytes),
[
3, 0, 1, 0, 1, 1280, 800, NEVER_MHZ, 1, 1, 0, 1, 1920, 1080, 60_000, 2, 1, 0, 1, 2560,
1440, NEVER_MHZ
3, //
0, 1, 0, 4, 1280, 800, n, 1120, 700, n, 992, 620, n, 960, 600, n, //
1, 1, 0, 5, 1920, 1080, m, 1680, 944, m, 1504, 846, m, 1440, 810, m, 1280, 720,
m, //
2, 1, 0, 6, 2560, 1440, n, 2240, 1260, n, 2000, 1124, n, 1920, 1080, n, 1696, 954,
n, //
1280, 720, n,
]
);
}
/// The modes of each display in `bytes`, a `DISPLAYS` answer whose records carry a scale where
/// `scaled`, read as the guest's kext reads them (`RgfxDisplayTable.hpp`, `rgfxListDisplays`):
/// each display's id, its scale (0 where there is none) and the mode records its count says
/// follow it. The records end at the answer's padding, under 8 bytes of zeros.
fn listed(bytes: &[u8], scaled: bool) -> Vec<(u32, u32, Vec<[u32; 3]>)> {
let words = words(bytes);
let mut at = 1;
let mut displays = Vec::new();
for _ in 0..words[0] {
let (id, connected, preferred, count) =
(words[at], words[at + 1], words[at + 2], words[at + 3]);
assert_eq!((connected, preferred), (1, 0), "display {id}");
at += 4;
let scale = if scaled {
at += 2;
words[at - 2]
} else {
0
};
let modes = (0..count as usize)
.map(|i| {
[
words[at + 3 * i],
words[at + 3 * i + 1],
words[at + 3 * i + 2],
]
})
.collect();
at += 3 * count as usize;
displays.push((id, scale, modes));
}
assert!(
words.len() - at < 2,
"{} words past the records",
words.len() - at
);
assert!(words[at..].iter().all(|&w| w == 0), "the padding is zeros");
displays
}
/// Each display's mode count is the mode records that follow it, which are the modes it offers
/// (`display::offered_modes`) at its screen's rate, after its scale where the guest took
/// `DISPLAY_SCALE`, on devices of one to four displays: the guest's walk of the records ends at
/// the answer's end
#[test]
fn each_display_s_mode_count_is_the_records_that_follow_it() {
struct Scales;
impl Host for Scales {
fn raise_interrupt(&self, _vector: u32) {}
fn features(&self) -> u64 {
RGFX_FEATURE_DISPLAY_SCALE
}
}
let screens = [
Mode {
width: 3840,
height: 2160,
refresh_mhz: 120_000,
scale_120ths: 240,
},
Mode {
width: 1280,
height: 720,
refresh_mhz: 59_940,
scale_120ths: 120,
},
Mode {
width: 3072,
height: 1920,
refresh_mhz: 60_000,
scale_120ths: 180,
},
Mode {
width: 7680,
height: 4320,
refresh_mhz: 144_000,
scale_120ths: 120,
},
];
for count in 1..=4 {
for scaled in [false, true] {
let mut rig = Rig::with_displays(Box::new(Scales), Lanes::default(), count);
*rig.mode.lock() = screens[0];
for (i, (mode, _)) in rig.more.iter().enumerate() {
*mode.lock() = screens[i + 1];
}
let mut took = 0;
if count > 1 {
took |= RGFX_FEATURE_MULTI_DISPLAY;
}
if scaled {
took |= RGFX_FEATURE_DISPLAY_SCALE;
}
rig.device
.mmio_write(RGFX_REG_DRIVER_FEATURES_HI.into(), (took >> 32) as u32);
rig.start();
rig.send(get_displays());
let listed = listed(&rig.event().unwrap(), scaled);
assert_eq!(listed.len(), count, "{count} displays");
for (i, (id, scale, modes)) in listed.into_iter().enumerate() {
let offered = crate::display::offered_modes(screens[i], count as u32);
assert_eq!(id, i as u32);
assert_eq!(scale, if scaled { screens[i].scale_120ths } else { 0 });
let want: Vec<[u32; 3]> = (offered.iter())
.map(|m| [m.width, m.height, screens[i].refresh_mhz])
.collect();
assert_eq!(modes, want, "display {i} of {count}, scaled {scaled}");
assert!(modes.len() > 1, "display {i} of {count}: smaller modes");
}
}
}
}
/// Each display's scanout, cursor and panel reach its own screen alone, and its state is its own
#[test]
fn each_display_s_commands_reach_its_own_screen() {
@@ -385,8 +512,8 @@ fn a_display_offers_the_largest_mode_its_room_holds() {
four.start();
four.send(get_displays());
let words = words(&four.event().unwrap());
assert_eq!(words[5..8], [1280, 800, NEVER_MHZ]);
assert_eq!(words[12..15], [3840, 2160, NEVER_MHZ]);
assert_eq!(words[4..8], [4, 1280, 800, NEVER_MHZ]);
assert_eq!(words[20..24], [7, 3840, 2160, NEVER_MHZ]);
}
/// Each display's `VBLANK`s and `DISPLAY_CHANGED` carry its id, its `VBLANK`s on while the guest
@@ -849,7 +976,7 @@ fn placed(scale: u32, x1: i32, y1: i32) -> Rig {
rig
}
/// The captured pointer held at an edge of display 0's window where the guest's desktop puts
/// A drag's pointer held at an edge of display 0's window where the guest's desktop puts
/// display 1 goes on onto display 1, as the guest arranged them, its moves scaled as over display
/// 0's window, and comes back across the same edge; edges no display meets hold it
#[test]
@@ -199,6 +199,170 @@ fn a_guest_that_sees_one_display_hides_its_cursor_there() {
assert!(link.cursor_hidden_for().is_some());
}
/// A `HIDDEN_PLACES` saying the guest reports where its hidden cursor goes (`reports`), or not,
/// carried out: it carries out the answered `GET_DISPLAYS` after it.
fn hidden_places(rig: &mut Rig, reports: bool) {
let command = RgfxHiddenPlaces {
header: RgfxMsgHeader {
r#type: RGFX_CMD_HIDDEN_PLACES,
..Default::default()
},
reports: u32::from(reports),
reserved_14: 0,
};
moved(rig, command.as_bytes().to_vec());
}
/// The next event, as a `POINTER_LOOK`: its display.
fn look(rig: &mut Rig) -> u32 {
let l = RgfxPointerLook::read_from_bytes(&rig.event().expect("a POINTER_LOOK")).unwrap();
assert_eq!(
(
l.header.r#type,
l.header.size,
l.header.seqno,
l.reserved_14
),
(RGFX_EVT_POINTER_LOOK, 24, 0, 0)
);
l.display
}
/// A guest that reports where its hidden cursor goes (`HIDDEN_PLACES`) has a hide counted as a
/// game's only once it reports its hidden cursor at a new place (a `MOVE_CURSOR` of the cursor
/// still hidden): the tablet's moves of a game's hidden cursor move it (lane sharecur, potluck
/// jobs m3-max-78716 and m3-max-78811). Until then the window's pointer is the tablet's, and each
/// move of it over the window sends `POINTER_LOOK`, one every 50 ms at most, which has the guest
/// read where its hidden cursor went; none goes while the cursor shows, nor once it followed.
/// A show, and the next hide, count afresh
#[test]
fn a_hide_whose_cursor_follows_the_tablet_is_a_games() {
let mut rig = motion_rig(1);
take_and_start(&rig, RGFX_FEATURE_POINTER_MOTION);
let link = rig.device.pointer_link();
hidden_places(&mut rig, true);
link.tablet_moved(0);
assert!(
rig.quiet_for(20),
"no look before the guest moved its cursor"
);
moved(&mut rig, cursor_of(0, 100, 100, true));
link.tablet_moved(0);
assert!(rig.quiet_for(20), "no look while it shows");
moved(&mut rig, cursor_of(0, 100, 100, false));
assert_eq!(
link.cursor_hidden_for(),
None,
"a hide the tablet has not moved"
);
link.tablet_moved(0);
assert_eq!(look(&mut rig), 0);
link.tablet_moved(0);
assert!(rig.quiet_for(20), "one look every 50 ms at most");
moved(&mut rig, cursor_of(0, 100, 100, false));
assert_eq!(
link.cursor_hidden_for(),
None,
"reported where the hide left it"
);
moved(&mut rig, cursor_of(0, 130, 115, false));
assert!(
link.cursor_hidden_for().is_some(),
"reported where the tablet put it: a game's"
);
std::thread::sleep(Duration::from_millis(60));
link.tablet_moved(0);
assert!(rig.quiet_for(20), "no look once it followed");
moved(&mut rig, cursor_of(0, 140, 120, true));
assert_eq!(link.cursor_hidden_for(), None, "shown");
moved(&mut rig, cursor_of(0, 140, 120, false));
assert_eq!(link.cursor_hidden_for(), None, "a new hide counts afresh");
link.tablet_moved(0);
assert_eq!(look(&mut rig), 0, "and looks at its first move");
}
/// A hide whose cursor stays where the hide left it while the tablet moves is a system
/// recording's: macOS draws the cursor into the recording and leaves the hidden cursor's place
/// alone (lane sharecur, potluck job m3-max-78811, x86-64 26.7.2). It is never counted a game's,
/// so the window's pointer stays the tablet's, absolute, and the guest is asked again every 50 ms
/// while the tablet moves
#[test]
fn a_hide_whose_cursor_stays_put_under_the_tablet_is_no_games() {
let mut rig = motion_rig(1);
take_and_start(&rig, RGFX_FEATURE_POINTER_MOTION);
let link = rig.device.pointer_link();
hidden_places(&mut rig, true);
moved(&mut rig, cursor_of(0, 2922, 1952, true));
moved(&mut rig, cursor_of(0, 2922, 1952, false));
for _ in 0..3 {
link.tablet_moved(0);
assert_eq!(look(&mut rig), 0);
assert_eq!(link.cursor_hidden_for(), None, "never a game's");
std::thread::sleep(Duration::from_millis(60));
}
}
/// A guest that reports no hidden places (a kext built before `HIDDEN_PLACES`, which sends none,
/// or one that says 0) hides as before: its hide counts from the hide, and it is sent no
/// `POINTER_LOOK`; a reset forgets a guest's report, until it sends another
#[test]
fn a_guest_that_reports_no_hidden_places_hides_as_before() {
let mut rig = motion_rig(1);
take_and_start(&rig, RGFX_FEATURE_POINTER_MOTION);
let link = rig.device.pointer_link();
moved(&mut rig, cursor_of(0, 100, 100, true));
moved(&mut rig, cursor_of(0, 100, 100, false));
assert!(link.cursor_hidden_for().is_some(), "no HIDDEN_PLACES");
link.tablet_moved(0);
assert!(rig.quiet_for(20), "no look");
hidden_places(&mut rig, false);
moved(&mut rig, cursor_of(0, 120, 110, true));
moved(&mut rig, cursor_of(0, 120, 110, false));
assert!(link.cursor_hidden_for().is_some(), "HIDDEN_PLACES of 0");
link.tablet_moved(0);
assert!(rig.quiet_for(20), "no look");
hidden_places(&mut rig, true);
rig.device
.mmio_write(RGFX_REG_STATUS.into(), RGFX_STATUS_RESET);
(rig.produced, rig.consumed, rig.seqno) = (0, 0, 0);
take_and_start(&rig, RGFX_FEATURE_POINTER_MOTION);
moved(&mut rig, cursor_of(0, 130, 115, true));
moved(&mut rig, cursor_of(0, 130, 115, false));
assert!(
link.cursor_hidden_for().is_some(),
"the reset forgot the report"
);
link.tablet_moved(0);
assert!(rig.quiet_for(20), "no look");
}
/// A move of a cursor the guest hid already shows nothing: it is the device's alone (the guest's
/// report of its hidden cursor), and the display's screen is told of the hide and the show, not
/// of the moves between
#[test]
fn a_hidden_cursors_moves_are_not_the_screens() {
let mut rig = motion_rig(1);
take_and_start(&rig, RGFX_FEATURE_POINTER_MOTION);
moved(&mut rig, cursor_of(0, 100, 100, true));
moved(&mut rig, cursor_of(0, 100, 100, false));
moved(&mut rig, cursor_of(0, 130, 115, false));
moved(&mut rig, cursor_of(0, 160, 130, false));
moved(&mut rig, cursor_of(0, 170, 135, true));
let moves: Vec<Told> = rig
.told()
.into_iter()
.filter(|told| matches!(told, Told::Moved(..)))
.collect();
assert_eq!(
moves,
[
Told::Moved(100, 100, true),
Told::Moved(100, 100, false),
Told::Moved(170, 135, true),
]
);
}
/// Each `POINTER_MOTION` the window sends reaches the guest that took it as it was sent: motion,
/// wheel and buttons
#[test]
@@ -1,5 +1,5 @@
read MAGIC = 0x58464752
read VERSION = 0x2
read VERSION = 0x3
read REGION_SIZE_HI = 0x0
read REGION_SIZE_LO = 0x40000000
read FEATURES_LO = 0x7
@@ -15,7 +15,7 @@ arm ring0 recheck empty
post ring0 GET_DISPLAYS seqno=1 size=16
write DOORBELL = 0x0
interrupt 0
take ring0 DISPLAYS seqno=1 size=48 0x1 0x1 0x50000000001 0x100000320
take ring0 DISPLAYS seqno=1 size=88 0x1 0x1 0x50000000004 0x100000320 0x2bc00000460 0x3e000000001 0x10000026c 0x258000003c0 0x1
arm ring0 recheck empty
post ring0 0x7777 seqno=2 size=24 0x0
write DOORBELL = 0x0
@@ -23,7 +23,7 @@ interrupt 0
take ring0 COMPLETE seqno=2 size=24 0x1
arm ring0 recheck empty
header ring0.submit +0x00=0x28 +0x40=0x28 +0x80=0x1
header ring0.complete +0x00=0x48 +0x40=0x48 +0xc0=0x1
header ring0.complete +0x00=0x70 +0x40=0x70 +0xc0=0x1
header queue.submit
header queue.complete
post ring0 BLOCK_GRANT seqno=3 size=40 0x7 0x8400000 0x10100
@@ -37,7 +37,7 @@ take ring0 COMPLETE seqno=5 size=24 0x0
arm ring0 recheck empty
arm queueA recheck empty
header ring0.submit +0x00=0xb0 +0x40=0xb0 +0x80=0x1
header ring0.complete +0x00=0x60 +0x40=0x60 +0xc0=0x1
header ring0.complete +0x00=0x88 +0x40=0x88 +0xc0=0x1
header queue.submit +0x80=0x1
header queue.complete +0xc0=0x1
post queueA COMMAND_BUFFER seqno=1 size=40 0x70000000001 0x100 0x0
@@ -53,7 +53,7 @@ take queueA CB_COMPLETE seqno=2 size=48 0x101 0x0 0x0 0x0
take queueA CB_COMPLETE seqno=3 size=48 0x102 0x0 0x0 0x0
arm queueA recheck empty
header ring0.submit +0x00=0xb0 +0x40=0xb0 +0x80=0x1
header ring0.complete +0x00=0x60 +0x40=0x60 +0xc0=0x1
header ring0.complete +0x00=0x88 +0x40=0x88 +0xc0=0x1
header queue.submit +0x00=0x78 +0x40=0x78 +0x80=0x1
header queue.complete +0x00=0x90 +0x08=0x3 +0x40=0x90 +0xc0=0x1
post ring0 OBJECT_DESTROY seqno=6 size=24 0x70000000001
@@ -61,10 +61,10 @@ write DOORBELL = 0x0
post ring0 GET_DISPLAYS seqno=7 size=16
write DOORBELL = 0x0
interrupt 0
take ring0 DISPLAYS seqno=7 size=48 0x1 0x1 0x50000000001 0x100000320
take ring0 DISPLAYS seqno=7 size=88 0x1 0x1 0x50000000004 0x100000320 0x2bc00000460 0x3e000000001 0x10000026c 0x258000003c0 0x1
arm ring0 recheck empty
header ring0.submit +0x00=0xd8 +0x40=0xd8 +0x80=0x1
header ring0.complete +0x00=0x90 +0x40=0x90 +0xc0=0x1
header ring0.complete +0x00=0xe0 +0x40=0xe0 +0xc0=0x1
header queue.submit +0x00=0x78 +0x40=0x78 +0x80=0x1
header queue.complete +0x00=0x90 +0x08=0x3 +0x40=0x90 +0xc0=0x1
post ring0 QUEUE_CREATE seqno=8 size=56 0x70000000002 0x8400000 0x8500000 0x1000000010000 0x300000002
@@ -74,7 +74,7 @@ take ring0 COMPLETE seqno=8 size=24 0x0
arm ring0 recheck empty
arm queueB recheck empty
header ring0.submit +0x00=0x110 +0x40=0x110 +0x80=0x1
header ring0.complete +0x00=0xa8 +0x40=0xa8 +0xc0=0x1
header ring0.complete +0x00=0xf8 +0x40=0xf8 +0xc0=0x1
header queue.submit +0x80=0x1
header queue.complete +0xc0=0x1
post queueB COMMAND_BUFFER seqno=1 size=40 0x70000000002 0x200 0x0
@@ -83,7 +83,7 @@ interrupt 3
take queueB CB_COMPLETE seqno=1 size=48 0x200 0x0 0x0 0x0
arm queueB recheck empty
header ring0.submit +0x00=0x110 +0x40=0x110 +0x80=0x1
header ring0.complete +0x00=0xa8 +0x40=0xa8 +0xc0=0x1
header ring0.complete +0x00=0xf8 +0x40=0xf8 +0xc0=0x1
header queue.submit +0x00=0x28 +0x40=0x28 +0x80=0x1
header queue.complete +0x00=0x30 +0x08=0x1 +0x40=0x30 +0xc0=0x1
post ring0 CONTEXT_CLOSE seqno=9 size=24 0x7
@@ -92,7 +92,7 @@ interrupt 0
take ring0 COMPLETE seqno=9 size=24 0x0
arm ring0 recheck empty
header ring0.submit +0x00=0x128 +0x40=0x128 +0x80=0x1
header ring0.complete +0x00=0xc0 +0x40=0xc0 +0xc0=0x1
header ring0.complete +0x00=0x110 +0x40=0x110 +0xc0=0x1
header queue.submit +0x00=0x28 +0x40=0x28 +0x80=0x1
header queue.complete +0x00=0x30 +0x08=0x1 +0x40=0x30 +0xc0=0x1
write STATUS = 0x0
@@ -195,6 +195,32 @@ fn an_unreadable_vt_message_is_answered_malformed() {
assert!(handed.lock().is_empty() && taken_handed.lock().is_empty());
}
/// An unreadable `VT_MESSAGE` whose struct reads gives back the lends it names, as a `rels` before
/// its `VT_STATUS`: the guest's kext holds each lend of a message it posted until a `rels` names
/// it, and the host never sees this one. One that names none gets no `rels`, and neither does a
/// guest that did not take `VT_MESSAGES`, which sends none
#[test]
fn an_unreadable_vt_message_gives_back_the_lends_it_names() {
let (mut rig, handed) = vt_rig();
take_and_start(&rig, RGFX_FEATURE_VT_MESSAGES);
let seqno = rig.send(vt_message(0x4001, &[(0x4000, 0x4000)], &[7, 9]));
let mut release = 24u32.to_be_bytes().to_vec();
release.extend_from_slice(b"rels");
release.extend_from_slice(&7u64.to_be_bytes());
release.extend_from_slice(&9u64.to_be_bytes());
assert_eq!(vt_event(&mut rig), release);
assert_eq!(status(&mut rig), (seqno, RGFX_VT_STATUS_MALFORMED));
let seqno = rig.send(vt_message(0x4001, &[(0x4000, 0x4000)], &[]));
assert_eq!(status(&mut rig), (seqno, RGFX_VT_STATUS_MALFORMED));
let (mut untaken, untaken_handed) = vt_rig();
untaken.start();
let seqno = untaken.send(vt_message(64, &[(0x4000, 0x4000)], &[7]));
assert_eq!(status(&mut untaken), (seqno, RGFX_VT_STATUS_MALFORMED));
assert!(untaken.quiet_for(20));
assert!(handed.lock().is_empty() && untaken_handed.lock().is_empty());
}
/// A host message is dropped for a guest that did not take `VT_MESSAGES` and once the device is
/// reset, and a link made before the reset says it is stale.
#[test]
@@ -110,6 +110,32 @@ impl VtLink {
}
}
/// The `rels` box that gives back the lends a `VT_MESSAGE` the device could not read names
/// ([`read_message`]), where its struct reads and names any: its big-endian size, `rels`, then
/// each nonzero lend of its first `surface_count` (at most [`RGFX_VT_MESSAGE_SURFACES`]),
/// big-endian. The guest's kext holds each lend of a message it posted until a `rels` names it,
/// so a message the host never sees would hold them to the kext's stop. `None` where the struct
/// does not read or names no lend.
pub(crate) fn unread_lends_release(message: &Message) -> Option<Vec<u8>> {
let (command, _) = RgfxVtMessage::read_from_prefix(&message.bytes).ok()?;
let lends: Vec<u64> = (command.surfaces.iter())
.take(command.surface_count as usize)
.copied()
.filter(|&lend| lend != 0)
.collect();
if lends.is_empty() {
return None;
}
let size = u32::try_from(8 + 8 * lends.len()).ok()?;
let mut release = Vec::with_capacity(size as usize);
release.extend_from_slice(&size.to_be_bytes());
release.extend_from_slice(b"rels");
for lend in lends {
release.extend_from_slice(&lend.to_be_bytes());
}
Some(release)
}
/// A `VT_MESSAGE`'s answer: `VT_STATUS` with `status`.
pub(crate) fn vt_status(seqno: u64, status: i32) -> Vec<u8> {
RgfxVtStatus {
+261 -9
View File
@@ -1,12 +1,15 @@
//! The device's display as the guest drives it, and [`Screen`], what shows it on the host: the
//! window of `reims-vgpu`'s glue, or a fixed mode with nothing shown ([`FixedScreen`]).
//!
//! **Modes.** The display offers one mode: the screen's size and refresh rate ([`Screen::mode`]),
//! which for a window is its size in pixels at its host screen's rate, with the host screen's
//! scale, which a guest that took `DISPLAY_SCALE` is told after the display's record
//! (`RgfxDisplayScale`). The guest runs at the host screen's rate. When the screen's mode changes
//! (the window resized, or moved to a screen of another scale), the device tells the guest with
//! `DISPLAY_CHANGED`, and the guest asks `GET_DISPLAYS` again (`refresh`).
//! **Modes.** The display offers first, and prefers, the screen's size and refresh rate
//! ([`Screen::mode`]), which for a window is its size in pixels at its host screen's rate, with
//! the host screen's scale, which a guest that took `DISPLAY_SCALE` is told after the display's
//! record (`RgfxDisplayScale`). After it come the smaller modes of its ratio at a Mac's steps
//! ([`offered_modes`]), each at the same rate: the guest runs at the host screen's rate whichever
//! it picks, and a window keeps its size at a smaller mode and shows it scaled to fill it
//! (`reims-vgpu`'s `graphics::sink`). When the screen's mode changes (the window resized, or
//! moved to a screen of another scale), the device tells the guest with `DISPLAY_CHANGED`, and
//! the guest asks `GET_DISPLAYS` again (`refresh`); the smaller modes follow the first.
//!
//! **Scanout.** `SET_SCANOUT` names the pixels the display shows, in the scanout's room of the
//! region (`RGFX_SCANOUT_SPAN` bytes at `RGFX_ALLOCATIONS_OFFSET`, before the processes' blocks,
@@ -31,8 +34,9 @@
//! each with a [`Screen`] of its own (docs/graphics-kext/design.md, "Multiple displays"). Each
//! display's scanout lies in a room of its own: the scanout's room split evenly among them
//! ([`scanout_room`], [`scanout_room_at`]), so one display keeps the whole room, as before any
//! display had a room of its own. On a device of more than one display each display offers only
//! display had a room of its own. On a device of more than one display each display offers first
//! a mode whose scanout fits its room ([`offered_in_room`]); with one, the screen's mode as it is.
//! Each smaller mode is offered only where its scanout fits the room.
pub(crate) mod cursor_color;
@@ -98,6 +102,77 @@ pub fn offered_in_room(mode: Mode, count: u32) -> Mode {
}
}
/// The steps of a display's smaller modes, largest first: each a fraction of its first mode's
/// width, so that a 3840 × 2160 screen is offered 3360 × 1890, 3008 × 1692, 2880 × 1620,
/// 2560 × 1440, 1920 × 1080 and 1440 × 810 below its own. They come from two sources:
/// - 7/8, 3/4, 1/2 and 3/8 are steps of the modes of its own ratio a Mac's built-in panel lists
/// below its native one: CoreGraphics lists the 3072 × 1920 panel of a MacBook Pro 16-inch
/// (2019, macOS 26.7.1) at 2688 × 1680, 2304 × 1440, 1536 × 960, 1440 × 900, 1280 × 800 and
/// 1152 × 720 below it (`CGDisplayCopyAllDisplayModes`, measured 2026-12-02);
/// - 47/60 and 2/3 are the steps of 3008 × 1692 and 2560 × 1440, which a Mac lists for an
/// external 3840 × 2160 screen, taken from a user's report and from what is known of that
/// list; they were not read on a Mac of ours.
///
/// That panel's 15/32 and 5/12 (1440 × 900 and 1280 × 800) are left out as near twins of 1/2,
/// and so are the 1650 × 1050 it lists, of another ratio, and the 3584 × 2240 above its native
/// mode.
const SMALLER_MODE_STEPS: [(u64, u64); 6] = [(7, 8), (47, 60), (3, 4), (2, 3), (1, 2), (3, 8)];
/// The smallest smaller mode a display offers, its longer side then its shorter: the smallest a
/// Mac takes for its desktop. On that MacBook Pro CoreGraphics lists 800 × 600 usable for the
/// desktop and 840 × 524 and 640 × 480 not (`CGDisplayModeIsUsableForDesktopGUI`); a portrait
/// screen's modes take the floor turned.
const SMALLER_MODE_FLOOR: (u32, u32) = (800, 600);
// A host-side bound: the guest reads each display's count from the answer, so cbindgen leaves it out of
// the wire header.
/// The most modes a display offers, its first among them.
/// cbindgen:ignore
pub const MODES_MAX: usize = 8;
// The first mode and one for each step fit.
const _: () = assert!(SMALLER_MODE_STEPS.len() < MODES_MAX);
/// The modes a display whose screen offers `mode` offers its guest on a device of `count`
/// displays, at most [`MODES_MAX`]: first the mode [`offered_in_room`] gives, which the guest
/// prefers, then each smaller mode of its ratio at [`SMALLER_MODE_STEPS`] that is at least
/// [`SMALLER_MODE_FLOOR`] and whose scanout fits the display's room ([`scanout_room`], rows laid
/// out as [`laid_out`] says), largest first. A smaller mode is a multiple of 16 pixels wide and an
/// even number high (the steps of a window's offered modes, `reims-vgpu-window`'s
/// `geometry::offered_mode`): its width is the step's fraction of the first mode's, rounded down
/// to a multiple of 16, and its height the first mode's ratio of that width, rounded down to
/// even. Every mode has the first's refresh rate and scale.
pub fn offered_modes(mode: Mode, count: u32) -> Vec<Mode> {
let first = offered_in_room(mode, count);
let mut modes = vec![first];
let (w, h) = (u64::from(first.width), u64::from(first.height));
if w == 0 || h == 0 {
return modes;
}
let room = scanout_room(count);
for (numerator, denominator) in SMALLER_MODE_STEPS {
let width = (w * numerator / denominator) & !15;
let height = (width * h / w) & !1;
let (Ok(width), Ok(height)) = (u32::try_from(width), u32::try_from(height)) else {
continue;
};
let (longer, shorter) = (width.max(height), width.min(height));
if longer < SMALLER_MODE_FLOOR.0
|| shorter < SMALLER_MODE_FLOOR.1
|| laid_out(width, height) > room
|| modes.iter().any(|m| (m.width, m.height) == (width, height))
{
continue;
}
modes.push(Mode {
width,
height,
..first
});
}
modes
}
/// A display mode: pixels each way and a refresh rate, and the scale of the host screen that
/// shows it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -165,8 +240,9 @@ pub struct CursorImage {
/// (the control thread and the refresh thread, never inside a call of the host's) and must not
/// wait for the device.
pub trait Screen: Send + Sync + 'static {
/// The one mode the display offers now: for a window, its size in pixels at its host
/// screen's refresh rate, with that screen's scale. Asked at `GET_DISPLAYS`, and at each
/// The mode the display offers first now, which the guest prefers: for a window, its size in
/// pixels at its host screen's refresh rate, with that screen's scale. Asked at
/// `GET_DISPLAYS`, where the smaller modes follow from it ([`offered_modes`]), and at each
/// refresh, where a change is told to the guest.
fn mode(&self) -> Mode;
@@ -327,6 +403,182 @@ mod tests {
}
}
/// The modes a display offers for a screen of `width` x `height` on a device of `count`
/// displays, as sizes.
fn sizes(width: u32, height: u32, count: u32) -> Vec<(u32, u32)> {
let mode = Mode {
width,
height,
refresh_mhz: 59_940,
scale_120ths: 240,
};
offered_modes(mode, count)
.iter()
.map(|m| (m.width, m.height))
.collect()
}
/// A 4K screen is offered the modes a Mac lists for an external 4K screen, its own first; a
/// screen of the Mac panel four of the steps were read from is offered that panel's modes at
/// those steps, and two of the external screen's steps between them
#[test]
fn a_display_offers_its_screen_s_ratio_at_a_mac_s_steps() {
assert_eq!(
sizes(3840, 2160, 1),
[
(3840, 2160),
(3360, 1890),
(3008, 1692),
(2880, 1620),
(2560, 1440),
(1920, 1080),
(1440, 810)
]
);
assert_eq!(
sizes(3072, 1920, 1),
[
(3072, 1920),
(2688, 1680),
(2400, 1500),
(2304, 1440),
(2048, 1280),
(1536, 960),
(1152, 720)
]
);
assert_eq!(
sizes(2560, 1440, 2),
[
(2560, 1440),
(2240, 1260),
(2000, 1124),
(1920, 1080),
(1696, 954),
(1280, 720)
]
);
}
/// Every mode a display offers carries its first mode's refresh rate and scale, the guest
/// running at the host screen's rate whichever it picks; a smaller mode is a multiple of 16
/// pixels wide and even high, smaller each way than the first, and of its ratio to within
/// those steps; there are at most `MODES_MAX`
#[test]
fn every_mode_has_the_screen_s_rate_and_steps() {
for (w, h) in [
(3840, 2160),
(3456, 2234),
(1712, 1148),
(1366, 768),
(1001, 777),
(2160, 3840),
(5120, 1440),
(7680, 4320),
] {
for count in 1..=crate::wire::RGFX_DISPLAYS_MAX {
let mode = Mode {
width: w,
height: h,
refresh_mhz: 143_912,
scale_120ths: 180,
};
let modes = offered_modes(mode, count);
assert!(modes.len() <= MODES_MAX, "{w}x{h} on {count}");
assert_eq!(modes[0], offered_in_room(mode, count));
let (fw, fh) = (u64::from(modes[0].width), u64::from(modes[0].height));
for m in &modes[1..] {
assert_eq!((m.refresh_mhz, m.scale_120ths), (143_912, 180));
assert_eq!((m.width % 16, m.height % 2), (0, 0), "{m:?} of {w}x{h}");
assert!(m.width < modes[0].width && m.height < modes[0].height);
assert!(laid_out(m.width, m.height) <= scanout_room(count));
// The first mode's height for the width, less under two rows.
let exact = u64::from(m.width) * fh / fw;
assert!(exact - u64::from(m.height) < 2, "{m:?} of {w}x{h}");
}
}
}
}
/// Sizes of odd pixels, a fixed screen's (`resolution=`), take the steps too, each smaller
/// mode on even pixels; and a portrait screen's modes are its own ratio, the floor turned
#[test]
fn odd_and_portrait_screens_offer_their_own_ratio() {
assert_eq!(sizes(1366, 768, 1), [(1366, 768), (1184, 664)]);
assert_eq!(sizes(1001, 777, 1), [(1001, 777), (864, 670)]);
assert_eq!(
sizes(1080, 1920, 1),
[
(1080, 1920),
(944, 1678),
(832, 1478),
(800, 1422),
(720, 1280)
]
);
assert_eq!(
sizes(1440, 2560, 1),
[
(1440, 2560),
(1248, 2218),
(1120, 1990),
(1072, 1904),
(960, 1706),
(720, 1280)
]
);
}
/// No smaller mode is below 800 x 600, the smallest a Mac takes for its desktop (960 x 600
/// is at it); a screen's own mode is offered whatever its size, and alone where no step
/// reaches the floor
#[test]
fn no_smaller_mode_is_below_the_floor() {
assert_eq!(
sizes(1280, 800, 1),
[(1280, 800), (1120, 700), (992, 620), (960, 600)]
);
assert_eq!(
sizes(1920, 1080, 1),
[
(1920, 1080),
(1680, 944),
(1504, 846),
(1440, 810),
(1280, 720)
]
);
assert_eq!(sizes(1024, 768, 1), [(1024, 768), (896, 672), (800, 600)]);
assert_eq!(sizes(800, 600, 1), [(800, 600)]);
assert_eq!(sizes(640, 480, 1), [(640, 480)]);
assert_eq!(sizes(0, 0, 1), [(0, 0)]);
}
/// The first mode is sized to the display's room on a device of several, and the smaller
/// modes follow it; on a device of one a screen too large for the room is offered as it is,
/// and of its smaller modes only those whose scanout the room holds
#[test]
fn smaller_modes_keep_to_the_display_s_room() {
assert_eq!(sizes(7680, 4320, 4), sizes(3840, 2160, 4));
assert_eq!(
sizes(7680, 4320, 2),
[
(5440, 3060),
(4752, 2672),
(4256, 2394),
(4080, 2294),
(3616, 2034),
(2720, 1530),
(2032, 1142)
]
);
// 7168 x 7168, 6416 x 6416 and 6144 x 6144 miss the room's 128 MiB.
assert_eq!(
sizes(8192, 8192, 1),
[(8192, 8192), (5456, 5456), (4096, 4096), (3072, 3072)]
);
}
/// A scanout's range runs from its first row's start to its last row's end
#[test]
fn a_scanout_s_range_ends_at_its_last_pixel() {
+7 -4
View File
@@ -19,6 +19,7 @@
//! nothing to do.
//! - [`clock`] is the device's clock, `HOST_TIME`'s, and [`clock::runtime`] places the
//! platform's GPU times on it before they reach the guest.
//! - [`threads`] is what each thread the device starts runs first, which the host sets.
//! - [`trip`] times a command buffer's completion's trip down to the guest and the guest's next
//! buffer's up, by stage: a diagnostic, off unless reims-vgpu turns it on.
@@ -31,8 +32,9 @@ pub mod keep;
pub mod managed;
pub mod ops;
pub mod region;
pub mod snapshot;
mod ring;
pub mod snapshot;
pub mod threads;
// The trip line's histograms are a host diagnostic: cbindgen leaves the module out of the wire header.
/// cbindgen:ignore
pub mod trip;
@@ -40,9 +42,10 @@ mod wake;
pub mod wire;
pub use device::{
CompleteAnswer, CompletionPoster, Device, DoorbellAt, Host, PointerLink, PoolAnswer,
PresentAnswer, PrivateAnswer, QueueClaim, REGION_SIZE, RingDegradation, SLOW_ANSWER_NS, Spot,
Then, VtAnswer, VtLink, VtMessage, VtSurface,
CompleteAnswer, CompletionPoster, Device, DoorbellAt, GuestBundle, HoldWaker, Host,
PointerLink, PoolAnswer, PresentAnswer, PrivateAnswer, QueueClaim, REGION_SIZE,
RingDegradation, SLOW_ANSWER_NS, Spot, Then, VtAnswer, VtLink, VtMessage, VtSurface,
raise_elsewhere,
};
pub use display::{CursorImage, FixedScreen, Mode, Scanout, Screen};
pub use wake::RawDoorbell;
+8
View File
@@ -430,6 +430,14 @@ impl Region {
.then(|| self.atomic_u64(offset).load(Ordering::Acquire))
}
/// Swaps the `u32` the guest keeps at `offset` for `value`, atomically and in the order of
/// every sequentially consistent access (`SeqCst`), as the guest reads and writes it: the
/// value it held. `None`, swapping nothing, where it is not 4-aligned and inside the region.
pub fn swap_u32(&self, offset: u64, value: u32) -> Option<u32> {
(offset.is_multiple_of(4) && self.contains(offset, 4))
.then(|| self.atomic_u32(offset).swap(value, Ordering::SeqCst))
}
/// The `u64` at `offset`, which is 8-aligned and inside the region, as an atomic.
pub(crate) fn atomic_u64(&self, offset: u64) -> &AtomicU64 {
assert!(
+110 -36
View File
@@ -48,6 +48,8 @@ pub struct DeviceSnapshot {
pub status: u32,
/// Negotiated `DRIVER_FEATURES` bitmask.
pub driver_features: u64,
/// Negotiated `DRIVER_FEATURES_EXT` bitmask.
pub driver_features_ext: u32,
/// Control submission ring `control_done` count.
pub control_done: u64,
/// Control submission ring consumer byte count.
@@ -68,9 +70,15 @@ pub struct DeviceSnapshot {
pub queues: Vec<QueueSnapshot>,
}
fn put_u8(o: &mut Vec<u8>, v: u8) { o.push(v); }
fn put_u32(o: &mut Vec<u8>, v: u32) { o.extend_from_slice(&v.to_le_bytes()); }
fn put_u64(o: &mut Vec<u8>, v: u64) { o.extend_from_slice(&v.to_le_bytes()); }
fn put_u8(o: &mut Vec<u8>, v: u8) {
o.push(v);
}
fn put_u32(o: &mut Vec<u8>, v: u32) {
o.extend_from_slice(&v.to_le_bytes());
}
fn put_u64(o: &mut Vec<u8>, v: u64) {
o.extend_from_slice(&v.to_le_bytes());
}
fn put_bytes(o: &mut Vec<u8>, b: &[u8]) {
put_u64(o, b.len() as u64);
o.extend_from_slice(b);
@@ -82,20 +90,26 @@ fn get_u8(i: &mut &[u8]) -> Option<u8> {
Some(b)
}
fn get_u32(i: &mut &[u8]) -> Option<u32> {
if i.len() < 4 { return None; }
if i.len() < 4 {
return None;
}
let (a, rest) = i.split_at(4);
*i = rest;
Some(u32::from_le_bytes(a.try_into().ok()?))
}
fn get_u64(i: &mut &[u8]) -> Option<u64> {
if i.len() < 8 { return None; }
if i.len() < 8 {
return None;
}
let (a, rest) = i.split_at(8);
*i = rest;
Some(u64::from_le_bytes(a.try_into().ok()?))
}
fn get_bytes(i: &mut &[u8]) -> Option<Vec<u8>> {
let n = usize::try_from(get_u64(i)?).ok()?;
if i.len() < n { return None; }
if i.len() < n {
return None;
}
let (a, rest) = i.split_at(n);
*i = rest;
Some(a.to_vec())
@@ -124,9 +138,10 @@ fn read_vec<T>(
impl DeviceSnapshot {
/// Encodes this device snapshot into `out`.
pub fn encode(&self, o: &mut Vec<u8>) {
put_u32(o, 1);
put_u32(o, 2);
put_u32(o, self.status);
put_u64(o, self.driver_features);
put_u32(o, self.driver_features_ext);
put_u64(o, self.control_done);
put_u64(o, self.control_submit_count);
put_u8(o, u8::from(self.control_submit_broken));
@@ -134,15 +149,19 @@ impl DeviceSnapshot {
put_u64(o, self.vt_ring_count);
put_u32(o, self.pages.len() as u32);
for &p in &self.pages { put_u32(o, p); }
for &p in &self.pages {
put_u32(o, p);
}
put_u32(o, self.displays.len() as u32);
for d in &self.displays {
match d.scanout {
Some(s) => {
put_u8(o, 1);
put_u32(o, s.width); put_u32(o, s.height);
put_u32(o, s.stride); put_u64(o, s.offset);
put_u32(o, s.width);
put_u32(o, s.height);
put_u32(o, s.stride);
put_u64(o, s.offset);
}
None => put_u8(o, 0),
}
@@ -152,8 +171,10 @@ impl DeviceSnapshot {
match d.told {
Some(m) => {
put_u8(o, 1);
put_u32(o, m.width); put_u32(o, m.height);
put_u32(o, m.refresh_mhz); put_u32(o, m.scale_120ths);
put_u32(o, m.width);
put_u32(o, m.height);
put_u32(o, m.refresh_mhz);
put_u32(o, m.scale_120ths);
}
None => put_u8(o, 0),
}
@@ -161,8 +182,10 @@ impl DeviceSnapshot {
match &d.cursor_image {
Some(c) => {
put_u8(o, 1);
put_u32(o, c.width); put_u32(o, c.height);
put_u32(o, c.hot_spot.0); put_u32(o, c.hot_spot.1);
put_u32(o, c.width);
put_u32(o, c.height);
put_u32(o, c.hot_spot.0);
put_u32(o, c.hot_spot.1);
put_bytes(o, &c.rgba);
}
None => put_u8(o, 0),
@@ -171,10 +194,13 @@ impl DeviceSnapshot {
put_u32(o, self.region_blocks.len() as u32);
for b in &self.region_blocks {
put_u64(o, b.offset); put_u64(o, b.size);
put_u64(o, b.offset);
put_u64(o, b.size);
put_u8(o, u8::from(b.shared));
put_u32(o, b.holders.len() as u32);
for &h in &b.holders { put_u32(o, h); }
for &h in &b.holders {
put_u32(o, h);
}
}
put_u32(o, self.queues.len() as u32);
@@ -191,9 +217,13 @@ impl DeviceSnapshot {
/// Decodes a device snapshot from `i`.
pub fn decode(i: &mut &[u8]) -> Option<Self> {
if get_u32(i)? != 1 { return None; }
let version = get_u32(i)?;
if !matches!(version, 1 | 2) {
return None;
}
let status = get_u32(i)?;
let driver_features = get_u64(i)?;
let driver_features_ext = if version == 2 { get_u32(i)? } else { 0 };
let control_done = get_u64(i)?;
let control_submit_count = get_u64(i)?;
let control_submit_broken = get_u8(i)? != 0;
@@ -204,35 +234,59 @@ impl DeviceSnapshot {
let displays = read_vec(i, 14, |i| {
let scanout = if get_u8(i)? != 0 {
Some(Scanout {
width: get_u32(i)?, height: get_u32(i)?,
stride: get_u32(i)?, offset: get_u64(i)?,
width: get_u32(i)?,
height: get_u32(i)?,
stride: get_u32(i)?,
offset: get_u64(i)?,
})
} else { None };
} else {
None
};
let vblank = get_u8(i)? != 0;
let asleep = get_u8(i)? != 0;
let refreshes = get_u64(i)?;
let told = if get_u8(i)? != 0 {
Some(Mode {
width: get_u32(i)?, height: get_u32(i)?,
refresh_mhz: get_u32(i)?, scale_120ths: get_u32(i)?,
width: get_u32(i)?,
height: get_u32(i)?,
refresh_mhz: get_u32(i)?,
scale_120ths: get_u32(i)?,
})
} else { None };
} else {
None
};
let changed = get_u8(i)? != 0;
let cursor_image = if get_u8(i)? != 0 {
Some(CursorImage {
width: get_u32(i)?, height: get_u32(i)?,
width: get_u32(i)?,
height: get_u32(i)?,
hot_spot: (get_u32(i)?, get_u32(i)?),
rgba: get_bytes(i)?,
})
} else { None };
Some(DisplaySnapshot { scanout, vblank, asleep, refreshes, told, changed, cursor_image })
} else {
None
};
Some(DisplaySnapshot {
scanout,
vblank,
asleep,
refreshes,
told,
changed,
cursor_image,
})
})?;
let region_blocks = read_vec(i, 21, |i| {
let offset = get_u64(i)?;
let size = get_u64(i)?;
let shared = get_u8(i)? != 0;
let holders = read_vec(i, 4, get_u32)?;
Some(RegionBlockSnapshot { offset, size, holders, shared })
Some(RegionBlockSnapshot {
offset,
size,
holders,
shared,
})
})?;
let queues = read_vec(i, 45, |i| {
Some(QueueSnapshot {
@@ -247,10 +301,18 @@ impl DeviceSnapshot {
})?;
Some(DeviceSnapshot {
status, driver_features, control_done,
control_submit_count, control_submit_broken,
control_completion_count, vt_ring_count,
pages, displays, region_blocks, queues,
status,
driver_features,
driver_features_ext,
control_done,
control_submit_count,
control_submit_broken,
control_completion_count,
vt_ring_count,
pages,
displays,
region_blocks,
queues,
})
}
}
@@ -261,11 +323,12 @@ mod tests {
#[test]
fn decode_rejects_oversized_counts_without_allocating() {
// Minimal valid header (version=1 + fixed scalar fields = 49 bytes).
// The fixed fields in version 2 occupy 53 bytes.
let mut base = Vec::new();
let empty = DeviceSnapshot {
status: 1,
driver_features: 2,
driver_features_ext: 1,
control_done: 3,
control_submit_count: 4,
control_submit_broken: false,
@@ -278,16 +341,27 @@ mod tests {
};
empty.encode(&mut base);
let mut s = base.as_slice();
assert_eq!(DeviceSnapshot::decode(&mut s), Some(empty));
assert_eq!(DeviceSnapshot::decode(&mut s), Some(empty.clone()));
assert!(s.is_empty());
let mut legacy = base.clone();
legacy[..4].copy_from_slice(&1u32.to_le_bytes());
legacy.drain(16..20);
let mut legacy = legacy.as_slice();
let mut legacy_device = empty;
legacy_device.driver_features_ext = 0;
assert_eq!(DeviceSnapshot::decode(&mut legacy), Some(legacy_device));
assert!(legacy.is_empty());
// Overwrite each of the 4 top-level collection counts with u32::MAX.
// Header length before pages count: 4 + 4 + 8 + 8 + 8 + 1 + 8 + 8 = 49.
for offset in [49usize, 53, 57, 61] {
for offset in [53usize, 57, 61, 65] {
let mut bad = base.clone();
bad[offset..offset + 4].copy_from_slice(&u32::MAX.to_le_bytes());
let mut sl = bad.as_slice();
assert!(DeviceSnapshot::decode(&mut sl).is_none(), "offset {offset} must fail");
assert!(
DeviceSnapshot::decode(&mut sl).is_none(),
"offset {offset} must fail"
);
}
}
}
+22
View File
@@ -0,0 +1,22 @@
//! What each thread the device starts runs first ([`on_start`]): the host's, set once. reims-vgpu
//! sets it to keep the thread's whole name for its pacing line where the OS cuts the name it
//! gives the thread (Linux, at 15 bytes: every `reims-vgpu.graphics-…` name reads
//! `reims-vgpu.grap` there). A diagnostic: what it does is free under the contract.
use std::sync::OnceLock;
/// The host's function.
static ON_START: OnceLock<fn()> = OnceLock::new();
/// Each thread the device starts from now on calls `f` first: the control and refresh threads,
/// ring 0's lanes and each queue's service thread. The first given wins.
pub fn on_start(f: fn()) {
let _ = ON_START.set(f);
}
/// The calling thread, one the device started, calls the host's function, where it set one.
pub(crate) fn started() {
if let Some(f) = ON_START.get() {
f();
}
}
+323 -3
View File
@@ -712,12 +712,133 @@ pub const RGFX_REG_POOL_BASE_HI: u32 = 0x048;
pub const RGFX_REG_POOL_LENGTH_LO: u32 = 0x04c;
/// `POOL_LENGTH_HI`, RO: as [`RGFX_REG_POOL_LENGTH_LO`], its high 32 bits.
pub const RGFX_REG_POOL_LENGTH_HI: u32 = 0x050;
/// `GUEST_BUNDLE`, WO: what the guest's accelerator found of its Metal bundle as WindowServer
/// opened the display, once a boot, so the host can tell its user why a desktop runs without
/// Metal: in bits 0 to 7 an `RGFX_GUEST_BUNDLE_*` (ours, another version's, none, or RgfxGate's
/// install still under way), in bits 8 to 15 the wire version another version's bundle's marker
/// names (0 where it names none the kext knows), in bits 16 to 23 RgfxGate's install pass, an
/// `RGFX_GATE_*`, and in bits 24 to 31 the error its failed write gave (`errno`, 0 for none). It
/// reads 0. A host that does not know it ignores the write, as at any offset it does not know, and
/// the guest acts on nothing of it, so it needs no feature: a kext built before it never writes
/// it, and a host then says nothing of the bundle.
pub const RGFX_REG_GUEST_BUNDLE: u32 = 0x054;
/// `FEATURES_EXT`, RO: feature bits 64 to 95 the host offers. The guest uses each with no take,
/// but those [`RGFX_REG_DRIVER_FEATURES_EXT`] takes ([`RGFX_FEATURE_EXT_SURFACE_HOLD`]): a guest
/// that sees one of the others may send the messages it names, and the host carries out nothing
/// else for a guest that does, so a guest that never reads it gets the wire it had before. It
/// reads [`RGFX_FEATURE_EXT_SHARED_TEXTURE_NAMES`] and [`RGFX_FEATURE_EXT_SURFACE_HOLD`] where the
/// host offers them; 0 from a host older than it, as at any offset a host does not know. A write
/// is ignored. Bit 1 is offered by no host: hosts built before the hold word left the block's
/// header offered `SURFACE_HOLD` there, with the word in the header, and kexts built before it
/// take it; a write of it takes nothing, so such a kext and this host, or this kext and such a
/// host, take no hold.
pub const RGFX_REG_FEATURES_EXT: u32 = 0x058;
/// `DRIVER_FEATURES_EXT`, RW: the feature bits 64 to 95 the guest's driver took of those
/// `FEATURES_EXT` offers that are taken ([`RGFX_FEATURE_EXT_SURFACE_HOLD`]). A write takes the
/// bits written that `FEATURES_EXT` offers and that are taken, and a read answers the bits taken.
/// As at `DRIVER_FEATURES_LO`, a write while `STATUS` reads [`RGFX_STATUS_DRIVER_READY`] is
/// ignored, and a reset clears it. A guest that never writes it (the option ROM, a kext built
/// before it) gets the wire it had before; a host older than it reads 0 there and ignores a
/// write, as at any offset it does not know.
pub const RGFX_REG_DRIVER_FEATURES_EXT: u32 = 0x05c;
/// `FEATURES_EXT` bit 0, feature bit 64, `SHARED_TEXTURE_NAMES`: ring 0 carries
/// [`RGFX_CMD_SHARED_TEXTURE_CREATE`], a process's texture another process may open
/// (`newSharedTextureWithDescriptor:`), and the messages the accelerator kext posts for its handle:
/// [`RGFX_CMD_SHARED_TEXTURE_NAME`], which names it device-wide, [`RGFX_CMD_SHARED_TEXTURE_IMPORT`],
/// by which another process's new texture is the same host texture, and
/// [`RGFX_CMD_SHARED_TEXTURE_UNNAME`]. Every host offers it.
pub const RGFX_FEATURE_EXT_SHARED_TEXTURE_NAMES: u32 = 1 << 0;
/// `FEATURES_EXT` bit 2, feature bit 66, `SURFACE_HOLD`, taken in
/// [`RGFX_REG_DRIVER_FEATURES_EXT`]. A host whose GPU's memory is its own (a device of one
/// memory) may make an image in place over guest pages it imports by their pointer by copying the
/// bytes under the image out and back around the image's first layout move, so a CPU write of
/// those bytes between the two copies is lost. Where the guest took it:
/// - **A cached surface's hold word.** The block of a surface with a device cache
/// ([`RGFX_SURFACE_PAGES_CACHED`]) holds a 32-bit word in its own part, which no process maps:
/// the first of the [`RGFX_SURFACE_HOLD_ROOM`] bytes right before its runs, at region offset
/// `runs_offset - RGFX_SURFACE_HOLD_ROOM`, which the kext stores 0 into as it caches the block.
/// So only the kext and the host write it. Before such a make over the block's pages the host
/// raises it ([`RGFX_SURFACE_HOLD_RAISED`]), and after a full fence reads the surface's CPU
/// generation in the block's header again: where it moved since the host decided on the make,
/// the host lowers the word and makes nothing in place. Once the bytes are back it stores 0
/// there. A block whose word would lie in its first [`RGFX_SURFACE_HOLD_ROOM`] bytes, where
/// its header lies (its runs less than twice that past its start), has none, and gets no image
/// made so over its pages. A read-write CPU lock stores the new generation, and after a full
/// fence reads the word: while it is raised, the lock sets [`RGFX_SURFACE_HOLD_WAITED`] beside
/// it and waits, looking again at the device's next vector or within 1 ms. So either the host
/// reads the lock's generation and makes nothing in place, or the lock goes on once the bytes
/// are back. A read-only lock waits for nothing.
/// - **Answered creates over pages.** A [`RGFX_CMD_TEXTURE_FROM_BUFFER`] or
/// [`RGFX_CMD_LINEAR_TEXTURE_FROM_BUFFER`] over a buffer a [`RGFX_CMD_BUFFER_OVER_PAGES`]
/// made (the host's refusal of it among them) is answered by an [`RGFX_EVT_COMPLETE`] of
/// [`RGFX_STATUS_OK`] once carried out, the texture made or refused, and the guest's create
/// waits for that answer, so the creating thread writes the buffer only after the make. Every
/// such create is answered: the host answers a pages block before it imports the block's
/// pages, and on Linux the import alone finds whether it goes by the pages' pointer, the kind
/// of import a make copies out and back.
///
/// A guest that does not take it gets no image made so over a cached surface's pages, and no
/// answer. The host offers it where its GPU's memory is its own. The x86-64 and arm64e kexts
/// take it.
pub const RGFX_FEATURE_EXT_SURFACE_HOLD: u32 = 1 << 2;
/// The bytes of a cached surface's block right before its runs that hold its hold word
/// ([`RGFX_FEATURE_EXT_SURFACE_HOLD`]), a `u32` at their start: a page of the block's own part,
/// past the part its processes map, which no process maps.
pub const RGFX_SURFACE_HOLD_ROOM: u64 = 0x1000;
/// The hold word's bit the host raises around a make that copies the pages' bytes out and back
/// ([`RGFX_FEATURE_EXT_SURFACE_HOLD`]).
pub const RGFX_SURFACE_HOLD_RAISED: u32 = 1 << 0;
/// The hold word's bit a read-write CPU lock sets beside [`RGFX_SURFACE_HOLD_RAISED`] while it
/// waits ([`RGFX_FEATURE_EXT_SURFACE_HOLD`]), which the host counts.
pub const RGFX_SURFACE_HOLD_WAITED: u32 = 1 << 1;
/// A [`RGFX_REG_GUEST_BUNDLE`] value's bundle field: the kext's own version's bundle is on disk,
/// and the accelerator registered for it.
pub const RGFX_GUEST_BUNDLE_OURS: u32 = 1;
/// A [`RGFX_REG_GUEST_BUNDLE`] value's bundle field: the bundle's executable is there without the
/// marker of the kext's version, so the accelerator stays unregistered for the boot.
pub const RGFX_GUEST_BUNDLE_OTHER_VERSION: u32 = 2;
/// A [`RGFX_REG_GUEST_BUNDLE`] value's bundle field: no bundle's executable is there, so the
/// accelerator stays unregistered for the boot.
pub const RGFX_GUEST_BUNDLE_ABSENT: u32 = 3;
/// A [`RGFX_REG_GUEST_BUNDLE`] value's bundle field: RgfxGate's install pass had not ended, so the
/// accelerator stays unregistered for the boot.
pub const RGFX_GUEST_BUNDLE_GATE_BUSY: u32 = 4;
/// Where a [`RGFX_REG_GUEST_BUNDLE`] value's other version starts: bits 8 to 15.
pub const RGFX_GUEST_BUNDLE_VERSION_SHIFT: u32 = 8;
/// Where a [`RGFX_REG_GUEST_BUNDLE`] value's `RGFX_GATE_*` starts: bits 16 to 23.
pub const RGFX_GUEST_BUNDLE_GATE_SHIFT: u32 = 16;
/// Where a [`RGFX_REG_GUEST_BUNDLE`] value's `errno` starts: bits 24 to 31.
pub const RGFX_GUEST_BUNDLE_ERRNO_SHIFT: u32 = 24;
/// RgfxGate's install pass, as [`RGFX_REG_GUEST_BUNDLE`] gives it: no RgfxGate published one.
pub const RGFX_GATE_NONE: u32 = 0;
/// RgfxGate's install pass: under way still.
pub const RGFX_GATE_RUNNING: u32 = 1;
/// RgfxGate's install pass: ended without saying how, as an RgfxGate built before
/// `RgfxGateInstallResult` does.
pub const RGFX_GATE_UNTOLD: u32 = 2;
/// RgfxGate's install pass: its own bundle was there already, written and tagged.
pub const RGFX_GATE_PRESENT: u32 = 3;
/// RgfxGate's install pass: it wrote its own bundle and tagged it.
pub const RGFX_GATE_INSTALLED: u32 = 4;
/// RgfxGate's install pass: its own bundle was there, and it tagged it.
pub const RGFX_GATE_TAGGED: u32 = 5;
/// RgfxGate's install pass: a write or the rename of its bundle failed, with the `errno`.
pub const RGFX_GATE_FAILED: u32 = 6;
/// RgfxGate's install pass: the Data volume did not mount while it waited, about 60 s.
pub const RGFX_GATE_NO_DATA_VOLUME: u32 = 7;
/// RgfxGate's install pass: none, in the installer or Recovery.
pub const RGFX_GATE_SKIPPED: u32 = 8;
/// RgfxGate's install pass: it could not start one (no thread, no VFS context, or on arm64 a
/// kernel whose vnode layout it does not know).
pub const RGFX_GATE_REFUSED: u32 = 9;
/// What `MAGIC` reads: "RGFX", little-endian.
pub const RGFX_MAGIC: u32 = 0x5846_4752;
/// What `VERSION` reads: the wire's version, which every change a guest built before it would
/// misread moves on (docs/graphics-kext/design.md, "The wire's version"). The kext and the option
/// ROM leave a device of any other version.
pub const RGFX_VERSION: u32 = 2;
/// misread moves on, a record's size among them: `include/reims_graphics_wire_sizes.h` pins each
/// record's size to it (docs/graphics-kext/design.md, "The wire's version"). The kext and the
/// option ROM leave a device of any other version, and the kext registers its accelerator only for
/// a bundle of its own.
pub const RGFX_VERSION: u32 = 3;
/// `STATUS`: the device is reset, and takes no message.
pub const RGFX_STATUS_RESET: u32 = 0;
/// `STATUS`: the guest's driver has read the rings' headers; the device takes its messages.
@@ -932,6 +1053,9 @@ pub const RGFX_CMD_CURSOR_COLOR: u32 = 10;
/// Command `SCROLL_DEVICES` ([`RgfxScrollDevices`]), where the guest took
/// [`RGFX_FEATURE_POINTER_MOTION`]: not answered.
pub const RGFX_CMD_SCROLL_DEVICES: u32 = 11;
/// Command `HIDDEN_PLACES` ([`RgfxHiddenPlaces`]), where the guest took
/// [`RGFX_FEATURE_POINTER_MOTION`]: not answered.
pub const RGFX_CMD_HIDDEN_PLACES: u32 = 12;
/// Event `COMPLETE` ([`RgfxComplete`]): a command's answer, with its `seqno`.
pub const RGFX_EVT_COMPLETE: u32 = 0x100;
/// Event `DISPLAYS` ([`RgfxDisplays`]): `GET_DISPLAYS`'s answer, with its `seqno`.
@@ -952,6 +1076,11 @@ pub const RGFX_EVT_POINTER_MOTION: u32 = 0x105;
/// ([`RGFX_CMD_SCROLL_DEVICES`]) take it: the host's wheel or trackpad scrolled, and the guest's
/// own devices scroll as far.
pub const RGFX_EVT_SCROLL: u32 = 0x106;
/// Event `POINTER_LOOK` ([`RgfxPointerLook`]), sent only to a guest whose last `HIDDEN_PLACES`
/// since its last start ([`RGFX_CMD_HIDDEN_PLACES`]) said it reports them: the host's pointer
/// moved the guest's tablet while the guest hides its cursor, and the guest reports where its
/// hidden cursor goes.
pub const RGFX_EVT_POINTER_LOOK: u32 = 0x107;
/// `COMPLETE`'s status: the command was done.
pub const RGFX_STATUS_OK: u32 = 0;
@@ -1308,6 +1437,44 @@ pub const RGFX_CMD_HEAP_OVER_POOL: u32 = 0x23c;
/// create among them, which waits for its block's view's address: the answer comes once the
/// buffer lies there. Makes nothing.
pub const RGFX_CMD_PAGES_BUFFER_ADDRESS: u32 = 0x23d;
/// Command `SHARED_TEXTURE_CREATE` ([`RgfxSharedTextureCreate`]), where the host offers
/// [`RGFX_FEATURE_EXT_SHARED_TEXTURE_NAMES`]: a texture of shape `desc` that other processes may
/// open (`newSharedTextureWithDescriptor:`), with the guest-picked `resource_id`. The host makes
/// the texture's storage itself, at an address and a resource index of its own, which no context
/// holds, and the sender's texture `obj_id` over all of it at `resource_id`; each process that
/// opens it later has its own texture over the same storage at its own index
/// ([`RGFX_CMD_SHARED_TEXTURE_IMPORT`]). So the storage outlives the context that made it while
/// another process's texture or a name holds it, and no context's addresses or indices are held
/// past its close. Its storage mode is Private: a create of any other is refused. Not answered;
/// a create the host refuses stands for a refused object, as a `TEXTURE_CREATE`'s does.
/// `OBJECT_DESTROY` drops the sender's texture; the storage goes with its last texture and its
/// last name.
pub const RGFX_CMD_SHARED_TEXTURE_CREATE: u32 = 0x23e;
/// Command `SHARED_TEXTURE_NAME` ([`RgfxSharedTextureName`]), which the accelerator kext posts for
/// a process's handle of its shared texture `obj_id` (`newSharedTextureHandle`), where the host
/// offers [`RGFX_FEATURE_EXT_SHARED_TEXTURE_NAMES`]: the texture's storage is named `name`
/// device-wide, so another process may open it ([`RGFX_CMD_SHARED_TEXTURE_IMPORT`]), until the kext
/// lets go of the name ([`RGFX_CMD_SHARED_TEXTURE_UNNAME`]). A name holds the storage as a texture
/// over it does. Answered by [`RGFX_EVT_COMPLETE`]: [`RGFX_STATUS_OK`], or
/// [`RGFX_STATUS_NOT_FOUND`] where the sender holds no shared texture of that id (one whose
/// create the host refused among them), and [`RGFX_STATUS_INVALID_ARGUMENT`] for a name of 0. The
/// kext builds the message: `name` is the kext's, never the process's.
pub const RGFX_CMD_SHARED_TEXTURE_NAME: u32 = 0x23f;
/// Command `SHARED_TEXTURE_IMPORT` ([`RgfxSharedTextureImport`]), which the accelerator kext posts
/// for a process that opens a handle another process's `SHARED_TEXTURE_NAME` named
/// (`newSharedTextureWithHandle:`), where the host offers
/// [`RGFX_FEATURE_EXT_SHARED_TEXTURE_NAMES`]: the process's new texture `obj_id` lies over all of
/// the storage `name` names, in the shape it was made in, at the guest-picked `resource_id`.
/// Answered by [`RGFX_EVT_SHARED_TEXTURE`] with the shape, which the process's texture answers,
/// or [`RGFX_STATUS_NOT_FOUND`] where the name was let go of or never given, and
/// [`RGFX_STATUS_INVALID_ARGUMENT`] for another context's id or a resource index the sender does
/// not hold; nothing is made then. `OBJECT_DESTROY` drops it, as any texture.
pub const RGFX_CMD_SHARED_TEXTURE_IMPORT: u32 = 0x240;
/// Command `SHARED_TEXTURE_UNNAME` ([`RgfxSharedTextureUnname`]), which the accelerator kext posts
/// once nothing but the kext holds the handle a `SHARED_TEXTURE_NAME` named, where the host offers
/// [`RGFX_FEATURE_EXT_SHARED_TEXTURE_NAMES`]: no process can open the name from then on, and the
/// storage goes once no texture lies over it. Context 0's, which no process is. Not answered.
pub const RGFX_CMD_SHARED_TEXTURE_UNNAME: u32 = 0x241;
/// `CONTEXT_CLOSE` ([`RgfxContextClose`]), on ring 0 from the accelerator kext: the process that
/// held context `context` closed the device or died. The host ends the context's command queues
@@ -1631,6 +1798,16 @@ pub const RGFX_EVT_POOL_BLOCK: u32 = 0x410;
/// [`RGFX_CMD_PRIVATE_TAKE`]'s `seqno`: its answer. `status` [`RGFX_STATUS_OK`] with the block's
/// `gpu_address` and `length`; otherwise each 0.
pub const RGFX_EVT_PRIVATE_BLOCK: u32 = 0x411;
/// Event `SHARED_TEXTURE` ([`RgfxSharedTexture`], on the control completion ring), with a
/// [`RGFX_CMD_SHARED_TEXTURE_IMPORT`]'s `seqno`: its answer. `status` [`RGFX_STATUS_OK`] with the
/// shape the storage was made in; otherwise the shape is zeros.
pub const RGFX_EVT_SHARED_TEXTURE: u32 = 0x412;
/// Event `SURFACE_HOLD_LOWERED` ([`RgfxSurfaceHoldLowered`], on the control completion ring,
/// `seqno` 0), where the guest took [`RGFX_FEATURE_EXT_SURFACE_HOLD`]: the host lowered the hold
/// word of the cached surface's block at `block_offset` after a read-write CPU lock set
/// [`RGFX_SURFACE_HOLD_WAITED`] beside it, so the lock looks at the word again. Posted with no
/// wait: one the ring has no room for is dropped, and the lock looks again within 1 ms.
pub const RGFX_EVT_SURFACE_HOLD_LOWERED: u32 = 0x413;
/// A command buffer's status in [`RgfxCbComplete`]: finished with no error.
pub const RGFX_CB_OK: u32 = 0;
@@ -2092,6 +2269,19 @@ pub struct RgfxDisplayChanged {
pub reserved_14: u32,
}
/// `SURFACE_HOLD_LOWERED`: the host lowered a cached surface's hold word that a lock waited on
/// ([`RGFX_EVT_SURFACE_HOLD_LOWERED`]).
#[repr(C)]
#[derive(
Clone, Copy, Debug, Default, PartialEq, Eq, FromBytes, IntoBytes, Immutable, KnownLayout,
)]
pub struct RgfxSurfaceHoldLowered {
/// [`RGFX_EVT_SURFACE_HOLD_LOWERED`], `seqno` 0.
pub header: RgfxMsgHeader,
/// The region offset of the surface's block.
pub block_offset: u64,
}
/// `VBLANK`: the display's host screen refreshed.
#[repr(C)]
#[derive(
@@ -2182,6 +2372,47 @@ pub struct RgfxScrollDevices {
pub reserved_14: u32,
}
/// `HIDDEN_PLACES`: whether the guest reports where its hidden cursor goes (`reports` 1, else 0),
/// which its driver sends once its mouse ([`RGFX_FEATURE_POINTER_MOTION`]) is up after each start.
/// A guest that reports them is sent [`RGFX_EVT_POINTER_LOOK`] when the host's pointer moves its
/// tablet while it hides its cursor, and answers with a `MOVE_CURSOR` of the cursor still hidden
/// (`visible` 0) at each new place it reads for a while after; the device then counts a hide as a
/// game's only once its hidden cursor has followed the tablet (docs/graphics-kext/design.md, "A
/// pointer for games", "The hidden cursor's place"). A guest that sends none, or 0, is never sent
/// `POINTER_LOOK`, and each hide of its counts as a game's as before, until the next reset. The
/// x86-64 kext sends it; the arm64e kext, whose cursor is a layer of its swaps, sends none.
#[repr(C)]
#[derive(
Clone, Copy, Debug, Default, PartialEq, Eq, FromBytes, IntoBytes, Immutable, KnownLayout,
)]
pub struct RgfxHiddenPlaces {
/// [`RGFX_CMD_HIDDEN_PLACES`].
pub header: RgfxMsgHeader,
/// 1 where the guest reports where its hidden cursor goes, else 0.
pub reports: u32,
/// 0.
pub reserved_14: u32,
}
/// `POINTER_LOOK`: the host's pointer, over display `display`'s window, moved the guest's tablet
/// while the guest hides its cursor on every display: the guest looks where its hidden cursor
/// goes for a while, and reports each new place in a `MOVE_CURSOR` of the cursor still hidden
/// (`visible` 0). Sent only to a guest whose [`RGFX_CMD_HIDDEN_PLACES`] said it reports them,
/// while the hide has not shown its hidden cursor following the tablet, one at most every 50 ms;
/// one that finds the ring held or full is not sent, and the next move sends it.
#[repr(C)]
#[derive(
Clone, Copy, Debug, Default, PartialEq, Eq, FromBytes, IntoBytes, Immutable, KnownLayout,
)]
pub struct RgfxPointerLook {
/// [`RGFX_EVT_POINTER_LOOK`], `seqno` 0.
pub header: RgfxMsgHeader,
/// The display whose window the host's pointer is over.
pub display: u32,
/// 0.
pub reserved_14: u32,
}
/// [`RgfxScrollDevices`]'s `devices`: the guest's mouse takes wheel notches, up and sideways
/// ([`RgfxScroll`]'s `notches_up` and `notches_right`).
pub const RGFX_SCROLL_DEVICE_WHEEL: u32 = 1 << 0;
@@ -2279,6 +2510,9 @@ const _: () = {
assert!(offset_of!(RgfxPointerMotion, wheel) == 24);
assert!(offset_of!(RgfxPointerMotion, buttons) == 28);
assert!(size_of::<RgfxScrollDevices>() == 24);
assert!(size_of::<RgfxHiddenPlaces>() == 24);
assert!(size_of::<RgfxPointerLook>() == 24);
assert!(offset_of!(RgfxPointerLook, display) == 16);
assert!(size_of::<RgfxScroll>() == 32);
assert!(offset_of!(RgfxScroll, fine_up) == 24);
assert!(size_of::<RgfxDisplayBounds>() == 40);
@@ -2471,6 +2705,87 @@ pub struct RgfxSharedEventValue {
pub value: u64,
}
/// `SHARED_TEXTURE_CREATE`: the sender's texture `obj_id`, of shape `desc`, over storage the host
/// makes for it, which other processes may open.
#[repr(C)]
#[derive(
Clone, Copy, Debug, Default, PartialEq, Eq, FromBytes, IntoBytes, Immutable, KnownLayout,
)]
pub struct RgfxSharedTextureCreate {
/// [`RGFX_CMD_SHARED_TEXTURE_CREATE`].
pub header: RgfxMsgHeader,
/// The new texture's guest-picked id.
pub obj_id: u64,
/// The texture's guest-picked resource id.
pub resource_id: u64,
/// The texture's shape: Private storage.
pub desc: RgfxTextureDescriptor,
}
/// `SHARED_TEXTURE_NAME`: the storage of the sender's shared texture `obj_id` named `name`
/// device-wide. The kext builds the message: `name` is the kext's, never the process's.
#[repr(C)]
#[derive(
Clone, Copy, Debug, Default, PartialEq, Eq, FromBytes, IntoBytes, Immutable, KnownLayout,
)]
pub struct RgfxSharedTextureName {
/// [`RGFX_CMD_SHARED_TEXTURE_NAME`].
pub header: RgfxMsgHeader,
/// The sender's shared texture, or a texture it opened from another's name.
pub obj_id: u64,
/// Its name, unique to the device from the kext's start: never 0.
pub name: u64,
}
/// `SHARED_TEXTURE_IMPORT`: the sender's new texture `obj_id` over the storage named `name`, at
/// `resource_id`. The kext builds the message from the handle the process holds.
#[repr(C)]
#[derive(
Clone, Copy, Debug, Default, PartialEq, Eq, FromBytes, IntoBytes, Immutable, KnownLayout,
)]
pub struct RgfxSharedTextureImport {
/// [`RGFX_CMD_SHARED_TEXTURE_IMPORT`].
pub header: RgfxMsgHeader,
/// The sender's new texture's guest-picked id.
pub obj_id: u64,
/// The name the storage was given ([`RgfxSharedTextureName::name`]).
pub name: u64,
/// The new texture's guest-picked resource id.
pub resource_id: u64,
}
/// `SHARED_TEXTURE_UNNAME`: the name `name` is no longer the kext's to give out.
#[repr(C)]
#[derive(
Clone, Copy, Debug, Default, PartialEq, Eq, FromBytes, IntoBytes, Immutable, KnownLayout,
)]
pub struct RgfxSharedTextureUnname {
/// [`RGFX_CMD_SHARED_TEXTURE_UNNAME`].
pub header: RgfxMsgHeader,
/// 0: the message is context 0's, which no process is, so it waits for no process's
/// messages.
pub reserved_10: u64,
/// The name ([`RgfxSharedTextureName::name`]).
pub name: u64,
}
/// `SHARED_TEXTURE`: a `SHARED_TEXTURE_IMPORT`'s answer, with its `seqno`: the shape the storage
/// was made in, which the new texture answers.
#[repr(C)]
#[derive(
Clone, Copy, Debug, Default, PartialEq, Eq, FromBytes, IntoBytes, Immutable, KnownLayout,
)]
pub struct RgfxSharedTexture {
/// [`RGFX_EVT_SHARED_TEXTURE`], with the import's `seqno`.
pub header: RgfxMsgHeader,
/// An `RGFX_STATUS_*`: [`RGFX_STATUS_OK`] where the texture is made.
pub status: u32,
/// Pads to a multiple of 8; 0.
pub reserved_14: u32,
/// The storage's shape; zeros where the texture was not made.
pub desc: RgfxTextureDescriptor,
}
/// `QUEUE_CREATE`: a command queue and its submission+completion ring pair, each
/// a [`RgfxRingHeader`] followed by a byte ring of the given data size (a power
/// of two) at the given region offset. The completion ring raises `vector`.
@@ -5822,6 +6137,11 @@ const _: () = {
assert!(size_of::<RgfxObjectCreate>() == 24);
assert!(size_of::<RgfxSharedEventCreate>() == 32);
assert!(size_of::<RgfxSharedEventSetValue>() == 32);
assert!(size_of::<RgfxSharedTextureCreate>() == 80);
assert!(size_of::<RgfxSharedTextureName>() == 32);
assert!(size_of::<RgfxSharedTextureImport>() == 40);
assert!(size_of::<RgfxSharedTextureUnname>() == 32);
assert!(size_of::<RgfxSharedTexture>() == 72);
assert!(size_of::<RgfxQueueCreate>() == 56);
assert!(RGFX_QUEUE_CREATE_FLAGS_OFFSET as usize == size_of::<RgfxQueueCreate>());
assert!(size_of::<RgfxQueueCreateFlags>() == 8);
@@ -55,6 +55,9 @@ CHECK(RGFX_EVT_POINTER_MOTION == 0x105);
CHECK(RGFX_FEATURE_POINTER_MOTION == (1ULL << 51));
CHECK(RGFX_CMD_SCROLL_DEVICES == 11 && sizeof(RgfxScrollDevices) == 24);
CHECK(RGFX_EVT_SCROLL == 0x106 && sizeof(RgfxScroll) == 32);
CHECK(RGFX_CMD_HIDDEN_PLACES == 12 && sizeof(RgfxHiddenPlaces) == 24);
CHECK(RGFX_EVT_POINTER_LOOK == 0x107 && sizeof(RgfxPointerLook) == 24);
CHECK(offsetof(RgfxPointerLook, display) == 16);
CHECK(offsetof(RgfxScroll, fine_up) == 24);
CHECK(RGFX_FEATURE_VT_MESSAGES == (1ULL << 52));
CHECK(RGFX_CMD_VT_MESSAGE == 0x2fa);
@@ -118,6 +121,20 @@ CHECK(RGFX_CMD_PAGES_BUFFER_ADDRESS == 0x23d && sizeof(RgfxPagesBufferAddress) =
CHECK(offsetof(RgfxPagesBufferAddress, obj_id) == 16);
CHECK(RGFX_FEATURE_SURFACE_CACHE_EVERY == (1ULL << 62));
CHECK(RGFX_FEATURE_MANAGED_AT_COPY == (1ULL << 63));
CHECK(RGFX_REG_FEATURES_EXT == 0x058 && RGFX_FEATURE_EXT_SHARED_TEXTURE_NAMES == 1);
CHECK(RGFX_FEATURE_EXT_SURFACE_HOLD == (1 << 2) && RGFX_SURFACE_HOLD_ROOM == 0x1000);
CHECK(RGFX_CMD_SHARED_TEXTURE_CREATE == 0x23e && sizeof(RgfxSharedTextureCreate) == 80);
CHECK(offsetof(RgfxSharedTextureCreate, resource_id) == 24);
CHECK(offsetof(RgfxSharedTextureCreate, desc) == 32);
CHECK(RGFX_CMD_SHARED_TEXTURE_NAME == 0x23f && sizeof(RgfxSharedTextureName) == 32);
CHECK(offsetof(RgfxSharedTextureName, obj_id) == 16 && offsetof(RgfxSharedTextureName, name) == 24);
CHECK(RGFX_CMD_SHARED_TEXTURE_IMPORT == 0x240 && sizeof(RgfxSharedTextureImport) == 40);
CHECK(offsetof(RgfxSharedTextureImport, name) == 24);
CHECK(offsetof(RgfxSharedTextureImport, resource_id) == 32);
CHECK(RGFX_CMD_SHARED_TEXTURE_UNNAME == 0x241 && sizeof(RgfxSharedTextureUnname) == 32);
CHECK(offsetof(RgfxSharedTextureUnname, name) == 24);
CHECK(RGFX_EVT_SHARED_TEXTURE == 0x412 && sizeof(RgfxSharedTexture) == 72);
CHECK(offsetof(RgfxSharedTexture, status) == 16 && offsetof(RgfxSharedTexture, desc) == 24);
CHECK(offsetof(RgfxCursorColor, on) == 20 && offsetof(RgfxCursorColor, source_curves) == 24);
CHECK(offsetof(RgfxCursorColor, to_xyz) == 120 && offsetof(RgfxCursorColor, from_xyz) == 156);
CHECK(offsetof(RgfxCursorColor, blend_curves) == 192);
@@ -0,0 +1,179 @@
//! Each wire record's size, as the committed header lays it out, against the table pinned to the
//! wire's version, `include/reims_graphics_wire_sizes.h` (docs/graphics-kext/design.md, "The
//! wire's version"): a record whose size changed without `RGFX_VERSION` moving is one a guest of
//! that version misreads. The header is cbindgen's of `wire`'s and `ops`' records, which `cargo
//! xtask header --check` holds it to, so its sizes are the records' own. The guest checks the same
//! table as it compiles the header (`guest/kext/tests/wire_sizes_test.cpp`).
// A failure is the assertion (architecture 17.4).
#![allow(clippy::unwrap_used)]
use reims_vgpu_graphics::wire::RGFX_VERSION;
use std::collections::BTreeSet;
use std::path::PathBuf;
use std::process::Command;
/// The crate's `include` directory, which holds the header and the table.
fn include_dir() -> PathBuf {
PathBuf::from(std::env::var_os("CARGO_MANIFEST_DIR").unwrap()).join("include")
}
/// The table's text.
fn table() -> String {
std::fs::read_to_string(include_dir().join("reims_graphics_wire_sizes.h")).unwrap()
}
/// The version the table pins its sizes to: its `RGFX_WIRE_SIZES_VERSION`.
fn table_version(table: &str) -> u32 {
table
.lines()
.find_map(|l| l.strip_prefix("#define RGFX_WIRE_SIZES_VERSION "))
.unwrap()
.trim()
.parse()
.unwrap()
}
/// The table's rows, each a record's name and its size in bytes, in the table's order.
fn rows(table: &str) -> Vec<(String, u64)> {
table
.lines()
.filter_map(|l| l.strip_prefix("RGFX_WIRE_SIZE("))
.map(|l| {
let (name, size) = l.strip_suffix(')').unwrap().split_once(", ").unwrap();
(name.to_owned(), size.parse().unwrap())
})
.collect()
}
/// The table is pinned to the version the host speaks: one that moved without its table, or a
/// table moved without the version, fails here
#[test]
fn the_size_table_is_pinned_to_the_wire_s_version() {
assert_eq!(
table_version(&table()),
RGFX_VERSION,
"include/reims_graphics_wire_sizes.h pins its sizes to another version than \
RGFX_VERSION: pin the records' sizes at the version the wire speaks"
);
}
/// The table's register rows, each a register's name and its offset in BAR 0, in the table's
/// order.
fn registers(table: &str) -> Vec<(String, u32)> {
table
.lines()
.filter_map(|l| l.strip_prefix("RGFX_WIRE_REGISTER("))
.map(|l| {
let (name, at) = l.strip_suffix(')').unwrap().split_once(", ").unwrap();
let at = u32::from_str_radix(at.strip_prefix("0x").unwrap(), 16).unwrap();
(name.to_owned(), at)
})
.collect()
}
/// The table has one row for each register of BAR 0 the header defines and names none other, no
/// two at one offset, so a new register takes its offset at the version it lands in, and one
/// that moved fails `each_wire_record_keeps_its_size_at_the_wire_s_version`
#[test]
fn the_layout_table_names_each_register_of_the_header_once() {
let header = std::fs::read_to_string(include_dir().join("reims_graphics_wire.h")).unwrap();
let defined: BTreeSet<&str> = header
.lines()
.filter_map(|l| l.strip_prefix("#define RGFX_REG_"))
.filter_map(|l| l.split_whitespace().next())
.collect();
assert!(
defined.len() >= 20,
"only {} registers found",
defined.len()
);
let table = table();
let rows = registers(&table);
let named: BTreeSet<&str> = rows
.iter()
.map(|(n, _)| n.strip_prefix("RGFX_REG_").unwrap())
.collect();
let offsets: BTreeSet<u32> = rows.iter().map(|(_, at)| *at).collect();
assert_eq!(named.len(), rows.len(), "a register has two rows");
assert_eq!(offsets.len(), rows.len(), "two registers share an offset");
let missing: Vec<_> = defined.difference(&named).collect();
let unknown: Vec<_> = named.difference(&defined).collect();
assert!(
missing.is_empty() && unknown.is_empty(),
"registers without a row: {missing:?}; rows of no register: {unknown:?}"
);
}
/// The table has one row for each record of the header and names none other, so a new record
/// takes its size at the version it lands in
#[test]
fn the_size_table_names_each_record_of_the_header_once() {
let header = std::fs::read_to_string(include_dir().join("reims_graphics_wire.h")).unwrap();
let records: BTreeSet<&str> = header
.lines()
.filter_map(|l| l.strip_prefix("} ")?.strip_suffix(';'))
.filter(|n| n.starts_with("Rgfx"))
.collect();
assert!(records.len() > 300, "only {} records found", records.len());
let table = table();
let rows = rows(&table);
let named: BTreeSet<&str> = rows.iter().map(|(n, _)| n.as_str()).collect();
assert_eq!(named.len(), rows.len(), "a record has two rows");
let missing: Vec<_> = records.difference(&named).collect();
let unknown: Vec<_> = named.difference(&records).collect();
assert!(
missing.is_empty() && unknown.is_empty(),
"records without a row: {missing:?}; rows of no record: {unknown:?}"
);
}
/// Each record of the header has the size the table pins at the wire's version, and each register
/// its offset, in C11 as the option ROM compiles it and in C++17 as the kext does: a size or an
/// offset that moved fails here, naming each, and moves `RGFX_VERSION` on
#[test]
fn each_wire_record_keeps_its_size_at_the_wire_s_version() {
for (language, std) in [("c", "-std=c11"), ("c++", "-std=c++17")] {
let checks = "#include \"reims_graphics_wire.h\"\n\
#ifdef __cplusplus\n#define CHECK(e, m) static_assert(e, m)\n\
#else\n#define CHECK(e, m) _Static_assert(e, m)\n#endif\n\
#define RGFX_WIRE_SIZE(T, n) CHECK(sizeof(T) == n, #T \" changed size \
without RGFX_VERSION moving\");\n\
#define RGFX_WIRE_REGISTER(R, at) CHECK(R == at, #R \" moved without \
RGFX_VERSION moving\");\n\
#include \"reims_graphics_wire_sizes.h\"\n\
CHECK(RGFX_WIRE_SIZES_VERSION == RGFX_VERSION, \"the table's version\");\n\
int main(void) { return 0; }\n";
let tmp = std::env::temp_dir().join(format!(
"rgfx-wire-sizes-{}-{language}.c",
std::process::id()
));
std::fs::write(&tmp, checks).unwrap();
let out = Command::new("cc")
.args(["-x", language, std, "-Wall", "-Wextra", "-Werror"])
.arg("-fsyntax-only")
.arg("-I")
.arg(include_dir())
.arg(&tmp)
.output()
.unwrap();
let _ = std::fs::remove_file(&tmp);
let stderr = String::from_utf8_lossy(&out.stderr);
let moved: Vec<&str> = stderr
.lines()
.filter(|l| {
l.contains("changed size without RGFX_VERSION moving")
|| l.contains("moved without RGFX_VERSION moving")
|| l.contains("evaluates to")
})
.collect();
assert!(
out.status.success(),
"{language}: records whose size, or registers whose offset, differs from \
include/reims_graphics_wire_sizes.h at version {RGFX_VERSION}: move RGFX_VERSION \
on by one and pin the new sizes and offsets at it (docs/graphics-kext/design.md, \
\"The wire's version\"):\n{}\n{stderr}",
moved.join("\n")
);
}
}
+6
View File
@@ -10,6 +10,12 @@ license.workspace = true
[lints]
workspace = true
[features]
# The test-only delays at named points of the arms and the sessions (`video_delay`), and the
# paravirtual protocol's key names (`paravirt::names`), for the host-only harness of reims-vgpu's
# tests, whose `testkit` feature turns this on. Without it the delays are empty inline functions.
testkit = []
[dependencies]
thiserror = "2"
log = { version = "0.4", features = ["kv"] }
@@ -5,7 +5,10 @@
//! - [`mp4`] reads a track's configuration record and samples out of an
//! MP4, and [`mp4_write`] writes one of what an encoder gave.
//! - [`md5`] hashes frames, as ffmpeg's `framemd5` does.
//! - [`marks`] reads what the conformance suite's scripts say of their streams beside them, the
//! streams the decoder refuses, and holds a test's decode of each to it.
pub mod marks;
pub mod md5;
pub mod mp4;
pub mod mp4_write;
@@ -0,0 +1,124 @@
//! What the conformance suite's scripts write beside their streams, for the tests that decode
//! those streams elsewhere (`tools/lib.sh`'s `refusals`, and `tools/hevc-check.sh`):
//! `refused.txt`, the streams the decoder refuses on every host, a line each, `NAME|BEFORE|SAYS`
//! (the Annex B stream's file name, the pictures it decodes before its refusal, and what the
//! refusal says), and `range-extensions.txt`, the range extensions' streams, a file name a line
//! ([`Marks`]).
//!
//! A test holds each stream's decode to them ([`Marks::judge`]): a stream they name as refused
//! is refused as they say, after the pictures they say; a refusal they do not name fails the
//! test, as does a named stream that decodes past its refusal. So a stream that decoded and
//! starts being refused turns the test red, and a test skips no refusal for being one.
use std::collections::{HashMap, HashSet};
use std::path::Path;
/// A refusal `refused.txt` names.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Refusal {
/// The pictures the stream decodes before it.
pub before: usize,
/// What it says: text the decoder's error holds.
pub says: String,
}
/// The lists of the directories read, by stream file name.
#[derive(Clone, Debug, Default)]
pub struct Marks {
/// `refused.txt`'s streams.
pub refused: HashMap<String, Refusal>,
/// `range-extensions.txt`'s streams.
pub range_extensions: HashSet<String>,
}
/// How a stream's decode ended.
#[derive(Clone, Copy, Debug)]
pub enum Ended<'a> {
/// At the stream's end, every access unit decoded.
Whole,
/// Where the caller stopped it, before its end.
Stopped,
/// At a refusal, which says this.
Refused(&'a str),
}
impl Marks {
/// The lists in each of `dirs`; a directory without them names none. `Err` where one does
/// not read, or holds a line that does not parse.
pub fn read<P: AsRef<Path>>(dirs: impl IntoIterator<Item = P>) -> Result<Self, String> {
let mut marks = Self::default();
for dir in dirs {
let read = |name: &str| {
let path = dir.as_ref().join(name);
match std::fs::read_to_string(&path) {
Ok(text) => Ok(text),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(String::new()),
Err(error) => Err(format!("{}: {error}", path.display())),
}
};
for line in read("refused.txt")?.lines().filter(|line| !line.is_empty()) {
let mut fields = line.splitn(3, '|');
let (Some(stream), Some(before), Some(says)) =
(fields.next(), fields.next(), fields.next())
else {
return Err(format!("refused.txt: a line of three fields, not {line:?}"));
};
let before = (before.parse())
.map_err(|_| format!("refused.txt: a count of pictures, not {before:?}"))?;
let says = says.to_owned();
marks
.refused
.insert(stream.to_owned(), Refusal { before, says });
}
let names = read("range-extensions.txt")?;
let names = names.lines().filter(|line| !line.is_empty());
marks.range_extensions.extend(names.map(str::to_owned));
}
Ok(marks)
}
/// Whether `range-extensions.txt` names the stream `name`.
pub fn is_range_extensions(&self, name: &str) -> bool {
self.range_extensions.contains(name)
}
/// The decode of the stream `name`, which gave `decoded` pictures and ended as `ended` says,
/// held to `refused.txt` (module doc): `Ok(Some(line))`, naming the stream and its refusal,
/// where it was refused as the list says; `Ok(None)` where the list names no refusal it
/// reached; `Err` saying how it differs otherwise.
pub fn judge(
&self,
name: &str,
decoded: usize,
ended: Ended<'_>,
) -> Result<Option<String>, String> {
let listed = self.refused.get(name);
let said = |r: &Refusal| format!("after {} pictures: {}", r.before, r.says);
match (ended, listed) {
(Ended::Refused(error), Some(r)) if decoded == r.before && error.contains(&r.says) => {
Ok(Some(format!("{name}: after {decoded} pictures: {error}")))
}
(Ended::Refused(error), Some(r)) => Err(format!(
"{name}: refused after {decoded} pictures: {error}; the suite's list says {}",
said(r)
)),
(Ended::Refused(error), None) => Err(format!(
"{name}: refused after {decoded} pictures, which the suite's list does not say: \
{error}"
)),
(Ended::Whole, Some(r)) => Err(format!(
"{name}: decoded whole, {decoded} pictures, where the suite's list says it is \
refused {}",
said(r)
)),
(Ended::Stopped, Some(r)) if decoded > r.before => Err(format!(
"{name}: {decoded} pictures decoded, past its refusal: the suite's list says {}",
said(r)
)),
_ => Ok(None),
}
}
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,155 @@
use std::path::PathBuf;
use std::sync::atomic::{AtomicUsize, Ordering};
use super::*;
/// A directory of the test's own, empty: one a call, as the tests may run in one process.
fn scratch() -> PathBuf {
static MADE: AtomicUsize = AtomicUsize::new(0);
let n = MADE.fetch_add(1, Ordering::Relaxed);
let dir = std::env::temp_dir().join(format!("rvg-marks-{}-{n}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
dir
}
/// The lists h264-check.sh and hevc-check.sh wrote (potluck job m3-max-85184), two directories'
/// worth, read from a directory of the test's own; and one directory with no lists.
fn suites() -> Marks {
let root = scratch();
let (h264, hevc, none) = (root.join("h264"), root.join("hevc"), root.join("none"));
for dir in [&h264, &hevc, &none] {
std::fs::create_dir_all(dir).unwrap();
}
std::fs::write(
h264.join("refused.txt"),
"high-1080p-interlaced.264|0|interlaced: \nhigh-1080p-fakeint.264|0|interlaced: \n",
)
.unwrap();
std::fs::write(
hevc.join("refused.txt"),
"kvz-720p-tiles-col64.265|0|ColumnWidthInLumaSamples is out of range\r\n\
kvz-720p-ref15.265|9|VA-API takes 8\r\n",
)
.unwrap();
std::fs::write(
hevc.join("range-extensions.txt"),
"main444-360p.265\nmain12-360p.265\n",
)
.unwrap();
let marks = Marks::read([&h264, &hevc, &none]).unwrap();
std::fs::remove_dir_all(&root).unwrap();
marks
}
#[test]
fn the_lists_read_by_stream_name() {
let marks = suites();
assert_eq!(marks.refused.len(), 4);
let ref15 = Refusal {
before: 9,
says: "VA-API takes 8".to_owned(),
};
assert_eq!(marks.refused.get("kvz-720p-ref15.265"), Some(&ref15));
assert_eq!(
marks
.refused
.get("high-1080p-fakeint.264")
.map(|r| r.says.as_str()),
Some("interlaced: ")
);
assert!(marks.is_range_extensions("main12-360p.265"));
assert!(!marks.is_range_extensions("main-720p.265"));
}
#[test]
fn a_line_that_does_not_parse_is_an_error() {
let dir = scratch();
for bad in ["a.264|0\n", "a.264|none|interlaced\n"] {
std::fs::write(dir.join("refused.txt"), bad).unwrap();
assert!(Marks::read([&dir]).is_err(), "{bad:?}");
}
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn a_listed_stream_refused_as_its_line_says_is_named() {
let marks = suites();
let interlaced = "interlaced: the SPS's frame_mbs_only_flag is 0";
assert_eq!(
marks.judge("high-1080p-interlaced.264", 0, Ended::Refused(interlaced)),
Ok(Some(format!(
"high-1080p-interlaced.264: after 0 pictures: {interlaced}"
)))
);
let ref15 = "the driver cannot: 9 pictures in the current reference sets: VA-API takes 8";
assert!(matches!(
marks.judge("kvz-720p-ref15.265", 9, Ended::Refused(ref15)),
Ok(Some(_))
));
}
#[test]
fn a_listed_stream_refused_otherwise_fails() {
let marks = suites();
let ref15 = "the driver cannot: 9 pictures in the current reference sets: VA-API takes 8";
// Earlier than its line says, or for another reason.
assert!(
marks
.judge("kvz-720p-ref15.265", 3, Ended::Refused(ref15))
.is_err()
);
let other = "the driver cannot: HEVCMain: no YUV420 render targets";
assert!(
marks
.judge("kvz-720p-ref15.265", 9, Ended::Refused(other))
.is_err()
);
}
/// A stream that decoded, refused now: the planner's rule (12-03), that no refusal is skipped for
/// being one.
#[test]
fn a_refusal_the_lists_do_not_name_fails() {
let marks = suites();
let refused = "the driver cannot: HEVCMain: the driver has no decoder";
let judged = marks.judge("main-720p.265", 0, Ended::Refused(refused));
assert!(judged.unwrap_err().contains("does not say"));
let empty = Marks::default();
let interlaced = "interlaced: the SPS's frame_mbs_only_flag is 0";
assert!(
empty
.judge("high-1080p-interlaced.264", 0, Ended::Refused(interlaced))
.is_err()
);
}
#[test]
fn a_listed_stream_that_decodes_past_its_refusal_fails() {
let marks = suites();
assert!(
marks
.judge("high-1080p-fakeint.264", 30, Ended::Whole)
.is_err()
);
assert!(
marks
.judge("kvz-720p-ref15.265", 10, Ended::Stopped)
.is_err()
);
// Stopped by its caller before it.
assert_eq!(
marks.judge("kvz-720p-ref15.265", 4, Ended::Stopped),
Ok(None)
);
assert_eq!(
marks.judge("kvz-720p-ref15.265", 9, Ended::Stopped),
Ok(None)
);
}
#[test]
fn an_unlisted_stream_that_decodes_is_nothing_to_name() {
let marks = suites();
assert_eq!(marks.judge("main-720p.265", 120, Ended::Whole), Ok(None));
assert_eq!(marks.judge("main-720p.265", 4, Ended::Stopped), Ok(None));
}
+34 -8
View File
@@ -52,6 +52,10 @@ pub enum Profile {
HevcMain,
/// HEVC Main 10, `general_profile_idc` 2: 10-bit 4:2:0.
HevcMain10,
/// HEVC Main 4:2:2 10, `general_profile_idc` 4 (the format range
/// extensions) with Main 4:2:2 10's constraint flags (A.3.5, Table
/// A.2): 10-bit 4:2:2.
HevcMain42210,
}
impl Profile {
@@ -59,7 +63,7 @@ impl Profile {
pub const fn codec(self) -> Codec {
match self {
Self::H264ConstrainedBaseline | Self::H264Main | Self::H264High => Codec::H264,
Self::HevcMain | Self::HevcMain10 => Codec::Hevc,
Self::HevcMain | Self::HevcMain10 | Self::HevcMain42210 => Codec::Hevc,
}
}
@@ -72,21 +76,31 @@ impl Profile {
Self::H264High => 100,
Self::HevcMain => 1,
Self::HevcMain10 => 2,
Self::HevcMain42210 => 4,
}
}
/// Bits a sample.
pub const fn bit_depth(self) -> u8 {
match self {
Self::HevcMain10 => 10,
Self::HevcMain10 | Self::HevcMain42210 => 10,
_ => 8,
}
}
/// `chroma_format_idc`: 1 for 4:2:0, 2 for 4:2:2.
pub const fn chroma_format_idc(self) -> u8 {
match self {
Self::HevcMain42210 => 2,
_ => 1,
}
}
/// The input format the profile takes.
pub const fn input_format(self) -> InputFormat {
match self {
Self::HevcMain10 => InputFormat::P010,
Self::HevcMain42210 => InputFormat::P210,
_ => InputFormat::Nv12,
}
}
@@ -97,15 +111,18 @@ impl Profile {
}
}
/// How the frames handed to an encoder are laid out: 4:2:0, a luma plane
/// and an interleaved Cb/Cr plane half as tall.
/// How the frames handed to an encoder are laid out: a luma plane and an
/// interleaved Cb/Cr plane, half as tall in 4:2:0 and as tall in 4:2:2.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum InputFormat {
/// 8-bit samples, one byte each (CoreVideo's `420v` and `420f`).
/// 4:2:0, 8-bit samples, one byte each (CoreVideo's `420v` and `420f`).
Nv12,
/// 10-bit samples in the high bits of little-endian 16-bit words
/// (CoreVideo's `x420` and `xf20`).
/// 4:2:0, 10-bit samples in the high bits of little-endian 16-bit
/// words (CoreVideo's `x420` and `xf20`).
P010,
/// 4:2:2, 10-bit samples in the high bits of little-endian 16-bit
/// words (CoreVideo's `x422` and `xf22`).
P210,
}
impl InputFormat {
@@ -113,7 +130,16 @@ impl InputFormat {
pub const fn bytes_per_sample(self) -> usize {
match self {
Self::Nv12 => 1,
Self::P010 => 2,
Self::P010 | Self::P210 => 2,
}
}
/// The chroma plane's rows of a picture of `rows` luma rows: half of
/// them, rounded down, in 4:2:0, and all of them in 4:2:2.
pub const fn chroma_rows(self, rows: u32) -> u32 {
match self {
Self::Nv12 | Self::P010 => rows / 2,
Self::P210 => rows,
}
}
}
@@ -68,6 +68,12 @@ pub struct DriverLimits {
pub max_width: u32,
/// The tallest surface it encodes.
pub max_height: u32,
/// What the coded width is a multiple of beside the codec's own
/// block, a power of two: 1 where the driver states nothing.
pub width_alignment: u32,
/// What the coded height is a multiple of beside the codec's own
/// block, a power of two: 1 where the driver states nothing.
pub height_alignment: u32,
/// HEVC's tools, resolved from what the driver allows and requires.
pub hevc_tools: Option<hevc::Tools>,
}
@@ -357,7 +363,12 @@ fn check_settings(settings: &EncoderSettings) -> Result<(), Unsupported> {
check(s.width > 0 && s.height > 0, || "an empty picture".into())?;
check(
s.width.is_multiple_of(2) && s.height.is_multiple_of(2),
|| format!("{}x{}: 4:2:0 needs an even size", s.width, s.height),
|| {
format!(
"{}x{}: the encoder takes even sizes alone",
s.width, s.height
)
},
)?;
check(
s.frame_rate.numerator > 0 && s.frame_rate.denominator > 0,
@@ -517,13 +528,14 @@ impl<A: Accelerator> Encoder<A> {
let intra_period = s.key_frame_interval.unwrap_or(0);
// The coded size: the settings' raised to the driver's least and
// rounded up to `to`, and what the SPS crops off it.
// The codec's block, or the driver's alignment where it is wider.
let coded = |to: u32| {
let size = |value: u32, least: u32| {
let coded = align(value.max(least), to)?;
let size = |value: u32, least: u32, alignment: u32| {
let coded = align(value.max(least), to.max(alignment))?;
Some((coded, coded.checked_sub(value)?))
};
size(s.width, limits.min_width)
.zip(size(s.height, limits.min_height))
size(s.width, limits.min_width, limits.width_alignment)
.zip(size(s.height, limits.min_height, limits.height_alignment))
.ok_or_else(|| Unsupported::overflow("the coded size"))
};
let (headers, coded_size) = match s.profile.codec() {
@@ -580,6 +592,7 @@ impl<A: Accelerator> Encoder<A> {
.ok_or_else(|| Unsupported::overflow("the least coding block"))?;
let ((coded_width, crop_right), (coded_height, crop_bottom)) = coded(min_cb)?;
let needs = hevc::LevelNeeds {
profile: s.profile,
width: coded_width,
height: coded_height,
frames_per_second: fps,
@@ -1441,6 +1454,8 @@ pub mod tests {
min_height: 128,
max_width: 4096,
max_height: 4096,
width_alignment: 1,
height_alignment: 1,
hevc_tools: Some(hevc::Tools {
log2_min_cb_size: 3,
log2_ctb_size: 6,
@@ -1699,6 +1714,66 @@ pub mod tests {
Ok(())
}
/// A coded size, and the rectangle an SPS shows: x, y, width and height.
type Shown = ((u32, u32), (u32, u32, u32, u32));
/// The coded size of an encoder of `profile` at `width` x `height`, under a driver that
/// states the alignment `(width, height)`, and the rectangle its SPS shows, as a decoder's
/// parser reads it.
fn shown(
profile: Profile,
(width, height): (u32, u32),
alignment: (u32, u32),
) -> Result<Shown, Unsupported> {
let limits = DriverLimits {
width_alignment: alignment.0,
height_alignment: alignment.1,
..limits()
};
let encoder = Encoder::new(
Fake::default(),
EncoderSettings::new(profile, width, height),
&limits,
)?;
let rect = match &encoder.headers {
Headers::Hevc { sps, .. } => crate::codec::hevc::sps::Sps::parse(&sps.sps_nal()?)
.expect("our SPS parses")
.crop_rect(),
Headers::H264 { sps, .. } => crate::codec::h264::sps::Sps::parse(&sps.to_nal()?)
.expect("our SPS parses")
.crop_rect(),
};
Ok((encoder.coded_size(), rect))
}
/// The coded size is a multiple of the codec's block and of the alignment the driver
/// states, and the SPS's window (HEVC) or crop (H.264) takes the rest off: a decoder shows
/// the asked rectangle. With none stated, the codec's block alone, as before.
#[test]
fn the_coded_size_follows_the_drivers_alignment_and_the_sps_shows_the_asked_size()
-> Result<(), Unsupported> {
// radeonsi's answers for HEVC (64x16) and H.264 (16x16) on an RX 550 and a Radeon 780M
// (m3-max-85418, m3-max-85437); iHD states none (m3-max-85417).
let cases = [
(Profile::HevcMain, (1920, 1080), (64, 16), (1920, 1088)),
(Profile::HevcMain10, (1920, 1080), (64, 16), (1920, 1088)),
(Profile::HevcMain, (1366, 768), (64, 16), (1408, 768)),
(Profile::HevcMain, (1366, 766), (64, 16), (1408, 768)),
(Profile::HevcMain, (1920, 1080), (1, 1), (1920, 1080)),
(Profile::HevcMain, (1366, 766), (1, 1), (1368, 768)),
(Profile::H264High, (1920, 1080), (16, 16), (1920, 1088)),
(Profile::H264High, (1366, 766), (16, 16), (1376, 768)),
(Profile::H264High, (1366, 766), (1, 1), (1376, 768)),
];
for (profile, size, alignment, coded) in cases {
let at = format!("{profile:?} at {size:?}, the driver's alignment {alignment:?}");
let (got, rect) = shown(profile, size, alignment)?;
assert_eq!(got, coded, "{at}: the coded size");
assert_eq!(rect, (0, 0, size.0, size.1), "{at}: what the SPS shows");
}
Ok(())
}
#[test]
fn hevc_predicts_from_the_last_picture_in_order() -> Result<(), Unsupported> {
let mut settings = EncoderSettings::new(Profile::HevcMain10, 100, 50);
@@ -114,11 +114,14 @@ fn header(unit_type: u8) -> [u8; 2] {
impl Sps {
/// `general_profile_compatibility_flag[j]` as hvcC's 32 bits, flag 0
/// first: Main streams are Main 10 streams too (A.3.2, A.3.3).
/// first: Main streams are Main 10 streams too (A.3.2, A.3.3), and a
/// Main 4:2:2 10 stream is of the format range extensions, profile 4
/// (A.3.5).
pub(crate) fn compatibility_flags(&self) -> u32 {
let flag = |j: u32| 0x8000_0000u32 >> j;
match self.profile {
Profile::HevcMain => flag(1) | flag(2),
Profile::HevcMain42210 => flag(4),
_ => flag(2),
}
}
@@ -132,9 +135,21 @@ impl Sps {
w.flag(false); // general_interlaced_source_flag
w.flag(false); // general_non_packed_constraint_flag
w.flag(true); // general_frame_only_constraint_flag
// general_reserved_zero_43bits (or Main 10's reserved and
// one_picture_only bits, all 0), then general_inbld_flag.
w.bits(44, 0);
if self.profile.profile_idc() == 4 {
// Main 4:2:2 10's constraint flags (Table A.2):
// general_max_12bit, _10bit, _8bit, _422chroma, _420chroma,
// _monochrome, general_intra, general_one_picture_only and
// general_lower_bit_rate_constraint_flag.
for flag in [true, true, false, true, false, false, false, false, true] {
w.flag(flag);
}
// general_reserved_zero_34bits, then general_inbld_flag.
w.bits(35, 0);
} else {
// general_reserved_zero_43bits (or Main 10's reserved and
// one_picture_only bits, all 0), then general_inbld_flag.
w.bits(44, 0);
}
w.u(8, u32::from(self.level_idc));
}
@@ -184,17 +199,21 @@ impl Sps {
w.flag(true); // sps_temporal_id_nesting_flag
self.write_profile_tier_level(&mut w);
w.ue(0); // sps_seq_parameter_set_id
w.ue(1); // chroma_format_idc: 4:2:0
w.ue(u32::from(self.profile.chroma_format_idc()));
w.ue(self.width);
w.ue(self.height);
let cropped = self.crop_right > 0 || self.crop_bottom > 0;
w.flag(cropped); // conformance_window_flag
if cropped {
// In chroma samples: SubWidthC and SubHeightC are 2 (6-1).
// In chroma samples: SubWidthC is 2, and SubHeightC 2 in 4:2:0
// and 1 in 4:2:2 (Table 6-1).
w.ue(0);
w.ue(self.crop_right / 2);
w.ue(0);
w.ue(self.crop_bottom / 2);
w.ue(match self.profile.chroma_format_idc() {
2 => self.crop_bottom,
_ => self.crop_bottom / 2,
});
}
let depth = u32::from(self.profile.bit_depth())
.checked_sub(8)
@@ -554,7 +573,8 @@ struct Level {
max_luma_ps: u64,
/// MaxLumaSr: luma samples a second.
max_luma_sr: u64,
/// MaxBR, in units of 1000 bit/s (CpbVclFactor, Table A.11).
/// MaxBR, in units of CpbVclFactor bit/s (Table A.9; Main's and Main
/// 10's CpbVclFactor is 1000).
max_br: u64,
}
@@ -583,9 +603,20 @@ const fn level(level_idc: u8, max_luma_ps: u64, max_luma_sr: u64, max_br: u64) -
}
}
/// `CpbVclFactor` (Table A.8): what the levels' MaxBR is in units of, in
/// bit/s: 1000 for Main and Main 10, 1667 for Main 4:2:2 10.
const fn cpb_vcl_factor(profile: Profile) -> u64 {
match profile {
Profile::HevcMain42210 => 1667,
_ => 1000,
}
}
/// What a stream needs of its level.
#[derive(Clone, Copy, Debug)]
pub struct LevelNeeds {
/// The profile, whose CpbVclFactor scales the levels' bitrates.
pub profile: Profile,
/// The width in luma samples.
pub width: u32,
/// The height in luma samples.
@@ -633,11 +664,13 @@ impl LevelNeeds {
&& side(h)
&& (size as f64) * self.frames_per_second <= level.max_luma_sr as f64
&& u64::from(self.dpb_pictures) <= max_dpb
// At most MaxBR thousand, so in thousands, rounded up, at most
// MaxBR.
// At most MaxBR units of the profile's CpbVclFactor.
&& self
.bits_per_second
.is_none_or(|bps| u64::from(bps).div_ceil(1000) <= level.max_br)
.is_none_or(|bps| {
(level.max_br.checked_mul(cpb_vcl_factor(self.profile)))
.is_some_and(|max| u64::from(bps) <= max)
})
}
}
@@ -756,6 +789,46 @@ mod tests {
Ok(())
}
/// A Main 4:2:2 10 SPS says profile 4 with Main 4:2:2 10's constraint flags (Table A.2), 4:2:2
/// at 10 bits, and its conformance window in rows of luma (SubHeightC 1), as a decoder's
/// parser reads it.
#[test]
fn a_main_422_10_sps_says_its_profile_and_chroma_format()
-> Result<(), crate::codec::hevc::Error> {
let sps = Sps {
profile: Profile::HevcMain42210,
level_idc: 120,
height: 1088,
crop_right: 8,
crop_bottom: 8,
..sps()
};
let unit = sps.sps_nal().unwrap();
let mut r = BitReader::new(&unit);
r.skip(16 + 8)?;
assert_eq!(r.bits(8)?, 4); // space, tier, profile 4
assert_eq!(r.bits(32)?, 0x0800_0000); // compatible with profile 4 alone
assert_eq!(r.bits(4)?, 0b1001);
// max_12bit, max_10bit, max_8bit, max_422chroma, max_420chroma, max_monochrome, intra,
// one_picture_only, lower_bit_rate; 34 reserved bits and general_inbld_flag.
assert_eq!(r.bits(9)?, 0b1_1010_0001);
assert_eq!(r.bits(32)?, 0);
assert_eq!(r.bits(3)?, 0);
assert_eq!(r.bits(8)?, 120);
let parsed = crate::codec::hevc::sps::Sps::parse(&unit)?;
let ptl = &parsed.profile_tier_level;
assert_eq!(ptl.general_profile_idc, 4);
assert!(ptl.compatible_with(4) && !ptl.compatible_with(2));
assert_eq!(parsed.chroma_format_idc, 2);
assert_eq!(
(parsed.bit_depth_luma_minus8, parsed.bit_depth_chroma_minus8),
(2, 2)
);
assert_eq!(parsed.conformance_window, [0, 4, 0, 8]);
assert_eq!(parsed.crop_rect(), (0, 0, 1912, 1080));
Ok(())
}
#[test]
fn slice_headers_carry_their_reference_sets() -> Result<(), crate::codec::hevc::Error> {
let sps = sps();
@@ -834,6 +907,7 @@ mod tests {
#[test]
fn levels_come_from_tables_a_8_and_a_9() -> Result<(), Unsupported> {
let needs = |width, height, fps, bps| LevelNeeds {
profile: Profile::HevcMain,
width,
height,
frames_per_second: fps,
@@ -856,6 +930,14 @@ mod tests {
assert_eq!(choose_level(&needs(3840, 2160, 60.0, None))?, 153);
assert_eq!(choose_level(&needs(136, 128, 30.0, None))?, 30);
assert!(choose_level(&needs(8192, 8192, 60.0, None)).is_err());
// Main 4:2:2 10's bitrates are 1667 bit/s a unit of MaxBR: level 4's 20 Mbit/s.
let main_422_10 = |bps| LevelNeeds {
profile: Profile::HevcMain42210,
..needs(1920, 1080, 30.0, Some(bps))
};
assert_eq!(choose_level(&main_422_10(15_000_000))?, 120);
assert_eq!(choose_level(&main_422_10(20_004_000))?, 120);
assert_eq!(choose_level(&main_422_10(20_004_001))?, 123);
Ok(())
}
}
@@ -30,6 +30,34 @@ pub(crate) const PROFILE_0_MD5: &str = include_str!("tests/vp9p0.md5");
/// high bits of a 16-bit little-endian word.
pub(crate) const PROFILE_2_MD5: &str = include_str!("tests/vp9p2.md5");
/// A profile 0 stream whose inter frames change size: 30 frames of ffmpeg's
/// `testsrc2` at each size, coded by libvpx-vp9 in one pass with no altref
/// frames, its size changed between frames with `vpx_codec_enc_config_set`,
/// as libvpx's own resize test changes it, in IVF. Its key frame is its first;
/// each frame after a change predicts from frames of the size before, scaled
/// (8.5.2.3): [`RESIZE_SIZES`].
pub(crate) const RESIZE_IVF: &[u8] = include_bytes!("tests/vp9resize.ivf");
/// The MD5 of each frame of [`RESIZE_IVF`] as libvpx's `vpxdec` decodes it, at
/// its own size, over NV12 planes as [`PROFILE_0_MD5`] is. ffmpeg's own VP9
/// decoder gives the same frames.
pub(crate) const RESIZE_MD5: &str = include_str!("tests/vp9resize.md5");
/// [`RESIZE_IVF`]'s sizes: each from the frame it names to the next's.
pub(crate) const RESIZE_SIZES: [(usize, (u32, u32)); 5] = [
(0, (352, 288)),
(8, (176, 144)),
(14, (264, 216)),
(20, (352, 288)),
(26, (320, 240)),
];
/// The size of [`RESIZE_IVF`]'s frame `frame`.
pub(crate) fn resize_size(frame: usize) -> (u32, u32) {
let (_, size) = (RESIZE_SIZES.iter().rev())
.find(|(first, _)| *first <= frame)
.expect("the first frame's size");
*size
}
/// A libvpx stream of one of VP9's formats past profile 0 and profile 2 at 10
/// bits: 352x288, 20 frames of ffmpeg's `testsrc2` coded by libvpx-vp9 (two
/// passes, altref frames on, so hidden frames in superframes), in IVF, with
@@ -1174,6 +1202,37 @@ fn libvpx_streams_of_every_format_decode_every_frame_in_order() {
}
}
/// Each frame of the stream whose inter frames change size comes out at its
/// own size, the accelerator configured again at each change, and the first
/// frame after each change, an inter frame, given its last frame, the frame
/// before it, at the size before.
#[test]
fn a_libvpx_stream_whose_inter_frames_change_size_decodes_every_frame_at_its_own_size() {
let mut decoder = Decoder::new(Recording::default());
for (id, sample) in (0u64..).zip(ivf_frames(RESIZE_IVF)) {
let out = decoder.decode(sample, id).unwrap();
assert_eq!(out.len(), 1, "sample {id} shows one frame");
let frame = usize::try_from(id).unwrap();
assert_eq!(out[0].size, resize_size(frame), "sample {id}");
assert_eq!(out[0].key_frame, id == 0, "sample {id}");
}
assert_eq!(RESIZE_MD5.lines().count(), 30, "a reference MD5 a frame");
let configured: Vec<_> = (decoder.accelerator().configured.iter())
.map(|format| (format.width, format.height))
.collect();
let sizes: Vec<_> = RESIZE_SIZES.iter().map(|(_, size)| *size).collect();
assert_eq!(configured, sizes);
let frames = &decoder.accelerator().frames;
for &(first, size) in &RESIZE_SIZES[1..] {
let (_, header, slots, _) = &frames[first];
assert!(!header.is_intra(), "frame {first}");
assert_eq!((header.width, header.height), size, "frame {first}");
let last = usize::from(header.ref_frame_idx[0]);
let (_, width, height) = slots[last].expect("its last frame");
assert_eq!((width, height), resize_size(first - 1), "frame {first}");
}
}
#[test]
fn decoded_frames_keep_their_pictures_alive_beside_the_slots() {
let mut decoder = Decoder::new(Recording::default());
@@ -0,0 +1,30 @@
382192e69ba47cf2aac051ada618cdc6
658ed97d3f77b828dfa2c70b122293b7
7f483b61d23cc900a33301a8208cd5f9
37ac20777df1fba89044ac3aeeb26898
b74df151274816526c3bce57f84dbee0
751d06ff288eb369139a59b67858bd26
d0fca88b2392acf1793e63f3961fbaa3
aef35dd2ed84595885bab482d68f7ebf
924a448a7a4acd7753021829a8afbfe6
bdc3b78b00226588c18c4c583f299159
9dacde185249742697f45d2e8ea25fb6
eaf5a370c39295d99bd5c206f7922a39
a6527ef009ec06be065c611a255ff25c
bd16282b63ed77b495746bf57b97e019
e165d13a0cfff7aa4a8e02542b97164b
f6ba6bb67670c9385056a5b35d9fa1a2
5d7d23dd933810e29528c0126ef698ff
1964c25c69b459cf4589f3398dd6803a
73f88aff8168799f2f8b46337753dc80
bdf2df94730a01541b09a51650a39ecf
82e0eabc5c4446b5f43c725a3aaf8029
1821dfcb28a2be86229f042ec8094288
dbf7a6cb64937b7bfa5b446e8f8ce347
a5188383b92612271581b258503c89cc
137e188302533648dcd921ba43ff9e9e
ebcd4d300532cdd4e673873dbb456ae8
651e3e03bc1d32edb67638b23a2e6054
f8adc30af51fb3214520cd75f204f092
38d3aeda3edba90a9fcec3a30fc385d3
36e36ae3730922b2fad39c89a4a7c3f3
@@ -289,6 +289,7 @@ pub struct GuestTarget<'a> {
width: u32,
height: u32,
planes: [TargetPlane; 2],
padding_unobserved: bool,
}
impl fmt::Debug for GuestTarget<'_> {
@@ -300,6 +301,7 @@ impl fmt::Debug for GuestTarget<'_> {
.field("width", &self.width)
.field("height", &self.height)
.field("planes", &self.planes)
.field("padding_unobserved", &self.padding_unobserved)
.finish()
}
}
@@ -386,9 +388,28 @@ impl<'a> GuestTarget<'a> {
width: layout.width,
height: layout.height,
planes,
padding_unobserved: false,
})
}
/// The same target, the bytes of each row past its samples, up to its pitch, the host's and
/// read by no one, so that a device may write them, as a driver that writes rows out to whole
/// alignments writes them (the VA crate's `ImportWrite::whole_rows`). A guest's buffer never
/// says so, its padding the guest's to read; a scratch of the host's that is read nowhere but
/// inside its samples' rows does.
pub fn with_padding_unobserved(self) -> Self {
Self {
padding_unobserved: true,
..self
}
}
/// Whether the bytes of its rows past their samples are the host's and read by no one
/// ([`GuestTarget::with_padding_unobserved`]).
pub fn padding_unobserved(&self) -> bool {
self.padding_unobserved
}
/// The memory the planes lie in.
pub fn memory(&self) -> &'a dyn DeviceMemory {
self.memory
+19 -6
View File
@@ -18,6 +18,7 @@
//! [`crate::core::sync`]'s.
use std::fmt;
use std::panic::Location;
use std::sync::{Arc, OnceLock};
use std::thread::JoinHandle;
use std::time::{Duration, Instant};
@@ -106,16 +107,19 @@ pub trait Runtime: Send + Sync {
/// A step of the host's exit gate around one job of a thread of the crate's that calls the
/// hardware's libraries (a call made on a display's or a context's thread, a sweep of work a
/// device did not finish, a drop of imports whose surfaces went): `None` once the process's
/// device did not finish, a drop of imports whose surfaces went), begun at `site`: the job's
/// own call, which the gate names where an exit waits for the step. `None` once the process's
/// exit began, and the thread then parks for good before the job ([`park_for_good`]), so no
/// call of the crate's runs beside the libraries' destructors as the process exits. The step
/// ends as what it returns drops, on the thread. By default a step that guards nothing, for
/// a runtime with no exit gate ([`StdRuntime`]).
fn exit_step(&self) -> Option<ExitStep> {
/// a runtime with no exit gate ([`StdRuntime`]). The crate takes its steps through
/// `exit_step` (below), at its caller's site.
fn exit_step_at(&self, site: &'static Location<'static>) -> Option<ExitStep> {
let _ = site;
Some(ExitStep::default())
}
/// Registers the host's exit gate's exit handler again ([`Runtime::exit_step`]), after the
/// Registers the host's exit gate's exit handler again ([`Runtime::exit_step_at`]), after the
/// crate loaded a hardware library that may register exit-time destructors of its own (a VA
/// display's driver, which `vaInitialize` loads): the C library runs exit handlers in the
/// reverse order of their registration, so the gate then closes, and waits out the steps in
@@ -124,7 +128,16 @@ pub trait Runtime: Send + Sync {
fn arm_exit(&self) {}
}
/// A step of the host's exit gate ([`Runtime::exit_step`]), ended as it drops, on its thread.
impl dyn Runtime + '_ {
/// [`Runtime::exit_step_at`], begun at its caller's site: the call that takes the step, or,
/// through a caller that is itself `#[track_caller]`, that caller's.
#[track_caller]
pub fn exit_step(&self) -> Option<ExitStep> {
self.exit_step_at(Location::caller())
}
}
/// A step of the host's exit gate ([`Runtime::exit_step_at`]), ended as it drops, on its thread.
#[derive(Default)]
pub struct ExitStep(Option<Box<dyn std::any::Any>>);
@@ -146,7 +159,7 @@ impl std::fmt::Debug for ExitStep {
}
/// Parks this thread for good: its runtime refused a step, the process exiting
/// ([`Runtime::exit_step`]).
/// ([`Runtime::exit_step_at`]).
pub fn park_for_good() -> ! {
loop {
std::thread::park();
+2 -1
View File
@@ -7,5 +7,6 @@
//! wait on a [`Condvar`] goes through the runtime's clock ([`crate::core::runtime::Bell`]).
pub use parking_lot::{
Condvar, MappedMutexGuard, Mutex, MutexGuard, RwLock, RwLockReadGuard, RwLockWriteGuard,
Condvar, MappedMutexGuard, Mutex, MutexGuard, ReentrantMutex, RwLock, RwLockReadGuard,
RwLockWriteGuard,
};
Loaded 100 of 628 files, more files were not shown because too many files have changed in this diff. Show more