Skip to content

watch: move guard/alias VirtualProtect outside GUARDS mutex and batch Bits/publish - #3760

Open
ScymicX wants to merge 2 commits into
trustno1-coder:mainfrom
ScymicX:perf/watch-unlocked-protect-and-batch-bits
Open

ScymicX wants to merge 2 commits into
trustno1-coder:mainfrom
ScymicX:perf/watch-unlocked-protect-and-batch-bits

Conversation

@ScymicX

@ScymicX ScymicX commented Nov 30, 2026

Copy link
Copy Markdown

What it changes

guard() previously held the global GUARDS mutex across all VirtualProtect, elsewhere, uncommitted_end, and aliased-view protect_alias calls, stalling concurrent refresh worker threads and any locked write-fault path behind OS page-table walks. In addition, writes_with allocated a Vec<usize> and updated PUBLISHED page by page on every guarded refresh.

This PR moves both primary and aliased-view VirtualProtect calls outside GUARDS and batches Bits / PUBLISHED updates per 64-block word (enabled by default; VICTORY_WATCH_UNLOCKED_PROTECT=0 falls back to the existing guard + publish path):

  • Concurrency & lock ordering (PROTECT_GATE + PROTECTING):
    • Strict lock order: MAPPING -> Asking -> PROTECT_GATE -> GUARDS -> OPENED.
    • guard_with_pub / protect_unlocked hold PROTECT_GATE.read() while running elsewhere, uncommitted_end, and VirtualProtect outside GUARDS; mutators (title_memory_allocated, look_at_holes, writing, kernel_writing, title_memory_written, views_mapped, title_memory_splitting, title_memory_remapped, title_memory_unmapping, title_memory_freed, title_memory_made_real) take PROTECT_GATE.write().
    • soft_runs(...) is read under GUARDS before dropping the lock so concurrent title_memory_made_real cannot be missed.
    • PROTECTING marks in-flight primary and alias blocks before dropping GUARDS (with RAII ClearProtecting / ClearProtectingSlice guards). Fault handlers (on_write, opened_for_writing, came_back) spin briefly on wait_protecting, and open_unlocked returns false if PROTECTING is set so racing faults take the safe locked/settled path.
    • If a block is opened concurrently while GUARDS is released, restore_rw reverts its protection; for aliased blocks, pending_clean re-verifies all all_others (g.protected, g.aliased, !failed_aliases, !OPENING, !PROTECTING || alias_to_vp_set, !BESIDE, !unsettled) before marking a block clean.
  • Word-batched bitmaps & publish:
    • Bits::{ensure_piece, set_word, clear_word, set_all} and word-level Blocks::{insert_all, diff_into}.
    • Hoisted BESIDE/OPENING/TOLD/PROTECTING piece lookups and cached g.protected/g.clean/now_instant in guard_with_pub.
    • publish_pairs avoids the Vec<usize> allocation in writes_with and updates PUBLISHED per 64-block word, only called when guard_with_pub reports any_publishable.

How it was tested

  • GPU and profile: NVIDIA GeForce RTX 5070 Ti, Xbox Series X, 1440p, DLSS Balanced, frame generation off (v2026.11.28.01 baseline).
  • Before: With alias VirtualProtect running inside GUARDS, guard: GUARDS mutex wait summed across worker threads reached 18.51 ms/frame.
  • After: Moving primary and alias VirtualProtect outside GUARDS + batching Bits/publish_pairs reduced guard: GUARDS mutex wait to ~2.8 ms/frame.
  • cargo test passed for the crates it touches: yes
    • cargo test --locked -p victory-gpu --lib watch:: -- --test-threads=1: 65 passed, 0 failed.
    • cargo test --locked -p victory-gpu --lib watch::many_askers_tests: 10 passed, 0 failed (default ON) and 10 passed, 0 failed (VICTORY_WATCH_UNLOCKED_PROTECT=0).
    • Race stress test watch::many_askers_tests::no_write_to_resting_views_is_lost_between_askers: 30 consecutive runs, 0 failures (runs=30 fails=0).
    • cargo clippy -p victory-gpu --no-deps --all-targets --locked and --all-features: 0 warnings in touched/new code.
    • cargo xtask policy --staged: passed.

Checked for overlap

…atch Bits/publish

Reduce GUARDS mutex contention during concurrent refresh workers and
title write faults by moving VirtualProtect (both primary block runs and
aliased views) outside the GUARDS mutex, and batch Bits / PUBLISHED
updates per 64-block word (VICTORY_WATCH_UNLOCKED_PROTECT=0 disables).

- Add PROTECT_GATE (RwLock) and PROTECTING bitset (strict lock order:
  MAPPING -> Asking -> PROTECT_GATE -> GUARDS -> OPENED) so guard_with_pub
  / protect_unlocked run VirtualProtect, elsewhere, and uncommitted_end
  under shared read access while mutators (unmap/free/remap/split/open)
  take exclusive write access and fault handlers spin briefly on
  wait_protecting.
