GPU: avoid heap allocations and batch unprotects in watch fault hot path #3343
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/3343"
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 danielibabet on 2026-11-26T19:19:30Z.
Summary
watch::changedfor single-page write faults without aliases (which covers nearly all vectored exception handler faults inon_write), skipping bothVecallocations andalias_of/protectedrange scans under the globalGUARDSmutex.alias_ofiteration inwatch::aliaseswhenalias_ofis empty, and skipalias_ofrange collection inwatch::changedwhenalias_ofis empty.watch::open_guardedinto singleVirtualProtect(..., 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 outcargo clippy --workspace --all-targets --all-features --locked -- -D warnings: 0 warningscargo run -p xtask --locked -- policy:asset policy: 191 files okImported from Marvisak/VIctory. Originally posted by Dukestar69 on 2026-11-26T19:28:22Z.
Review: COMMENTED
Tested on Windows against
origin/main(63bcca4).cargo test -p victory-gpu --lib watch:: -- --test-threads=1(15/15),clippy, andxtask policypass, but there is a bug in the batchedopen_guardedpath:open_guarded(crates/victory-gpu/src/watch.rs), the batchedVirtualProtect((start * PAGE) as *const _, (end - start) * PAGE, PAGE_READWRITE, &mut old)ignores its return value after removing all pages instart..endfromg.protected.VirtualProtectfails atomically (0) if[start, end)spans two separateVirtualAlloc/MapViewOfFileallocations (differentAllocationBase) or includes a page that was unmapped. When that happens, none of the still-mapped pages in the run are restored toPAGE_READWRITE, yet they have already been removed fromg.protected, so the next write to any of them will trigger an unhandled access violation instead of being handled by the watch fault handler.protect_notingright above it, which checks theVirtualProtectreturn value and falls back to per-pageVirtualProtecton failure. CheckingVirtualProtect(...) == 0inopen_guardedand falling back to per-pageVirtualProtect(oropen) forstart..endfixes this cleanly.first + 1 == lastcan overflow iffirst == usize::MAX(e.g.first.checked_add(1) == Some(last)is safer).Synthetic tests only (no game files used). AI-assisted (Gemini 4 Neon).
Imported from Marvisak/VIctory. Originally posted by danielibabet on 2026-11-26T19:35:06Z.
Good catch @Dukestar69! Fixed both in
crates/victory-gpu/src/watch.rs:VirtualProtect(...) != 0inopen_guardedbefore removingstart..endfromg.protected, and fall back to per-pageopen(g, page)when the batched call fails (e.g. across allocation boundaries or unmapped pages).first.checked_add(1) == Some(last)inchangedandopen_guardedto avoidusize::MAXoverflow.Re-ran
victory-gputests (229 passed, 0 failed; 2 skipped), strict clippy (--all-targets --all-features -- -D warnings), andxtask policy(191 files ok).Imported from Marvisak/VIctory. Originally posted by fuzeofficlal on 2026-11-26T20:24:30Z.
Review: APPROVED
Verified locally merged onto
origin/main(63bcca43) at PR head65d26e3c(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 underGUARDSwhile preservingmark_changed->openordering and return semantics;first.checked_add(1) == Some(last)preventsusize::MAXoverflow.open_guarded(L746-L787): batches contiguous guarded runs into singleVirtualProtect(..., PAGE_READWRITE)calls, checks!= 0before removingstart..endfromg.protected, and falls back to per-pageopen(g, page)when a batched call fails (e.g. across allocation boundaries or decommitted pages).aliases(L290-L293) andchanged(L724-L728): skipalias_oftraversal 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.MEM_DECOMMIT) of a 6-page guarded run beforewriting(p, 6 * PAGE), triggering the batchedVirtualProtectfailure path and confirming per-pageopenremoved all 6 entries fromg.protectedand restoredPAGE_READWRITEon all 5 remaining pages without faulting on subsequent writes.[0, 1]and[4, 5]),usize::MAXboundary 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).#3341(both touchwatch.rs): 0 clippy warnings and 26/26watch::+shadow::tests passing.Synthetic tests only; looks ready to merge.
Imported from Marvisak/VIctory. Originally posted by neonbyte1 on 2026-11-27T07:05:48Z.
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
mainplus 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).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.
Imported from Marvisak/VIctory. Originally posted by KainanP on 2026-11-27T12:40:22Z.
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 (65d26e3) 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. With 4 writers the writers' time in their writes and their wait for
GUARDScome out about 5 % lower thanmain(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 inchanged()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 callsVirtualProtectunder the lock, and behind a take's protect.Correctness.
refreshes_under_writes_lose_nothingpasses on this head (3 × 1,000 rounds), as do the existingwatch::tests.AI use: Claude Code (Claude Opus 5.5).
Imported from Marvisak/VIctory. Originally posted by upipibi on 2026-11-27T22:37:56Z.
Local benchmark of the fault fast path,
65d26e3cagainstmain63bcca4(both base63bcca4). It is an ignored test inwatch::tests, not proposed: 1, 4, 8 and 16 threads write one byte per 4 KiB into freshly takenpool(64)memory, so each first write per block faults throughon_write(64 pages, 40 rounds each, release, Windows 11, Ryzen 9 5950X). 3 alternating runs, µs a round:mainSo 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).
Imported from Marvisak/VIctory. Originally posted by pickles976 on 2026-11-28T06:11:14Z.
Offscreen verification on Linux/Wine 11, RTX 4060 Laptop / 16 GiB RAM:
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/).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_notingcost. 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_notingis 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.
View command line instructions
Checkout
From your project repository, check out a new branch and test the changes.Merge
Merge the changes and update on Forgejo.Warning: The "Autodetect manual merge" setting is not enabled for this repository, you will have to mark this pull request as manually merged afterwards.