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

@upipibi

upipibi commented Nov 27, 2026

Copy link
Copy Markdown

Local benchmark of the fault fast path, 65d26e3c against main 63bcca4 (both base 63bcca4). It is an ignored test in watch::tests, not proposed: 1, 4, 8 and 16 threads write one byte per 4 KiB into freshly taken pool(64) memory, so each first write per block faults through on_write (64 pages, 40 rounds each, release, Windows 11, Ryzen 9 5950X). 3 alternating runs, µs a round:

threads main this PR
1 781 / 805 / 795 796 / 810 / 790
4 426 / 430 / 434 423 / 425 / 419
8 563 / 585 / 609 558 / 542 / 530
16 777 / 751 / 784 759 / 740 / 715

So the gain is small and shows up only under contention: about 5-8 % at 8 threads and 3-6 % at 16, nothing measurable with 1-4. That fits what the PR changes: each fault's cost is mostly the kernel's exception dispatch, and this trims the user-side work done under GUARDS, not the time spent waiting for it. For the 52 ms a frame of fault-handler queueing in #3425's budget, taking the lock shared in the fault path (the fork's port 6, see #3455) is the larger lever. This PR's allocation and alias-scan cuts would still apply on top of it.

AI-assisted (Claude Code, Claude Opus 5.5 wrote and ran the local benchmark).

@pickles976

pickles976 commented Nov 28, 2026 •

Copy link
Copy Markdown

Offscreen verification on Linux/Wine 11, RTX 4060 Laptop / 16 GiB RAM:

  • Exact production 65d26e3cf08c545c627f0071fcd56518f795654e, with only a test-only decommitted-middle-page fallback fixture: 16/16 tracking tests passed, fresh 9.00 s build, 0.01 s tests (verify-watch-batch-owner-20261128T054357Z/).
  • Ported into our dirty, heavily mixed runtime (base 3ed7d725), preserving existing alias/snapshot/GPU-write-notification tracking: 17/17 passed, fresh 11.04 s build, 0.68 s tests (verify-mixed-watch-batching-20261128T060114Z/). This is not an exact-head or matched-parent result.

The tests cover armed before-images, alias writes, retakes, foreign/unmapped pages, overflow and failed range-opening fallback. The integrated suite initializes the physical NVIDIA device, but these are Win32 tracking/byte-consistency checks, not GPU shader execution or a measured frame-rate gain.

Why we selected it: our actual rendering profile has substantial protection/VEH cost (14 late copy-stat reports: medians 852.6 ms protecting, 762.5 ms in VEH, 107.3 ms moving bytes; nested/cross-thread timers overlap and must not be summed). Your change targets opening/handler overhead, not all read-only protect_noting cost. A changed-stack title comparison is still pending behind shader-integration validation. No safety limits changed and no assets/images uploaded.

28 Nov follow-through: the changed mixed stack rendered palms/buildings/lights, but no matched title speedup is established. Fifteen late reports still show median 822.7 ms watches, 887.5 ms page protection and 447.3 ms fault handling versus 133.2 ms moving bytes; these overlap and reflect different workload/caches from the earlier profile. protect_noting is not changed by the local #3343 port. A read-only review found no mark-before-open, alias or protected-run ordering defect; that is not complete certification.

The trial then hit NVIDIA Xid109/CTX SWITCH TIMEOUT in a 25-list submission, followed by the title watchdog. This is not attributed to #3343; per-command/checkpoint traces were disabled. Title/GPU runs are parked. Full chronology, hardware/provenance, performance and limitations are in the updated progress report. No resource threshold was raised or shader work bypassed.

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.

7 participants