Skip to content

GPU: write faults read the bytes they save without the guard lock - #3035

Open
liandraraiane wants to merge 4 commits into
Marvisak:mainfrom
liandraraiane:perf/save-outside-guard-lock
Open

liandraraiane wants to merge 4 commits into
Marvisak:mainfrom
liandraraiane:perf/save-outside-guard-lock

Conversation

@liandraraiane

Copy link
Copy Markdown

Problem

Issue #400 measures the guard lock of crates/victory-gpu/src/watch.rs held about 600 ms a world frame on an RTX 2080, with write faults taking about 450 µs each, mostly waiting for it. When a write faults on a page a tracker is armed for, the handler saves the page's 64 KiB before opening it, and it did that (a 64 KiB allocation and a ReadProcessMemory) while holding the guard lock, so every other title thread's fault, every take and every kernel write (writing) queued behind the copy.

Change

The fault reads the bytes it will save with the lock released, then takes the lock again and keeps them only if the page stayed guarded meanwhile. A guarded page's bytes can only change once it is opened, and open is the only place that removes a page from the guard set, so a count per page (folded onto 4,096 counters) is bumped there under the lock and compared when the lock is taken again. If it moved, or the page is no longer guarded, the bytes are read under the lock exactly as before. The bytes read ahead go only to the faulting page's own save, never to an alias's. No protection call moves out of the lock (an earlier attempt that made pages read-only outside it was slower: the protection calls cost more while writers keep running).

Benchmark

