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

Closed
github-bot wants to merge 2 commits from gh-pr/2169/head into gh-pr/2169/base
Owner

@⁠RVZO6 on GitHub · 2026-11-25 06:50 UTC · original
RVZO6:rvzo/watch-batch → main · +517 −130 · 5 files · 2 commits · closed without merging

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)

**@⁠RVZO6** on GitHub · 2026-11-25 06:50 UTC · [original](https://github.com/Marvisak/VIctory/pull/2169) `RVZO6:rvzo/watch-batch` → `main` · +517 −130 · 5 files · 2 commits · closed without merging 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](https://github.com/RVZO6/VIctory/actions/runs/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)
Addresses all three review findings on #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)
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 04:57:10 +00:00
github-bot closed this pull request 2026-11-26 04:57:10 +00:00
Author
Owner

@⁠nathanbzrr on GitHub · 2026-11-25 08:40 UTC · original

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.

**@⁠nathanbzrr** on GitHub · 2026-11-25 08:40 UTC · [original](https://github.com/Marvisak/VIctory/pull/2169#issuecomment-7157333944) 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.
Author
Owner

@⁠MamaLeVrai on GitHub · 2026-11-25 08:52 UTC · original

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.

**@⁠MamaLeVrai** on GitHub · 2026-11-25 08:52 UTC · [original](https://github.com/Marvisak/VIctory/pull/2169#issuecomment-7157575189) 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.
Author
Owner

@⁠RVZO6 on GitHub · 2026-11-25 09:19 UTC · original

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)

**@⁠RVZO6** on GitHub · 2026-11-25 09:19 UTC · [original](https://github.com/Marvisak/VIctory/pull/2169#issuecomment-7158187166) 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`](https://github.com/RVZO6/VIctory/actions/runs/45581807630)): both `clippy -D warnings` builds clean, `716 passed; 0 failed; 10 ignored`, `xtask` `6/6`. AI-assisted: T3 Code (Antigravity, gemini-4-neon)
Author
Owner

@⁠Marvisak on GitHub · 2026-11-25 13:27 UTC · original · edited 2026-11-25 16:00 UTC

Automated triage for the maintainers.

This pull request no longer merges cleanly into main (conflicts in crates/victory-gpu/src/watch.rs). It will be reviewed once it is rebased onto the current main. The earlier verdict (needs-work) was for an older state of main.


Generated by Claude Code

**@⁠Marvisak** on GitHub · 2026-11-25 13:27 UTC · [original](https://github.com/Marvisak/VIctory/pull/2169#issuecomment-7163815362) · edited 2026-11-25 16:00 UTC <!-- victory-triage v1 head=8b8b07643744736c9b808ade9c55a8a036068528 verdict=needs-rebase at=2026-11-25T16:08:00Z --> Automated triage for the maintainers. This pull request no longer merges cleanly into `main` (conflicts in `crates/victory-gpu/src/watch.rs`). It will be reviewed once it is rebased onto the current `main`. The earlier verdict (needs-work) was for an older state of `main`. --- _Generated by [Claude Code](https://claude.ai/code)_
Author
Owner

@⁠RVZO6 on GitHub · 2026-11-25 17:13 UTC · original

Closing as superseded by main's change-tracking rework (cc0e153 dense dirty bitmap, 280b150 region-by-region tracking, 36ca299 guard-free retake). Thanks to @⁠nathanbzrr, @⁠DenRakEiw, and @⁠MamaLeVrai for reviewing!

**@⁠RVZO6** on GitHub · 2026-11-25 17:13 UTC · [original](https://github.com/Marvisak/VIctory/pull/2169#issuecomment-7169198044) Closing as superseded by `main`'s change-tracking rework (`cc0e153` dense dirty bitmap, `280b150` region-by-region tracking, `36ca299` guard-free retake). Thanks to @⁠nathanbzrr, @⁠DenRakEiw, and @⁠MamaLeVrai for reviewing!

Pull request closed

This discussion has been locked. Commenting is limited to contributors.
No reviewers
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
github/Marvisak--VIctory!2169
No description provided.