Skip to content

GPU: write faults read the bytes they save without the guard lock (revives #3035) - #3754

Open
reallyvibe wants to merge 4 commits into
Marvisak:mainfrom
reallyvibe:perf/fault-read-outside-guard-lock
Open

reallyvibe wants to merge 4 commits into
Marvisak:mainfrom
reallyvibe:perf/fault-read-outside-guard-lock

Conversation

@reallyvibe

Copy link
Copy Markdown

This revives #3035, which was closed without merging, and adds independent validation on native Windows. The optimisation is not mine: the four commits are #3035's, unchanged (the same tree as its head 9e0eaa81), applied cleanly onto main 63bcca43, and each one's (cherry picked from …) line records where it came from. The commits carry a neutral author identity. My part is the re-checking below and the coordination.

Claim: #1633 (comment)

What it changes

watch.rs's write-fault handler saves a page's 64 KiB before its first write, for trackers armed on it. Today it reads those bytes while holding watch::GUARDS, so every other write fault and every take waits behind the copy.

With this change, when the page is guarded and a tracker would save it, the handler:

  1. notes the page's OPENED count;
  2. drops the lock;
  3. reads the page;
  4. takes the lock again;
  5. keeps the bytes only if the page is still guarded and its count has not moved.

Otherwise the bytes are read under the lock, as before (one extra 64 KiB read). Only the first armed tracker of the faulting page uses the read-ahead bytes. Alias pages and other trackers of the same page still read under the lock.

Why the kept bytes are the pre-write bytes

  • open() is the only place a page leaves protected (the only protected.remove). It bumps OPENED[page] before calling VirtualProtect(PAGE_READWRITE).

  • Every path that makes a guarded page writable while holding GUARDS goes through open(): write faults, writing (kernel writes and our own copy-backs), remaps and unmaps (title_memory_remapped), new aliases (title_memory_aliased), all through changed → open_guarded, and tracker drops (Tracked::drop).

  • So "guarded at both ends, count unchanged" means no GUARDS holder opened the page during the read, and title code could not have written it without faulting.

  • Two kinds of writer change a guarded page's bytes without GUARDS:

    • writes into physical pages through the runtime's own views (DirectStorage's write_physical and PageWindow), which are reported only after they land;
    • memory freed and allocated again without the runtime being told (the shortcut watch.rs documents).

    Neither ever took GUARDS, so the lock on main did not exclude them either. The read still happens right after the handler first takes the lock, as on main; only the time between the read and storing the bytes grows, and these writers cannot change bytes already read. Their exposure is unchanged by this PR, not fixed by it.

  • The count is folded onto 4,096 slots. A collision only makes the check fail more often, and then the bytes are read under the lock.

  • The read goes through ReadProcessMemory, which fails instead of faulting if the page was freed meanwhile; that case also falls back to the read under the lock.

This argument comes from reading the code; the tests below check it under contention but cannot prove it.

Integration risk: pages opened outside open()

The argument above holds on main only because every opening goes through open(). neonbyte1 found the case that breaks it on a stack that opens a whole run of guarded pages with one VirtualProtect and removes them from protected directly (comment): a fault's unlocked read can straddle a complete open, copy-back write and re-guard, find the page guarded with an unchanged OPENED count, and keep stale bytes. The fix there is to bump OPENED for every page such a path opens. So whichever lands second of this PR and any of these must add those bumps:

Known test failures, before and here

Measured before it closed (others' numbers)

  • In game (neonbyte1, RTX 5090, Linux/Wine, 420 s runs, control adjacent): one pair of runs, on main plus the unmerged PRs that setup needs (listed in Frame budget: where the time goes in the prison yard (RTX 5090, Linux/Wine), and which PRs move it #3425, including copy-back in page runs, the case above), not on plain main:
    • frame 196.1 → 188.6 ms;
    • fault-handler time ~58 → 50.0 ms per frame;
    • preparing 75.8 → 68.4 ms.
  • guard_contention (KainanP, comment):
    • with trackers armed, the writers' GUARDS wait is 0.55× of main (quartiles 0.51–0.60), and the refresh's falls from 8.7 to 0.05 ms;
    • with nothing armed, no change (0.96–1.07, within noise);
    • two aliased mappings read 1.07× for both, with quartiles 0.95–1.21: inconclusive.
  • GPU: write faults read the bytes they save without the guard lock #3035's own guard_lock_contention_bench tables reported a 2–4% loss of fault throughput when writers saturate the lock; fyernald measured a 5–6% gain there instead on another machine, with the 15-writer fault p50 up 15%. I did not rerun that benchmark.
  • Negative control (pawrenity): with the OPENED comparison replaced by true, saved_bytes_are_the_page_as_taken_under_concurrent_faults failed 10 of 10 release runs.

I have no game files. Everything I ran is synthetic and says nothing about frame time.

Tested here

Windows 11 26H2 (build 26300), Ryzen 7 7445HS, RTX 4050 Laptop (driver 616.64), Rust 1.98.1 MSVC, CARGO_BUILD_JOBS=1.

Run main 63bcca4 this branch
victory-gpu lib tests that need no GPU (debug) 141: 140 passed, 1 ignored 143: 142 passed, 1 ignored (the 2 new tests; per-test outcomes otherwise identical)
shadow:: saved-byte and copy-back tests on the GPU (8) 8 passed 8 passed
concurrent_writes_and_takes_lose_no_write, release, 20 runs — 20 of 20 passed
saved_bytes_are_the_page_as_taken_under_concurrent_faults, release, 20 runs — 20 of 20 passed
Negative control: the OPENED comparison replaced by true, 10 release runs — 0 of 10 passed: every run "page N saved other bytes than taken"; source restored (tree equals #3035's head)
cargo clippy -p victory-gpu --all-targets -- -D warnings (default / --all-features) clean / clean clean / clean
cargo fmt --all --check fails (pre-existing long lines in many files) fails identically; no new findings from this change
cargo xtask policy 191 files ok 191 files ok

Not run here: the other 91 victory-gpu tests (GPU and shader tests beyond those 8), and the rest of the workspace. Windows CI run 45754273382 (Tests, Clippy and diagnostics Clippy) succeeded on #3035's head, whose tree is identical to this branch's.

The tests cannot show whether the read-ahead bytes are ever kept rather than read again: if the check always failed, every test would still pass. The benchmark below is what shows that.

Native-Windows contention benchmark

Same machine. KainanP's guard_contention (ab96ee44, test-only, on 63bcca43) applied to both main 63bcca43 and this branch, plus one identical addition: a write count, printed as writes per second (all writers' writes during the refresh, divided by its duration). Both test binaries were built with the same toolchain and settings (release, --locked). The benchmark's WAITED times every lock acquisition that finds GUARDS taken, in both builds; this branch's handler takes the lock twice when it reads ahead, and both waits count.

Defaults otherwise: 256 MB pool, copies of 32 pages, 1,400 pages dirtied before each refresh, 11 counted rounds per run (each run's figure is its median). One warm-up run of each build per configuration, then 5 measured runs alternating main and branch (order flipped each repetition, 10 s pause before each run); nothing armed was extended to 10 runs because 5 left it ambiguous. Heavy background apps were closed; on AC power, Balanced plan.

Medians over runs, with the observed range. "Writer wait" is the writers' total wait for GUARDS per round; "refresh wait" is the refresh's.

configuration metric main this branch change
armed (4 writers, 20 µs apart) writes/s 22,038 (21,662–22,102) 32,000 (31,613–35,319) +9,962 (+45.2%)
writer wait 166.5 ms (165.6–169.1) 105.8 ms (98.7–119.3) −60.7 ms (−36.4%)
refresh wait 13.06 ms (12.59–13.56) 0.37 ms (0.25–0.44) −12.68 ms (−97.2%)
refresh 56.6 ms (55.9–57.2) 49.4 ms (48.2–57.0) −7.2 ms (−12.7%)
nothing armed (10 runs) writes/s 99,261 (96,714–104,330) 98,394 (94,196–102,487) −867 (−0.9%)
writer wait 45.72 ms (43.45–47.03) 45.56 ms (42.33–48.93) −0.16 ms (−0.4%)
refresh wait 0.449 ms (0.334–0.516) 0.456 ms (0.336–0.617) +0.007 ms (+1.4%)
refresh 35.28 ms (34.88–36.48) 34.67 ms (34.03–35.66) −0.61 ms (−1.7%)
two aliased mappings, armed writes/s 19,128 (18,350–19,387) 25,123 (21,541–26,738) +5,995 (+31.3%)
writer wait 182.4 ms (180.9–186.2) 124.8 ms (121.4–132.0) −57.6 ms (−31.6%)
refresh wait 13.61 ms (13.56–15.18) 1.26 ms (0.98–1.41) −12.35 ms (−90.7%)
refresh 59.7 ms (59.3–61.6) 50.3 ms (49.7–51.5) −9.4 ms (−15.8%)
saturated, armed (8 writers, no pause) writes/s 46,402 (44,647–47,575) 57,388 (54,277–60,888) +10,986 (+23.7%)
writer wait 702.7 ms (685.1–716.5) 367.2 ms (354.4–408.5) −335.6 ms (−47.8%)
refresh wait 46.75 ms (46.46–48.47) 4.00 ms (3.80–4.20) −42.75 ms (−91.4%)
refresh 98.2 ms (95.8–100.0) 62.3 ms (59.8–70.8) −36.0 ms (−36.6%)

Reading:

  • With trackers armed (alone, with aliases, and saturated) every run of this branch beat every run of main on writes/s, writer wait and refresh wait. The writers' wait is 0.64× of main's here (KainanP measured 0.55× on their machine).
  • With nothing armed there is no measurable change: the ranges overlap and the run-by-run differences go both ways (5 of 10 each). With run-to-run spread of several percent, these runs cannot rule out an effect of a few percent either way.
  • No measurable regression in any tested configuration. That is not a guarantee of none elsewhere: other machines, workloads and stacks may differ.
  • The two-mapping case, inconclusive in KainanP's runs, improved here with trackers armed. I did not run it with nothing armed.
  • With more writes landing during the refresh, the armed refresh copies more (151 vs 138 MB median); that follows from the extra writes, not from extra work per page.

Limits: one laptop, synthetic workload, 5 runs per configuration (10 for nothing armed), no significance tests, no thermal readings, a few light background apps still running.

Reproduce, and every measured run

The write counter, applied to watch.rs on both sides after KainanP's commit:

--- a/crates/victory-gpu/src/watch.rs
+++ b/crates/victory-gpu/src/watch.rs
@@
         // writers and the refresh waited for the guard lock.
-        let mut rows: Vec<[f64; 8]> = Vec::new();
+        let mut rows: Vec<[f64; 9]> = Vec::new();
         for round in 0..=rounds {
@@
                                 (0f64, 0u64, 0f64, 0f64);
+                            let mut writes = 0u64;
                             while !stop.load(Ordering::Relaxed) {
@@
                                 total += us;
+                                writes += 1;
                                 if us > 5.0 {
@@
                             }
-                            (total, slow, slow_us, longest, WAITED.get())
+                            (total, slow, slow_us, longest, WAITED.get(), writes)
                         })
@@
             let longest = spent.iter().map(|s| s.3).fold(0f64, f64::max);
+            let writes: u64 = spent.iter().map(|s| s.5).sum();
             rows.push([
@@
                 refresh_waited as f64 / 1e3,
+                writes as f64 / (ms / 1e3),
             ]);
@@
         println!(
-            "guard_contention: refresh_ms={:.3} writes_ms={:.3} writers_wait_ms={:.3} slow={:.0} slow_us={:.2} longest_us={:.0} mb={:.1} refresh_wait_ms={:.3}",
+            "guard_contention: refresh_ms={:.3} writes_ms={:.3} writers_wait_ms={:.3} slow={:.0} slow_us={:.2} longest_us={:.0} mb={:.1} refresh_wait_ms={:.3} writes_per_s={:.0}",
             m(0),
@@
             m(5),
-            m(7)
+            m(7),
+            m(8)
         );

Steps (Git Bash; the same on both sides):

git fetch https://github.com/KainanP/VIctory ab96ee44e6bf35ec1dc5cd97c0f059797950b2e8
git cherry-pick --no-commit ab96ee44   # on this branch: one conflict, both sides append to the end of watch.rs's tests module; keep both
# apply the write counter above
cargo test --release -p victory-gpu --locked --lib --no-run
# then, per configuration, with the test binary cargo printed:
BENCH_ARMED=1 <binary> --ignored --exact watch::tests::guard_contention --nocapture --test-threads=1
BENCH_ARMED=0 <binary> ...                                          # nothing armed
BENCH_ARMED=1 BENCH_ALIASED=1 <binary> ...                          # two aliased mappings
BENCH_ARMED=1 BENCH_GAP_US=0 BENCH_WRITERS=8 <binary> ...           # saturated

Each run's medians, from its guard_contention: line, in the order each pair ran:

configuration run build writes/s writer wait ms refresh wait ms refresh ms
armed 1 main 22038 166.463 13.394 56.824
armed 1 branch 32000 106.231 0.372 49.406
armed 2 branch 31613 105.811 0.257 50.489
armed 2 main 22102 169.051 13.555 57.235
armed 3 main 22101 165.595 12.585 55.875
armed 3 branch 35319 98.653 0.251 48.733
armed 4 branch 31943 119.290 0.442 57.040
armed 4 main 21662 168.585 12.643 56.598
armed 5 main 21914 166.459 13.055 56.497
armed 5 branch 32676 100.626 0.397 48.169
unarmed 1 main 99560 44.515 0.516 35.295
unarmed 1 branch 98709 45.921 0.470 35.012
unarmed 2 branch 94196 48.931 0.562 35.660
unarmed 2 main 98629 45.676 0.449 35.061
unarmed 3 main 101556 46.247 0.449 35.496
unarmed 3 branch 94810 48.049 0.617 35.028
unarmed 4 branch 97376 45.410 0.421 34.755
unarmed 4 main 96714 46.969 0.424 34.967
unarmed 5 main 97086 46.232 0.424 35.161
unarmed 5 branch 98079 45.701 0.529 34.591
unarmed 6 branch 100611 42.326 0.424 34.027
unarmed 6 main 104330 45.441 0.489 35.264
unarmed 7 main 98523 45.762 0.476 35.764
unarmed 7 branch 101848 43.728 0.336 35.118
unarmed 8 branch 100261 43.421 0.377 34.303
unarmed 8 main 98962 47.032 0.477 36.483
unarmed 9 main 100423 43.716 0.334 34.882
unarmed 9 branch 102487 42.585 0.441 34.566
unarmed 10 branch 96827 47.023 0.544 34.541
unarmed 10 main 103941 43.445 0.359 35.835
aliased 1 main 18350 183.115 13.612 59.852
aliased 1 branch 26738 121.368 0.982 49.691
aliased 2 branch 25123 127.978 1.364 51.501
aliased 2 main 19387 180.910 13.843 59.734
aliased 3 main 19128 181.368 13.581 59.316
aliased 3 branch 26402 124.777 1.262 50.322
aliased 4 branch 21541 132.043 1.414 50.090
aliased 4 main 19267 186.226 15.183 61.630
aliased 5 main 18566 182.393 13.557 59.469
aliased 5 branch 24489 124.046 1.208 50.301
saturated 1 main 46129 702.737 46.951 98.246
saturated 1 branch 54322 386.495 3.814 64.462
saturated 2 branch 57388 358.020 4.000 61.059
saturated 2 main 44647 692.406 46.459 96.130
saturated 3 main 46402 712.508 46.749 99.091
saturated 3 branch 54277 367.152 3.801 62.289
saturated 4 branch 58062 354.438 4.162 59.752
saturated 4 main 47575 685.121 46.618 95.751
saturated 5 main 47358 716.548 48.471 100.047
saturated 5 branch 60888 408.504 4.195 70.817

Interactions

AI-assisted (Claude Code).

VIctory contributor and others added 4 commits November 28, 2026 16:56
A benchmark of the guard lock under contention (issue Marvisak#400 puts about
940 write faults a frame at about 450 us each, mostly waiting for the
lock): writer threads fault on a hot set of guarded pages while a
submission thread arms and takes every tracker in rounds. Prints faults
a second, fault latency (median, 99th percentile) and a take round's
median per writer count.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 19856bc)
Twelve writer threads fault on guarded pages while a taker arms, takes
and copies every tracker (and reports pages taken by copy-back): at the
end every page whose copy differs from title memory must still be
changed, and no write may fault past the handler. Against a version
that made pages read-only outside the guard lock with a race between a
stale fault and the take, it failed 2 of 10 release runs (the process
died); main passes 20 of 20.

The contention benchmark gains GUARD_BENCH_SPIN_US, the time each writer
works between writes (closer to a title's fault rate than writing
back to back).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 86510ac)
A thread opens 8-page ranges with `writing` every 200 us, as a file read
or DirectStorage does, and the benchmark prints the median and 99th
percentile of each (the opening and the marking after). Issue Marvisak#400 puts
`writing` first among the guard lock's holders (174 ms a frame).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit a2189cb)
A write fault on a page a tracker is armed for saves the page's 64 KiB
before opening it, and did so (an allocation and a kernel copy) while
holding the guard lock that every title thread's write fault, every take
and every kernel write wait for (issue Marvisak#400: about 450 us a fault, the
lock held about 600 ms a world frame). The fault now reads the bytes with
the lock released and keeps them only if the page stayed guarded
meanwhile: a count per page (folded onto 4,096) is bumped under the lock
whenever a page is opened, the only way a guarded page's bytes can
change, and checked when the lock is taken again. Otherwise the bytes are
read under the lock, as before. The bytes go to the page's own save only,
not to its aliases'.

A new test checks the oracle under contention: whatever a tracker saved
of a page equals the copy taken of it; with the opened-count check
removed it fails 10 of 10 runs. The concurrency tests now stop their
writers when an assertion fails instead of hanging.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 9e0eaa8)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant