Skip to content

GPU: batch watch GUARDS locks, VirtualProtect runs, and shadow copy-back - #2169

Open
RVZO6 wants to merge 2 commits into
Marvisak:mainfrom
RVZO6:rvzo/watch-batch
Open

RVZO6 wants to merge 2 commits into
Marvisak:mainfrom
RVZO6:rvzo/watch-batch

Conversation

@RVZO6

@RVZO6 RVZO6 commented Nov 25, 2026

Copy link
Copy Markdown

On CPU-heavy frames and physical/tiled memory mappings, write-watch maintenance and marked-page copy-back incur avoidable global lock churn, per-page VirtualProtect syscalls, and per-page 64 KiB scratch allocations:

  1. xmem::map calls title_memory_aliased in a loop per 64 KiB page — locking global GUARDS even when shown is empty (the common unaliased case) and calling protect(&mut g, &[page]) one page at a time.
  2. Tracked::drop, changed, and changed_here call VirtualProtect(..., PAGE, PAGE_READWRITE, ...) one page at a time instead of coalescing contiguous runs.
  3. Shadow::copy_back_marked acquires Tracked's mutexes three times per page (unarm, saved, changed), allocates a fresh vec![0u8; n] (up to 64 KiB) per page, and locks GUARDS + calls VirtualProtect per page via t.taken(&[page / PAGE]).

The change

  • crates/victory-gpu/src/watch.rs & crates/victory-gpu/src/lib.rs:
    • Add title_memory_aliased_batch (with zero-lock early return when no entry has aliases; title_memory_aliased delegates when !others.is_empty()), linking aliases under one GUARDS lock and calling protect(&mut g, &to_protect) once (sorting & deduping in protect).
    • Replace per-page open() with open_runs(), coalescing consecutive pages into one VirtualProtect(PAGE_READWRITE) per run with per-page fallback across unmapped holes or distinct reservations.
    • Unify Changed's two mutexes into one Mutex<ChangedState>, adding Tracked::begin_copy_back(page) (single lock for disarm + take saved bytes + changed check) and Changed::mark(page, save).
  • crates/victory-hle/src/modules/xmem.rs: call title_memory_aliased_batch once per map() instead of per page.
  • crates/victory-gpu/src/shadow.rs & crates/victory-gpu/src/memory.rs:
    • Reuse a caller-owned 64 KiB scratch buffer (page_scratch) across copy_back_marks and memory::bind's copy_back_page loop.
    • Batch t.taken(&batch) per contiguous Shadow run in copy_back_marks, queuing only written or previously opened pages so unchanged guarded pages keep their guard and never clear a concurrent CPU write arriving after begin_copy_back.
  • Add 3 Windows VEH / VirtualProtect / twin-section tests: watch::tests::title_memory_aliased_empty_and_batch_propagate_faults, watch::tests::open_runs_coalesces_and_falls_back_across_unmapped_holes, and shadow::tests::batched_copy_back_reuses_scratch_batches_taken_and_rearms.

Not a duplicate of

  • #2147 changes Saved::armed from a BTreeSet<usize> to page runs (Tracked::arm/unarm); it does not batch title_memory_aliased, coalesce VirtualProtect in open_runs, unify begin_copy_back, reuse copy-back scratch buffers, or batch Tracked::taken. If #2147 merges first, this rebases cleanly onto its armed runs representation.
  • #2136 skips requesting unchanged host copies at submission and is orthogonal to marked-page copy-back and watch batching.

Tested

  • Official windows-latest MSVC + Windows WARP SM 6.6 CI on fork integration stack (Run 45562558052):
    • cargo clippy --workspace --all-targets --locked -- -D warnings: clean.
    • cargo clippy --workspace --all-targets --all-features --locked -- -D warnings: clean.
    • cargo test --workspace --locked: 712 passed, 0 failed, 10 ignored, including victory-gpu 152 passed, 0 failed, 2 ignored, victory-hle 143 passed, 0 failed (all 10 modules::xmem::tests::*), and xtask (6 passed, 0 failed, repository_passes_policy).
  • Standalone branch c5a9547: cargo clippy (default & --all-features) -D warnings clean; Wine-10.0 passed watch/shadow (13 passed, 0 failed) and xmem (10 passed, 0 failed).

Not run: the title; any hardware GPU (CI ran on Windows WARP only). The title was not used in these tests.

AI-assisted: T3 Code (Antigravity, gemini-4-neon)

Batch title_memory_aliased across xmem::map with an early return when unaliased, coalesce VirtualProtect(PAGE_READWRITE) runs in open_runs with per-page fallback across unmapped holes, unify Tracked's changed/saved state into one lock via begin_copy_back, reuse a caller-owned 64 KiB scratch buffer across copy_back_marks/copy_back_page, and batch Tracked::taken per contiguous Shadow run.

Assisted-by: T3 Code (Antigravity, gemini-4-neon)

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

Verified locally merged onto origin/main (940d32f, Windows 11 x64, Rust 1.98.1 MSVC):

  • cargo test -p victory-gpu --lib watch:: — 8 passed, 0 failed
  • cargo clippy -p victory-gpu -p victory-hle --all-targets — 0 warnings
  • cargo xtask policy — ok (183 files ok)

Clean batching of watch GUARDS locks, VirtualProtect runs, and shadow copy-back. Looks great.

AI-assisted (Gemini 4 Neon).

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

Static review only: victory-gpu is Windows-only (D3D12/windows_sys) — nothing compiles or runs on macOS; source review of the diff.

Watch GUARDS locks batched, VirtualProtect runs, shadow... — WPM batching; relates to #2147's page-run arming and #1865's dirty-bitmaps.

RecompLive pushed a commit to RecompLive/victory-fork that referenced this pull request Nov 25, 2026
…tory #2169)

Port of Marvisak/VIctory#2169 by RVZO6 (GPL-3.0-or-later), adapted to our
tree (armed runs from #2147, withheld ranges from #1998):

- watch.rs: one lock per tracker (`ChangedState`: changed pages, armed
  runs, saved bytes) so a copy-back disarms, takes saved bytes and checks
  the page once; `title_memory_aliased_batch` links a whole map() under
  one GUARDS lock with a zero-lock early return; `open_runs` coalesces
  VirtualProtect(PAGE_READWRITE) per contiguous run, falling back per page;
  `Tracked::taken` sorts and dedups its pages.
- xmem.rs: one batched `title_memory_aliased_batch` per `map()`, not one
  call per page.
- shadow.rs: one 64 KiB scratch buffer reused across copy-back loops, and
  `taken` queued per contiguous Shadow run instead of per page; unchanged
  guarded pages are left alone so a racing title write is not cleared.
- New tests: batched aliasing fault propagation, open_runs across
  unmapped holes, and batched copy-back (scratch reuse, racing write).

Assisted-by: T3 Code (Antigravity, gemini-4-neon)
@nathanbzrr

Copy link
Copy Markdown
Contributor

Audited head c5a95470f95e158354f3304eb36f68d3034b9dd5 on main (940d32f69b) on Windows 11 x64 / AMD Radeon RX 7600.

Baseline tests pass (watch::tests 8/8, shadow::tests 5/5), but empirical repros confirm a silent CPU data-loss regression and a broken public alias API:

  1. Live Repro — Deferred t.taken(&batch) loses concurrent CPU writes (shadow.rs:480-484, 770-802):
    In Shadow::copy_back_marked_page, after copying GPU bytes back to page P0, _writing drops immediately (leaving P0 as PAGE_READWRITE) while P0 / PAGE is only queued into batch. While copy_back_marks processes remaining pages P1..PN of that Shadow copy, any concurrent CPU write to P0 succeeds without faulting, and the final t.taken(&batch) removes P0 from changed.pages (watch.rs:428) and sets PAGE_READONLY.
    Repro across a 64-page pool (repro_batched_taken_loses_concurrent_cpu_write_on_written_page):

    REPRO #2169 Finding 3.1: title[100]=0x77, host[100]=0x0, t.changed(p0)=false
    (The CPU write 0x77 is invisible to future Shadow::update refreshes.)

  2. Live Repro — pub fn title_memory_aliased_batch misses chained aliases (watch.rs:545-583):
    Because protect(&mut g, &to_protect) is deferred until after the loop, chained pairs like title_memory_aliased_batch([(a, &[b][..]), (c, &[a][..])]) (where b is protected) check g.protected.contains(&a) == false and skip protecting c:

    REPRO #2169 Finding 3.2: writable(a)=false, writable(c)=true

  3. Source-level — Widened pre-write snapshot race & VEH allocation (watch.rs:498-501):
    When save == true (inside VEH on_write / writing), changed() calls open_runs(g, &others) before looping over others to snapshot pre-write bytes (c.mark(page, true)), widening the window where another thread writing through an alias corrupts Saved.bytes (and allocating to_open inside VEH whenever others.len() >= 2).

(Proposed / uncompiled fix direction:) re-guard each written page immediately in one GUARDS lock at _writing end (finish_writing), leave previously opened unchanged pages in changed.pages, propagate protections across chained aliases via worklist/BFS in title_memory_aliased_batch, and snapshot armed holders before open_runs when save == true.

AI-assisted; synthetic tests only, no game files, dumps, or captures used.

@MamaLeVrai

Copy link
Copy Markdown

Test report on real hardware: AMD RX 6950 XT (RDNA2), Windows 11, Rust 1.98.1, with a GPU present, so the hardware-only shader checks run. I merged this PR's head c5a95470 into main 940d32f in a throwaway tree (no conflict). cargo clippy --workspace --all-targets --locked -- -D warnings: clean; the same with --all-features: clean. cargo test --workspace --locked: 704 passed, 0 failed, 10 ignored, two runs (main alone on the same machine: 701 passed, 0 failed, 10 ignored). The title was not run, so this says nothing about in-game effect. No game data.

AI-assisted (Claude Code); no game data.

…and snapshot before opening

Addresses all three review findings on Marvisak#2169:
- Replace deferred t.taken(&batch) in Shadow::copy_back_marks with Writing::finish_taken, which removes the busy range, notifies other holders/aliases, re-guards the written full page and its aliases, and clears it from tracked.changed under one GUARDS lock immediately after write_mapped (also used in copy_back_page). Previously opened unchanged pages stay in changed.pages so concurrent CPU writes are never lost.
- Propagate read-only guards transitively across chained aliases in title_memory_aliased_batch via a worklist over g.alias_of (handling both forward and reverse chains in one GUARDS lock).
- In watch::changed, mark/snapshot armed holders before removing read-only guards on [first, last) or aliases, and use a 16-entry stack buffer in open_runs, open_range, and changed to avoid heap allocation on the VEH fault path.
- Add regression tests covering concurrent CPU writes immediately after page 0 copy-back, unchanged previously-opened pages, and forward/reverse chained aliases in title_memory_aliased_batch.

Assisted-by: T3 Code (Antigravity, gemini-4-neon)
RVZO6 added a commit to RVZO6/VIctory that referenced this pull request Nov 25, 2026
…and snapshot before opening

Addresses all three review findings on Marvisak#2169:
- Replace deferred t.taken(&batch) in Shadow::copy_back_marks with Writing::finish_taken, which removes the busy range, notifies other holders/aliases, re-guards the written full page and its aliases, and clears it from tracked.changed under one GUARDS lock immediately after write_mapped (also used in copy_back_page). Previously opened unchanged pages stay in changed.pages so concurrent CPU writes are never lost.
- Propagate read-only guards transitively across chained aliases in title_memory_aliased_batch via a worklist over g.alias_of (handling both forward and reverse chains in one GUARDS lock).
- In watch::changed, mark/snapshot armed holders before removing read-only guards on [first, last) or aliases, and use a 16-entry stack buffer in open_runs, open_range, and changed to avoid heap allocation on the VEH fault path.
- Add regression tests covering concurrent CPU writes immediately after page 0 copy-back, unchanged previously-opened pages, and forward/reverse chained aliases in title_memory_aliased_batch.

Assisted-by: T3 Code (Antigravity, gemini-4-neon)
@RVZO6

RVZO6 commented Nov 25, 2026

Copy link
Copy Markdown
Author

Thanks @nathanbzrr for the thorough RX 7600 repros — all three findings are fixed in 8b8b076:

  1. Immediate atomic re-guarding on written pages (watch.rs, shadow.rs):
    • Replaced deferred t.taken(&batch) in Shadow::copy_back_marks with Writing::finish_taken, which removes the busy range, notifies other holders/aliases, re-guards the written full page and its aliases, and clears it from tracked.changed under one GUARDS lock immediately after write_mapped (also used in copy_back_page).
    • Previously opened unchanged pages (saved.is_some() && written.is_none()) remain in changed.pages so concurrent CPU writes after read_into are never lost.
  2. Chained aliases in title_memory_aliased_batch (watch.rs):
    • Propagates read-only guards transitively across chained aliases via a worklist over g.alias_of (covering both forward [(a, &[b]), (c, &[a])] and reverse [(c, &[a]), (a, &[b])] chains in one GUARDS lock).
  3. Snapshot-before-open and zero-alloc VEH fast path (watch.rs):
    • watch::changed now marks/snapshots armed holders before removing read-only guards on [first, last) or aliases, and open_runs, open_range, and changed use a 16-entry stack buffer to avoid heap allocation on the VEH fault path.
  4. Regression tests: Updated shadow::tests::batched_copy_back_reuses_scratch_batches_taken_and_rearms to assert a concurrent CPU write immediately after page 0 copy-back faults and stays marked changed, and added watch::tests::title_memory_aliased_batch_propagates_chained_aliases.

Verified on fork windows-latest MSVC + Windows WARP SM 6.6 CI (Run 45581807630): both clippy -D warnings builds clean, 716 passed; 0 failed; 10 ignored, xtask 6/6.

AI-assisted: T3 Code (Antigravity, gemini-4-neon)

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