- Pre-mark PROTECTING/PROTECTED/g.protected before releasing GUARDS,
  protect primary runs via protect_unlocked, then protect aliased views
  outside GUARDS with RAII ClearProtectingSlice and full all_others
  re-verification before inserting into g.clean.
- Add word-batched Bits::{set_word, clear_word, set_all},
  Blocks::{insert_all, diff_into}, and publish_pairs to eliminate
  per-page PUBLISHED atomics and Vec allocations in writes_with.
@github-actions github-actions Bot added the pr-performance Pull request: makes it faster or use less memory label Nov 30, 2026
@github-actions github-actions Bot changed the title [pr-performance] watch: move guard/alias VirtualProtect outside GUARDS mutex and batch Bits/publish watch: move guard/alias VirtualProtect outside GUARDS mutex and batch Bits/publish Nov 30, 2026
@Yoruiopz

Yoruiopz commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

I reproduced an ownership regression on exact head 2789218. In open_unlocked, OPENING.swap_on returns true when another fault already owns the bit. The combined early-return branch then clears that other opener's bit. A guard or a third fault can observe the still-active opening as idle. This branch is shared by both VICTORY_WATCH_UNLOCKED_PROTECT settings.

The asset-free Windows fixture holds the first opener's claim on a real allocated block, exercises the competing fault entry, and checks that the first claim survives. It failed on the unmodified production logic and passed with this two-check correction. The correction leaves an existing claim alone and clears only a claim taken by the current caller when PROTECTING requires fallback.

All 66 watch tests passed with VICTORY_WATCH_UNLOCKED_PROTECT=1 and again with 0.

Preliminary in-game comparison

I built the exact PR head plus the small ownership correction as a single locked Windows diagnostics executable. Same RTX 5070 Laptop, copied porch checkpoint, warm cache, Series S with DLSS Ultra Performance and frame generation off. Only VICTORY_WATCH_UNLOCKED_PROTECT changed.

I used three corresponding host reports around 17–28 seconds after the world entered, with roughly 5,200 draws per frame in both modes. These numbers are medians of those reports.

Mode Rendered FPS CPU prepare Copy time Aggregate GUARDS wait across host threads
0 20.2 39.3 ms 22.0 ms 48.74 ms/frame
1 22.9 33.5 ms 16.1 ms 5.21 ms/frame

The enabled session lost Windows foreground shortly after two screenshots confirmed the expected porch pose, so the longer camera-qualified comparison and frame-time percentiles are incomplete. Both modes still show the separately tracked porch arm artifact. The aggregate lock time measures worker contention and is separate from wall-clock frame time.

Series X with 2x DLSS FG

I tested the corrected guard code on the same .05 base with the explicit 1080p startup fix and #3811, using one Windows diagnostics executable. Both processes used the same copied save, warmed cache, DLSS Performance (960×540 to 1920×1080), 2x DLSS frame generation, and the 15 rendered FPS cap. VICTORY_AB was clear. Only VICTORY_WATCH_UNLOCKED_PROTECT changed.

Foreground was polled for the duration. The enabled attempt lost focus after 15.46 seconds, so I compared an interior 14-second interval before that loss to the same world time in the disabled run. The initial screenshots matched the same porch pose. Both windows contain 210 rendered-frame intervals, with median draws 5,787 and 5,750. A later complete enabled window advanced to a much heavier scene and is excluded.

Measurement Disabled Enabled
Native cadence 15.0 FPS 15.0 FPS
Native frame p95 75.2 ms about 69.7 ms
Native frame p99 98.6 ms 98.4 ms
CPU preparation (host reports) 35.1 ms 33.1 ms
Aggregate GUARDS wait 60.7 ms/frame 12.8 ms/frame
DLSS plugin shown rate 30.0 FPS 29.6 FPS

The enabled p95 is 68.3–70.9 ms using either endpoint for the CSV clock alignment. The shown rate uses complete plugin reporting intervals, not individual display-frame timings. This supports lower guard contention in a second profile. The short matched window shows modest improvement at the cap and leaves steadiness under higher load unverified.

Protection protocol mode

The diagnostics toggle currently allows VICTORY_AB to switch which protection implementation and which publication path writes_with chooses. The legacy and unlocked implementations use the same protection bookkeeping, and the legacy path does not honor PROTECTING during an unlocked protection change. A live flip can therefore mix protocols across workers, or within one call if its two flag reads differ. The performance cases above explicitly clear VICTORY_AB and set the mode before each process.

I isolated the setting at first use in a follow-up commit. Default-on and exact =0 behavior stay the same. The regression launches fresh child processes with VICTORY_AB targeting this switch and checks unset, =0, and =1. The old selector failed the extracted regression. The integrated Windows regression and all 70 watch tests passed in both fresh switch modes after correction.

@ihyajb

ihyajb commented Nov 30, 2026

Copy link
Copy Markdown
Contributor

Whole-process stalls of 2.2–2.7 s with this PR (busy-wait in wait_protecting)

Tested this PR merged with ten other open PRs (#3733, #3850, #3832, #3848, #3750, #3753, #3705, #3694, #3762, #3726) on 41adb55, diagnostics build, Series S profile, DLSS + FG, 5-minute standing runs from one save.

  • With VICTORY_WATCH_UNLOCKED_PROTECT on (default): a single frame of 2.2–2.7 s every 2–4 minutes, in all 4 runs.
  • Same build, only VICTORY_WATCH_UNLOCKED_PROTECT=0: none (worst frame 163 ms).
  • Stock 41adb55 (3 runs): none (worst 499 ms).

A sampling profiler with per-round timestamps took 3–7 samples during each long frame instead of ~250, so its own thread was stalled too: the whole process stops, not one waiting thread.

Likely cause: wait_protecting (called from the write-fault handler on the title's threads) is a pure spin_loop(). When several title threads fault on a block in PROTECTING, they can occupy every core while the helper whose VirtualProtect clears the bit doesn't get scheduled, until Windows' starvation boost runs it. I didn't catch a stack inside a stall (the profiler couldn't sample), so this is inferred. But changing only this loop to spin briefly, then yield_now(), then sleep(200µs) removed the stalls in 2 runs (worst 153 / 142 ms), with no change in frame rate:

fn wait_protecting(block: usize) {
    let mut tries = 0u32;
    while PROTECTING.any(block, block + 1) {
        if tries < 256 {
            std::hint::spin_loop();
        } else if tries < 320 {
            std::thread::yield_now();
        } else {
            std::thread::sleep(std::time::Duration::from_micros(200));
        }
        tries = tries.saturating_add(1);
    }
}

cargo test -p victory-gpu --lib watch::: 66 passed. One or two runs per configuration, so the numbers are indicative rather than statistical.

Found with Claude Code.

…pin mode at startup

Address review findings on trustno1-coder#3760:
- Split open_unlocked's OPENING.swap_on(block) and PROTECTING.any(...)
  checks so a competing fault does not clear another opener's OPENING bit.
- Add spin/yield/sleep backoff to wait_protecting to prevent whole-process
  starvation stalls when multiple title threads fault on a PROTECTING block.
- Read VICTORY_WATCH_UNLOCKED_PROTECT once via OnceLock instead of
  toggled! so VICTORY_AB cannot mix legacy and unlocked protocols mid-run.
- Add regression test watch::tests::open_unlocked_preserves_existing_opening_claim.
@ScymicX

ScymicX commented Nov 30, 2026

Copy link
Copy Markdown
Author

Thank you @Yoruiopz and @ihyajb for catching those issues — all three fixes are now pushed in 8bdc117:

  1. open_unlocked OPENING ownership (@Yoruiopz): Split OPENING.swap_on(block) from PROTECTING.any(block, block + 1) so a competing fault returns false without clearing another opener's OPENING bit; only a caller that claimed OPENING itself clears it on PROTECTING fallback.
  2. wait_protecting backoff (@ihyajb): Replaced the pure spin_loop() with bounded spin (< 256) -> thread::yield_now() (< 320) -> thread::sleep(200µs) to avoid thread-starvation stalls when multiple title threads fault on a PROTECTING block.
  3. Process-start OnceLock (@Yoruiopz): unlocked_protect() now caches VICTORY_WATCH_UNLOCKED_PROTECT via OnceLock at first read instead of crate::toggled!, so VICTORY_AB cannot mix legacy and unlocked protocols mid-run.
  4. Regression test: Added watch::tests::open_unlocked_preserves_existing_opening_claim covering both the competing-claim preservation and the PROTECTING fallback clear.

Verified locally on 8bdc117:

  • cargo test --locked -p victory-gpu --lib watch:: -- --test-threads=1: 66 passed, 0 failed (default ON) and 66 passed, 0 failed (VICTORY_WATCH_UNLOCKED_PROTECT=0).
  • cargo test --locked -p victory-gpu --lib watch::many_askers_tests: 10 passed, 0 failed + 20 consecutive runs of no_write_to_resting_views_is_lost_between_askers (runs=20 fails=0).
  • cargo clippy -p victory-gpu --no-deps --all-targets --locked (+ --all-features): 0 warnings in touched/new code; cargo xtask policy --staged: passed.

FormulaChenZen added a commit to FormulaChenZen/VIctory-NVIDIA that referenced this pull request Nov 30, 2026
…ng paths

Wake only draws waiting for the affected pipeline and stop waiting when its compile is deferred. Publish placed-view shapes through immutable numbered slots. Handle adjacent soft copies of the same physical page under bounded remapping locks. Keep large gaps out of initial write-watch queries, retain full in-flight hazard checks, and publish the exact observed pages using word masks.

Based in part on upstream profiles and changes in VIctory-NVIDIA trustno1-coder#2188, trustno1-coder#2804, trustno1-coder#3760 and trustno1-coder#3850.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-performance Pull request: makes it faster or use less memory

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants