GPU: write faults read the bytes they save without the guard lock #3033
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/3035"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Imported from Marvisak/VIctory. Originally posted by liandraraiane on 2026-11-26T04:17:28Z.
Problem
Issue #400 measures the guard lock of
crates/victory-gpu/src/watch.rsheld 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 aReadProcessMemory) 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
openis 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 withwritingevery 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):writingp99 µsWriters writing back to back (saturated):
writingp99 µsIn the saturated case a fault that saves takes the lock twice, and throughput drops 2–4 %; the tail of kernel writes still improves.
Tests
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.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 onmainas 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 --checkreports the same 39 differences inwatch.rsas onmain, none in the new code.victory-gpuruns each, interleaved:descriptor::hostviews_bound_while_another_slot_gets_its_texture_do_not_wait(base 4, this 7) anda_slot_rewritten_while_its_view_is_prepared_views_the_new_record(2, 4) fail now and then on both, and on unmodifiedmaintoo (1 of 25 each).shadow::tests::partial_refresh_under_marked_range_updates_saved_bytesfailed 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
VirtualProtectcalls 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
Imported from Marvisak/VIctory. Originally posted by kotekompotek on 2026-11-26T04:42:18Z.
Review: APPROVED
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.
Imported from Marvisak/VIctory. Originally posted by fyernald on 2026-11-26T05:04:10Z.
Review: APPROVED
Ran
9e0eaa8on 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 ontomain63bcca4'swatch.rswithout the change.Correctness, 20 runs each:
concurrent_writes_and_takes_lose_no_writesaved_bytes_are_the_page_as_taken_under_concurrent_faultswatch::guard_lock_contention_bench, 7 runs per build, alternated, medians:GUARD_BENCH_SPIN_US=50writingp99 µsSaturated (
GUARD_BENCH_SPIN_US=0)writingp99 µsOne 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:
openis the only place a page leavesprotected, and it bumps the count. Copy-backs and kernel writes reach it throughwriting, and remaps throughchanged→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::hostflakes 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.Imported from Marvisak/VIctory. Originally posted by pickles976 on 2026-11-26T04:45:56Z.
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, freshCompiling 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]dguard_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'sVirtualProtect/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).Imported from Marvisak/VIctory. Originally posted by pawrenity on 2026-11-26T05:04:10Z.
VERIFY-3035: verified
9e0eaa8on NVIDIA GeForce RTX 4070, Windows 11 (MSVC). No defects found.Tests
cargo test -p victory-gpu --libat head: 231 passed, 2 ignored, 2 failed. With--features diagnostics: 246 passed, 2 failed. The two failures aredynamic_slots_are_held_until_releasedandlists_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, includingpartial_refresh_under_marked_range_updates_saved_bytes.opened(page) == beforecomparison in the handler replaced bytrue,saved_bytes_are_the_page_as_taken_under_concurrent_faultsfails 10/10 release runs (page 9 saved other bytes than taken). The test does catch the race the counter guards against.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 warningsis clean, with and without--features diagnostics.63bcca4is 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):writingp99 usAt 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)
would_savekeepsc.0locked while it takesc.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_splitandTracked::takenuse the same order (guards ->c.0->Changed::taken'sc.1). The other paths (save,arm,unarm,disarm,saved,refreshed) take onlyc.1, and none takes the guard lock orc.0while holding it. I found no inversion.open()(watch.rs:480) is the only place that removes fromprotected, and it is the onlyPAGE_READWRITEcall.Tracked::drop,writingand its drop,title_memory_remapped,title_memory_aliasedand the handler all reach it throughopen. Every way a page stops being guarded therefore bumpsOPENED. Both the bump and the loads happen under the guard lock, soRelaxedis 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 onewould_savematched) is still correct.refreshedrunning 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()readsholdersagain, 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).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).
Imported from Marvisak/VIctory. Originally posted by fuzeofficlal on 2026-11-26T05:21:17Z.
Review: APPROVED
Static review of
9e0eaa81(crates/victory-gpu/src/watch.rs).The lock-splitting design looks sound:
opened = OPENED.load(Acquire)before droppingGUARDSand recheckingg.protected.contains(&page)+OPENEDafter reading the page (while keeping the page read-only duringread_into) prevents ABA across reopens, aliases, and remaps —open()bumpsOPENEDunderGUARDSbeforeVirtualProtectrestores write access, so any concurrent unprotect/write forces a retry or sees the page already open.holderswith an armed tracker trigger a save, andsavedis populated after re-acquiringGUARDSonly if the page stayed protected.Two minor non-blocking notes:
Changed::would_save,let saved = ...shadows the earlierMutexGuardrather than explicitly droppingself.0before lockingself.1(the lock orderchanged.0 -> changed.1is still consistent with the rest ofwatch.rs, so no deadlock, just slightly subtle).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.Imported from Marvisak/VIctory. Originally posted by Dukestar69 on 2026-11-26T06:48:16Z.
Review: APPROVED
Tested locally merged onto
origin/main(63bcca4) on Windows 11 x64:OPENEDgeneration 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).
Imported from Marvisak/VIctory. Originally posted by Marvisak on 2026-11-26T06:18:35Z.
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 itsOPENEDcount 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 fromprotectedand the onlyPAGE_READWRITEcall, 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 ofchangedpass&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 onmaintoo, 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:
checkpassing.Generated by Claude Code
Imported from Marvisak/VIctory. Originally posted by MeMako on 2026-11-26T06:28:55Z.
Verified
#3035(9e0eaa8) on Windows 11 (10.0.26200, Ryzen 9 7950X, RX 9070 XT, driver32.0.32029.2010, 32 GB RAM).Tests
cargo clippy -p victory-gpu --all-targets --locked -- -D warnings: clean.victory-gpu: 272/272 passed (includingsaved_bytes_are_the_page_as_taken_under_concurrent_faultsandconcurrent_writes_and_takes_lose_no_write, with 0 lost writes in the stress tests).Live Title Verification (RX 9070 XT)
main63bcca4+#2051+#2472+#2918+#1010+#2130with VRAM upload flags off +#3055+#2914), adding#2985+#2849+#3035together in the same live run (n=54world frames /n=38heavy frames vs.n=51/n=38baseline).6,186draws vs.5,290draws 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)copy_back: 99.2 → 75.5 ms (-23.7 ms / -23.9%)watch.rstimers reflect#3035and#2849combined;#2985affects texture detile/upload separately.)#2985+#2849+#3035together): steady-tail frame time dropped 453.3 → 423.6 ms (2.20 → 2.40 fps), even with +17% more draws.Merge Note with
#2849୦#2849(batchedopen_range), placing#3035'sopened(page).fetch_add(1, Ordering::Relaxed)insideopen_range'sif g.protected.remove(&page)loop keeps every page open counted underGUARDS.#2918,#3035's new testsaved_bytes_are_the_page_as_taken_under_concurrent_faultsjust adaptst.saved(page)toFinished::Saved(bytes) = t.finish(page).Hardware runs were performed by me on my 7950X / RX 9070 XT; comment drafted with Antigravity.
Imported from Marvisak/VIctory. Originally posted by KainanP on 2026-11-27T12:40:26Z.
Contention numbers for this PR from a shared benchmark (for #3425).
Method. The benchmark
guard_contentionand the checkrefreshes_under_writes_lose_nothingfrom #3516, split out as a standalone test-only commit (KainanP/VIctoryperf/guard-bench: no behaviour change,guards()only times a lock it finds taken in test builds), applied unchanged to this PR's head (9e0eaa8) and tomain(63bcca4). 256 MB write-watched pool in 64 KiB pages, copies of 32 pages, 1,400 pages dirtied before each refresh, title threads writing a random word every 20 µs while the copies are taken and copied. Release builds, i7-14650HX (24 threads), Windows 11. 31 rounds, builds interleaved and rotated each round, each run = median of 5 refreshes after a warm-up; table = medians over the 31 runs, plus the median (and quartiles) of the per-round PR/main ratio. Foreign load: other agents'rustcjobs were running (≈8 % of the CPU in a spot sample); the paired ratio is what to read.GUARDS, msReading. The one PR here that moves the contention, and only where pages are saved: with the copies armed, the writers' wait for
GUARDSdrops to 0.55× ofmain(quartiles 0.51–0.60), their time in writes to 0.75×, and the refresh's own wait from 8.7 ms to 0.05 ms. Unarmed, nothing changes (0.96–1.07, within noise; thewould_savelook is cheap). The twin-view run reads 1.07× for both but with quartiles 0.95–1.21, so I wouldn't call it a regression without more runs.Correctness.
refreshes_under_writes_lose_nothingpasses on this head (3 × 1,000 rounds), as do the existingwatch::tests including yours.AI use: Claude Code (Claude Opus 5.5).
Imported from Marvisak/VIctory. Originally posted by neonbyte1 on 2026-11-27T13:57:42Z.
Tested in game on an RTX 5090 (driver 620.73.04), Linux, GE-Proton11-14 Wine with its vkd3d-proton, GTA VI's opening prison yard, warm caches. Base:
mainplus the unmerged PRs this setup needs (listed in #3425), including copy-back in page runs under one lease; this PR merged on top (head9e0eaa81). 420 s runs, medians of the last 30 frame-rate lines, candidate and control adjacent.One pair so far, but frame, fastest block and the handler counter move together, which matches what the PR changes. @KainanP's contention bench in #3425 found the same: this is the one open PR that shortens the writers' wait when trackers are armed. No crash, no device removal. Pictures at frames 1700 and 2048 show the same scene and lighting as the control (mean luma 31.9 vs 31.5); the pixel differences are the camera framing and the hint timing at that frame number, not rendering.
One extra case on stacks that open guarded pages outside
open(). Our base opens a whole run of guarded pages with oneVirtualProtectand removes them fromprotecteddirectly (copy-back in runs). There, a fault's unlocked read can straddle a complete lease (pages opened, copy-back writes them, pages guarded again) and find the page guarded with an unchangedOPENEDcount, so it would keep stale bytes. On our tree the fix is to bumpOPENEDfor each page such a lease opens; that, plus the bumps at the four places that change a guarded page's bytes without opening it (writing, remaps, aliased writes, alias copy-backs), is commit3a2aa2fcon our branch. Onmainevery opening goes throughopen(), so this PR as it stands is fine there; it only matters for whichever lands second of this and a run-based copy-back.AI-assisted (Claude); measured on my machine, no game data shared.
Pull request closed