Skip to content

GPU: avoid heap allocations and batch unprotects in watch fault hot path - #3343

Open
danielibabet wants to merge 2 commits into
Marvisak:mainfrom
danielibabet:pr/watch-zero-alloc-faults
Open

danielibabet wants to merge 2 commits into
Marvisak:mainfrom
danielibabet:pr/watch-zero-alloc-faults

Conversation

@danielibabet

Copy link
Copy Markdown

Summary

  • Add a zero-allocation fast path in watch::changed for single-page write faults without aliases (which covers nearly all vectored exception handler faults in on_write), skipping both Vec allocations and alias_of / protected range scans under the global GUARDS mutex.
  • Skip alias_of iteration in watch::aliases when alias_of is empty, and skip alias_of range collection in watch::changed when alias_of is empty.
  • Batch contiguous guarded pages in watch::open_guarded into single VirtualProtect(..., PAGE_READWRITE) calls instead of one syscall per page, with a single-page fast path.

Verification

  • cargo test -p victory-gpu --locked -- --test-threads=1 --skip dynamic_slots_are_held_until_released --skip lists_share_a_table_and_copies_keep_their_views: 229 passed; 0 failed; 1 ignored; 2 filtered out
  • cargo clippy --workspace --all-targets --all-features --locked -- -D warnings: 0 warnings
  • cargo run -p xtask --locked -- policy: asset policy: 191 files ok

@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 on Windows against origin/main (63bcca4). cargo test -p victory-gpu --lib watch:: -- --test-threads=1 (15/15), clippy, and xtask policy pass, but there is a bug in the batched open_guarded path:

  • In open_guarded (crates/victory-gpu/src/watch.rs), the batched VirtualProtect((start * PAGE) as *const _, (end - start) * PAGE, PAGE_READWRITE, &mut old) ignores its return value after removing all pages in start..end from g.protected.
  • On Windows, VirtualProtect fails atomically (0) if [start, end) spans two separate VirtualAlloc / MapViewOfFile allocations (different AllocationBase) or includes a page that was unmapped. When that happens, none of the still-mapped pages in the run are restored to PAGE_READWRITE, yet they have already been removed from g.protected, so the next write to any of them will trigger an unhandled access violation instead of being handled by the watch fault handler.
  • Compare protect_noting right above it, which checks the VirtualProtect return value and falls back to per-page VirtualProtect on failure. Checking VirtualProtect(...) == 0 in open_guarded and falling back to per-page VirtualProtect (or open) for start..end fixes this cleanly.
  • Minor: first + 1 == last can overflow if first == usize::MAX (e.g. first.checked_add(1) == Some(last) is safer).

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

@danielibabet

Copy link
Copy Markdown
Author

Good catch @Dukestar69! Fixed both in crates/victory-gpu/src/watch.rs:

  • Check VirtualProtect(...) != 0 in open_guarded before removing start..end from g.protected, and fall back to per-page open(g, page) when the batched call fails (e.g. across allocation boundaries or unmapped pages).
  • Use first.checked_add(1) == Some(last) in changed and open_guarded to avoid usize::MAX overflow.

Re-ran victory-gpu tests (229 passed, 0 failed; 2 skipped), strict clippy (--all-targets --all-features -- -D warnings), and xtask policy (191 files ok).

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

Verified locally merged onto origin/main (63bcca43) at PR head 65d26e3c (Windows 11 x64, Ryzen 9 9950X, NVIDIA RTX 5090 + Microsoft WARP, VICTORY_D3D12_DEBUG=1):

  • crates/victory-gpu/src/watch.rs:
    • changed (L717-L722): single-page non-aliased fault fast path avoids heap allocations and range scans under GUARDS while preserving mark_changed -> open ordering and return semantics; first.checked_add(1) == Some(last) prevents usize::MAX overflow.
    • open_guarded (L746-L787): batches contiguous guarded runs into single VirtualProtect(..., PAGE_READWRITE) calls, checks != 0 before removing start..end from g.protected, and falls back to per-page open(g, page) when a batched call fails (e.g. across allocation boundaries or decommitted pages).
    • aliases (L290-L293) and changed (L724-L728): skip alias_of traversal when empty.
  • cargo xtask policy: 191 files ok.
  • cargo clippy --locked -p victory-gpu --all-targets -- -D warnings (default and --all-features): 0 warnings.
  • cargo test --locked -p victory-gpu --features diagnostics --lib -- watch::: 15/15 passed on both RTX 5090 and WARP.
  • Extra adversarial synthetic probe (not committed):
    • Decommitted the middle page (MEM_DECOMMIT) of a 6-page guarded run before writing(p, 6 * PAGE), triggering the batched VirtualProtect failure path and confirming per-page open removed all 6 entries from g.protected and restored PAGE_READWRITE on all 5 remaining pages without faulting on subsequent writes.
    • Verified non-contiguous runs ([0, 1] and [4, 5]), usize::MAX boundary calls, and an 8-thread concurrent write-fault stress test across 64 guarded pages x 20 rounds (1,280 faults in 8.67 ms, 100% captured).
  • Also verified a clean co-merge with #3341 (both touch watch.rs): 0 clippy warnings and 26/26 watch:: + shadow:: tests passing.

Synthetic tests only; looks ready to merge.

@neonbyte1

Copy link
Copy Markdown

Measured 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 cache; base is main plus the unmerged PRs this setup needs (#3312, #3318, #2472 and others, listed in #3425). This PR merged on top, 600 s runs, medians of the last 30 frame-rate lines, against a control run of the same base taken next to it (frame times drift by up to ~25 ms between runs hours apart).

Frame Preparing Copy-back
control 402 ms 81 ms 53 ms
+ this PR 402 ms 82 ms 51.7 ms
+ this PR + #3289 404 ms 75.5 ms 51.9 ms (second control: 400 / 78 / 52)

About 1 ms off copy-back, within noise otherwise. For context, our counters put the copy-back of marked pages at ~51 ms/frame here, of which page writes and guard lease/protect rounds are ~94% of the thread time (2,829 lease rounds per frame) and the title reads ~3.5%; the single-page fast path doesn't reach the multi-page runs that dominate in this scene.

AI-assisted (Claude); measured on my machine, no game data shared.

@KainanP

KainanP commented Nov 27, 2026

Copy link
Copy Markdown

Contention numbers for this PR from a shared benchmark (for #3425).

Method. The benchmark guard_contention and the check refreshes_under_writes_lose_nothing from #3516, split out as a standalone test-only commit (KainanP/VIctory perf/guard-bench: no behaviour change, guards() only times a lock it finds taken in test builds), applied unchanged to this PR's head (65d26e3) and to main (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' rustc jobs were running (≈8 % of the CPU in a spot sample); the paired ratio is what to read.

Config Refresh ms (main → PR) Writers in their writes, ms Writers waiting for GUARDS, ms PR/main, writes PR/main, wait
1 writer 17.4 → 17.8 5.1 → 5.6 2.8 → 3.1 1.01 (0.89–1.24) 1.03 (0.91–1.25)
4 writers 29.1 → 30.0 37.8 → 35.1 24.3 → 22.6 0.95 (0.91–0.99) 0.95 (0.92–0.99)
4 writers, refresh on 4 threads 9.2 → 8.8 28.3 → 27.1 25.7 → 24.8 0.96 (0.93–1.04) 0.97 (0.93–1.05)
4 writers, twin views (aliased) 30.2 → 32.0 56.4 → 56.3 40.1 → 39.0 1.00 (0.93–1.11) 1.00 (0.92–1.10)
4 writers, copies armed (first writes save the page) 43.2 → 42.4 145.3 → 140.4 119.4 → 114.8 0.96 (0.93–1.03) 0.96 (0.93–1.03)

Reading. With 4 writers the writers' time in their writes and their wait for GUARDS come out about 5 % lower than main (quartiles 0.91–0.99), in the other configs within noise. That fits what the bench exercises: every fault here is a single-page write, so of this PR only the single-page fast path in changed() applies (the small gain is plausibly that); the multi-page runs it batches (writing() ranges) aren't in this workload. What's left of the wait is the writers queueing behind each other's fault handler, which still calls VirtualProtect under the lock, and behind a take's protect.

Correctness. refreshes_under_writes_lose_nothing passes on this head (3 × 1,000 rounds), as do the existing watch:: tests.

AI use: Claude Code (Claude Opus 5.5).

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.

5 participants