guard_lock_contention_bench (new, #[ignore]d): writer threads fault on 256 guarded pages, a submission thread arms every other tracker and takes all of them in rounds, and a kernel-writer thread opens 8-page ranges with writing every 200 µs. Ryzen 7 5700G (16 threads), Windows 11, release. Base = the same benchmark without the change. 15 runs alternated, median with the interquartile range.

Writers working 50 µs between writes (GUARD_BENCH_SPIN_US=50; a title faults far less often than this):

writers faults/s fault p99 µs take round µs 8-page writing p99 µs
4 52,125 → 53,432 202.5 → 202.8 266.4 [264–268] → 224.8 [224–227] 497.4 → 442.6
8 83,372 → 86,820 303.7 [300–306] → 291.0 [289–292] 315.6 [310–318] → 278.9 [277–282] 603.0 [591–622] → 479.4 [471–493]
15 102,795 → 111,712 481.1 [478–485] → 410.3 [409–413] 470.0 [459–481] → 355.3 [351–358] 1038.6 [978–1050] → 739.3 [736–752]

Writers writing back to back (saturated):

writers faults/s fault p50 µs fault p99 µs 8-page writing p99 µs
4 154,499 → 148,130 21.9 → 22.4 290.2 → 290.8 508.0 → 492.2
8 155,385 → 150,264 43.9 → 44.9 345.1 → 344.3 631.8 → 580.0
15 174,479 → 171,551 75.1 → 75.4 475.2 → 465.1 1009.5 → 784.1

In the saturated case a fault that saves takes the lock twice, and throughput drops 2–4 %; the tail of kernel writes still improves.

Tests

  • New saved_bytes_are_the_page_as_taken_under_concurrent_faults: 12 writers fault on armed pages while the main thread takes, copies and arms in rounds; whatever a tracker saved of a page must equal the copy taken of it. With the opened-count check removed it fails 10/10 release runs; with this change it passes 20/20.
  • New concurrent_writes_and_takes_lose_no_write: no write lost between a take's guard and its copy, no stray fault (it caught a race in the rejected attempt above, 2/10 runs); 20/20 here.
  • cargo test -p victory-gpu --lib: all pass except the two tests that fail on NVIDIA on main as well (dynamic_slots_are_held_until_released, lists_share_a_table_and_copies_keep_their_views, the capped view heap). cargo clippy --workspace --all-targets -- -D warnings: clean. rustfmt --check reports the same 39 differences in watch.rs as on main, none in the new code.
  • Flakiness, 100 full victory-gpu runs each, interleaved: descriptor::host views_bound_while_another_slot_gets_its_texture_do_not_wait (base 4, this 7) and a_slot_rewritten_while_its_view_is_prepared_views_the_new_record (2, 4) fail now and then on both, and on unmodified main too (1 of 25 each). shadow::tests::partial_refresh_under_marked_range_updates_saved_bytes failed once in about 160 full runs of this change (0 in 100 interleaved runs here, 0 in about 170 of the base); I could not reproduce it or find a path that explains it, so I am reporting it.

Not tested

The title (no game data here). AMD GPUs. The benchmark is synthetic: the fault rate, page counts and arming pattern are made up, and a title's VirtualProtect calls cost much more than here.

AI use

Claude Code (Claude Opus 5.5) wrote the change, tests and benchmark, ran every measurement above on this machine and drafted this description; I reviewed and approved it.

🤖 Generated with Claude Code

https://claude.ai/code/session_01SLrhrPRF9pqyeEQtcgYu3x

@kotekompotek kotekompotek left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM — verified the race argument: a protected page can't be written without faulting, every unguard path goes through open() which bumps OPENED, so still-protected + unchanged counter on re-lock proves the read was pre-write. take_if hands bytes to one tracker, others fall back to under-lock reads. Lock order g→changed→saved consistent throughout. The 12-writer stress test is a real check.

@pickles976

Copy link
Copy Markdown

Wine/NVIDIA cross-check of the two new concurrency tests — both pass on a different host class. Head 9e0eaa811e7f1c2924eab406941705434e593d43, Linux + Wine 11.0 (vkd3d-proton 3.2.0, NVIDIA 590.48.1), RTX 4060 Laptop GPU, i.e. neither the 5700G/Windows nor the 2080 that motivated #400. Wrapper-injected --locked --target x86_64-pc-windows-msvc, one test thread, fresh Compiling victory-gpu .../VIctory-pr3035/... provenance.

  • watch::tests::saved_bytes_are_the_page_as_taken_under_concurrent_faults — 1/1 pass (0.31 s): the 12-writer take/copy/arm rounds saved exactly the taken bytes on this host too.
  • watch::tests::concurrent_writes_and_takes_lose_no_write — 1/1 pass (1.19 s): no write lost between a take's guard and its copy, no stray fault.

Scope: correctness of the lock-release scheme on this host only. I did not run the #[ignore]d guard_lock_contention_bench, so no throughput/latency numbers from here — the author's 5700G tables stand unchallenged, and the saturated-case 2–4 % fault-throughput trade-off remains their measurement. Wine's VirtualProtect/exception path differs from Windows', so a pass here is cross-platform robustness evidence, not a preview of the Windows win. No title run.

Local logs: .compat-runtime/logs/verify-pr3035-wine-saved-bytes.log, verify-pr3035-wine-no-lost-write.log. AI-assisted verification and report (OpenAI Codex).

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>
@pawrenity

Copy link
Copy Markdown

VERIFY-3035: verified 9e0eaa8 on NVIDIA GeForce RTX 4070, Windows 11 (MSVC). No defects found.

Tests

  • cargo test -p victory-gpu --lib at head: 231 passed, 2 ignored, 2 failed. With --features diagnostics: 246 passed, 2 failed. The two failures are dynamic_slots_are_held_until_released and lists_share_a_table_and_copies_keep_their_views, which also fail on main on this card.
  • watch:: in release (both new tests included): 20/20 passes. shadow:: in release: 10/10 passes, including partial_refresh_under_marked_range_updates_saved_bytes.
  • Mutation at head: with the opened(page) == before comparison in the handler replaced by true, saved_bytes_are_the_page_as_taken_under_concurrent_faults fails 10/10 release runs (page 9 saved other bytes than taken). The test does catch the race the counter guards against.
  • The two new tests, applied alone to origin/main 63bcca4, pass 5/5 in release. They check properties that main already holds, so they are not regression tests for a defect on main.
  • cargo clippy -p victory-gpu --all-targets -- -D warnings is clean, with and without --features diagnostics.
  • Trial merge onto origin/main 63bcca4 is clean.

Benchmark (guard_lock_contention_bench, release, GUARD_BENCH_SPIN_US=50 GUARD_BENCH_MS=1000, 3 runs each alternating base/PR; few samples, so indicative only):

writers faults/s base -> PR fault p99 us take round p50 us 8-page writing p99 us
8 77.4k-81.4k -> 83.4k-84.8k 347-386 -> 342-348 354-417 -> 318-330 636-685 -> 503-534
15 95.2k-104.0k -> 106.1k-113.3k 540-644 -> 491-537 513-585 -> 391-416 891-986 -> 730-763

At 1, 2 and 4 writers the runs overlap. This agrees in direction with the PR's 5700G tables. I did not run the saturated (spin 0) case.

Review (reading only)

  • Lock ordering: would_save keeps c.0 locked while it takes c.1, because the shadowed guard is not dropped until the end of the function. It is called with the guard lock held, so its order is guards -> c.0 -> c.1. take_split and Tracked::taken use the same order (guards -> c.0 -> Changed::taken's c.1). The other paths (save, arm, unarm, disarm, saved, refreshed) take only c.1, and none takes the guard lock or c.0 while holding it. I found no inversion.
  • Counter invariant: open() (watch.rs:480) is the only place that removes from protected, and it is the only PAGE_READWRITE call. Tracked::drop, writing and its drop, title_memory_remapped, title_memory_aliased and the handler all reach it through open. Every way a page stops being guarded therefore bumps OPENED. Both the bump and the loads happen under the guard lock, so Relaxed is enough. When the page is guarded at both ends and the count is unchanged, the read lies inside one continuously read-only interval. Any holder that has the page un-changed at re-lock took it inside that interval, so giving the read-ahead to the first saving holder (which may not be the one would_save matched) is still correct.
  • Interleavings checked: a take by another holder during the unlocked read (no open, so the bytes stay valid); refreshed running between the read and the insert (it finds no saved entry, as on main, and its bytes equal memory); the tracker being dropped meanwhile (changed() reads holders again, and an unused read is freed); the page opened and guarded again (the count moves, so it falls back to the read under the lock).
  • Assumption carried over from main: a write that bypasses both the handler and writing (for example through an alias mapping that is not guarded) is not seen. The read-ahead window does not make this worse, because main read at fault time with the same exposure.

AI-assisted (Claude Code).

@fyernald fyernald left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ran 9e0eaa8 on Windows 10 22H2 with a Ryzen 7 5700X (8 cores / 16 threads, close to your 5700G), release build. For the base, I copied your new tests and the benchmark onto main 63bcca4's watch.rs without the change.

Correctness, 20 runs each:

base this PR
concurrent_writes_and_takes_lose_no_write 20/20 20/20
saved_bytes_are_the_page_as_taken_under_concurrent_faults 20/20 20/20
watch:: 17 passed 17 passed

guard_lock_contention_bench, 7 runs per build, alternated, medians:

GUARD_BENCH_SPIN_US=50

writers faults/s fault p99 µs take round µs 8-page writing p99 µs
4 45,521 → 48,053 270.4 → 266.8 464.9 → 371.4 475.2 → 382.1
8 69,687 → 72,738 465.2 → 455.2 565.3 → 469.2 801.3 → 662.5
15 81,451 → 86,496 694.1 → 619.3 748.9 → 557.3 1,181.1 → 905.5

Saturated (GUARD_BENCH_SPIN_US=0)

writers faults/s fault p50 µs fault p99 µs 8-page writing p99 µs
4 86,946 → 91,901 38.0 → 36.6 405.7 → 381.1 818.2 → 620.3
8 89,959 → 95,125 53.1 → 51.0 586.2 → 522.9 1,147.0 → 762.7
15 93,839 → 98,881 62.8 → 72.4 937.3 → 812.7 1,491.4 → 1,144.3

One difference from your numbers: saturated throughput goes up 5–6% here instead of down 2–4%, though the 15-writer fault p50 is up 15%. Faults are slower here than in your table at saturation (38 µs p50 at 4 writers vs your 22 µs), so the second lock taking may cost less than the read it moves out of the lock on this machine.

On the code: open is the only place a page leaves protected, and it bumps the count. Copy-backs and kernel writes reach it through writing, and remaps through changed → open_guarded. So bytes kept after the recheck can't include a write, and I found no path that changes a guarded page's bytes without opening it.

The two descriptor::host flakes you list (views_bound_while_another_slot_gets_its_texture_do_not_wait, a_slot_rewritten_while_its_view_is_prepared_views_the_new_record) are the ones #2585 fixes. It's test-only: their hook was one global shared by tests running in parallel.

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>

@fuzeofficlal fuzeofficlal left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Static review of 9e0eaa81 (crates/victory-gpu/src/watch.rs).

The lock-splitting design looks sound:

  • Capturing opened = OPENED.load(Acquire) before dropping GUARDS and rechecking g.protected.contains(&page) + OPENED after reading the page (while keeping the page read-only during read_into) prevents ABA across reopens, aliases, and remaps — open() bumps OPENED under GUARDS before VirtualProtect restores write access, so any concurrent unprotect/write forces a retry or sees the page already open.
  • Only holders with an armed tracker trigger a save, and saved is populated after re-acquiring GUARDS only if the page stayed protected.

Two minor non-blocking notes:

  • In Changed::would_save, let saved = ... shadows the earlier MutexGuard rather than explicitly dropping self.0 before locking self.1 (the lock order changed.0 -> changed.1 is still consistent with the rest of watch.rs, so no deadlock, just slightly subtle).
  • In Changed::save, read.take_if(...) moves the snapshot buffer into the first armed tracker; when multiple armed trackers share the same page, subsequent trackers clone as intended.

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>

Copy link
Copy Markdown
Owner

Automated triage for the maintainers.

In crates/victory-gpu/src/watch.rs, the write-fault handler now reads the 64 KiB it is about to save without holding the guard lock. It keeps those bytes only if, back under the lock, the page is still guarded and its OPENED count has not moved. Otherwise it reads under the lock as before (Changed::save, page_bytes). I checked the invariant this relies on: at this head, open() is the only place that removes a page from protected and the only PAGE_READWRITE call, and it bumps the count under the guard lock. So bytes read while the page stayed guarded cannot include a write. The bytes read ahead are used only for the faulting page's own save. Alias pages and other holders still read under the lock. All other callers of changed pass &mut None, so their behaviour does not change. This is a host-side locking change with measured benefit (#400 and the benchmark tables), not a change to emulated behaviour. The new tests pass on main too, so they are guards against regressions rather than reproductions of a bug. An independent run in this thread showed that the concurrent-faults test fails when the count check is removed.

CI: check passing.


Generated by Claude Code

@MeMako

MeMako commented Nov 26, 2026

Copy link
Copy Markdown

Verified #3035 (9e0eaa8) on Windows 11 (10.0.26200, Ryzen 9 7950X, RX 9070 XT, driver 32.0.32029.2010, 32 GB RAM).

Tests

  • cargo clippy -p victory-gpu --all-targets --locked -- -D warnings: clean.
  • victory-gpu: 272/272 passed (including saved_bytes_are_the_page_as_taken_under_concurrent_faults and concurrent_writes_and_takes_lose_no_write, with 0 lost writes in the stress tests).

Live Title Verification (RX 9070 XT)

  • Setup: Local integration branch (main 63bcca4 + #2051 + #2472 + #2918 + #1010 + #2130 with VRAM upload flags off + #3055 + #2914), adding #2985 + #2849 + #3035 together in the same live run (n=54 world frames / n=38 heavy frames vs. n=51 / n=38 baseline).
  • Result: 0 crashes or visible corruptions through the intro and opening world scene.
  • Subsystem metrics (steady tail, last 20 heavy frames — 6,186 draws vs. 5,290 draws in baseline):
    • prep → deferred: 92.7 → 71.8 ms (-20.9 ms / -22.5%)
    • copy_back → marks: 71.6 → 63.5 ms (27.2 → 25.8 µs/page)
    • Total copy_back: 99.2 → 75.5 ms (-23.7 ms / -23.9%)
    • (Both watch.rs timers reflect #3035 and #2849 combined; #2985 affects texture detile/upload separately.)
  • Combined frame-time delta (all three PRs #2985 + #2849 + #3035 together): steady-tail frame time dropped 453.3 → 423.6 ms (2.20 → 2.40 fps), even with +17% more draws.

Merge Note with #2849 & #2918

  • When combined with #2849 (batched open_range), placing #3035's opened(page).fetch_add(1, Ordering::Relaxed) inside open_range's if g.protected.remove(&page) loop keeps every page open counted under GUARDS.
  • When combined with #2918, #3035's new test saved_bytes_are_the_page_as_taken_under_concurrent_faults just adapts t.saved(page) to Finished::Saved(bytes) = t.finish(page).

Hardware runs were performed by me on my 7950X / RX 9070 XT; comment drafted with Antigravity.

@Dukestar69 Dukestar69 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tested locally merged onto origin/main (63bcca4) on Windows 11 x64:

  • Diff review: Reading guarded 64 KiB page bytes outside the guard lock and validating against the per-page OPENED generation counter + guarded state once back under the lock cleanly avoids holding the global guard lock across 64 KiB copies on write faults while falling back safely if the page was opened meanwhile.
  • cargo test -p victory-gpu watch::tests -- --test-threads=1: all tests passed.
  • cargo clippy -p victory-gpu --all-targets -- -D warnings: clean.
  • cargo xtask policy: 191 files ok.

Synthetic tests only (no game files used). AI-assisted (Gemini 4 Neon).

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>
Claude-Session: https://claude.ai/code/session_01SLrhrPRF9pqyeEQtcgYu3x
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants