Skip to content

GPU: batch descriptor sync_heaps per dirty page without holding SHADER_HEAPS - #2170

Open
RVZO6 wants to merge 2 commits into
Marvisak:mainfrom
RVZO6:rvzo/descriptor-sync
Open

RVZO6 wants to merge 2 commits into
Marvisak:mainfrom
RVZO6:rvzo/descriptor-sync

Conversation

@RVZO6

@RVZO6 RVZO6 commented Nov 25, 2026

Copy link
Copy Markdown

At every submission, descriptor::sync_heaps() currently holds the global SHADER_HEAPS mutex while scanning every dirty 64 KiB page of every shader-visible heap and calling HostHeap::mirror() slot by slot. Each 32-byte slot (2,048 slots per dirty page) separately locks self.made, locks global VIEWS, clones View, and touches D3D12 — blocking parallel command-list recording threads on SHADER_HEAPS and doing ~4,096 mutex acquisitions per dirty page even when most slots are empty or unchanged.

The change

  • crates/victory-gpu/src/descriptor.rs:
    • Store Arc<host::HostHeap> in Heap::host (OnceLock<Option<Arc<host::HostHeap>>>) so sync_heaps() snapshots (Arc<HostHeap>, dirty_ranges, start, step, count) under SHADER_HEAPS and releases SHADER_HEAPS immediately before scanning dirty pages or updating host descriptor heaps.
    • Add read-only Views::matches(i, generation) and Views::get(i, generation) helpers (valid packed keys are always non-zero because generation >= 1).
    • Add descriptor::tests::dirty_page_sync_leaves_shader_heaps_unlocked_and_skips_unchanged proving SHADER_HEAPS.try_lock() succeeds inside the sync callback and unchanged ranges are skipped.
  • crates/victory-gpu/src/descriptor/host.rs:
    • Add HostHeap::mirror_range(first, last, start, step) and classify_range(made, first, end, start, step):
      • Acquires self.made once per dirty page and VIEWS at most once per dirty page.
      • Skips already-empty slots (key == 0 && made[slot] == 0) without touching VIEWS or D3D12.
      • Validates unchanged populated slots (made[slot] == key) via views.matches(idx, gen) with zero View::clone() and zero D3D12 descriptor copies.
      • Only clones View and updates the host descriptor heap (apply_view) for added, changed, or invalidated slots, releasing VIEWS before calling D3D12.
    • Add descriptor::host::tests::classify_range_matches_per_slot_mirror_across_pages proving slot-for-slot equivalence with mirror() across empty, unchanged, changed, invalidated, and page-spanning ranges.

Not a duplicate of

#840 targets 256-byte aligned CBV table mirroring without dynamic slots, and #2121/#2128 target view-heap paging and unbound null descriptors. No other open PR removes the SHADER_HEAPS hold across dirty-page scans or batches HostHeap::mirror_range per dirty page.

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 (both new descriptor / descriptor::host tests and all existing descriptor tests) and xtask (6 passed, 0 failed, repository_passes_policy).
  • Standalone branch b42604b: cargo clippy (default & --all-features) -D warnings clean; Wine-10.0 passed descriptor tests (12 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)

…R_HEAPS

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 dirty_page_sync_leaves_shader_heaps_unlocked_and_skips_unchanged — passed
  • cargo clippy -p victory-gpu --all-targets — 0 warnings
  • cargo xtask policy — ok (183 files ok)

Clean per-dirty-page batching in sync_heaps without holding SHADER_HEAPS, skipping unchanged views cleanly. 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.

Descriptor sync_heaps batched per dirty page — sync batching perf work.

RecompLive added a commit to RecompLive/victory-fork that referenced this pull request Nov 25, 2026
…sync

Port of Marvisak/VIctory#2170 by RVZO6 (GPL-3.0-or-later).

sync_heaps collected dirty ranges, then mirrored every slot while still
holding SHADER_HEAPS, so recorders waited on the sync. It now takes the
ranges and an Arc of each host heap under that lock, drops it, and makes
each readable page's slots after. A page's slots are classified in one
pass under one VIEWS lock, unchanged populated slots are checked by
generation only (no clone), and a repeat scan emits no updates.

Shortcut: the page is still re-read for every dirty range covering it;
fine for the 1,300-14,400 slots a frame, upgrade if a wider heap is
written wholly each frame.

Tests: dirty_page_sync_leaves_shader_heaps_unlocked_and_skips_unchanged,
classify_range_matches_per_slot_mirror_across_pages.
@nathanbzrr

Copy link
Copy Markdown
Contributor

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

Baseline descriptor::tests pass (12/12), but removing the read_into safety boundary and dropping SHADER_HEAPS before raw pointer reads causes a deterministic single-threaded crash and multiple concurrency hazards:

  1. Live Repro — Deterministic STATUS_ACCESS_VIOLATION (0xC0000005) on partial 4 KiB decommits / boundary straddles (descriptor.rs:185-197, descriptor/host.rs:290-298):
    sync_heaps_with probes only 4 bytes (read_into(page, &mut [0u8; 4])), whereas classify_range reads 12 bytes per slot via raw (start + index * step) as *const [u32; 3].

    • When OS page 0 (page..page+4096) is committed and OS page 1 (page+4096..page+8192) is MEM_DECOMMIT, read_into(page, 4) succeeds and classify_range faults at slot 128 (page + 4096).
    • Repro (repro_sync_heaps_partial_4k_hole_must_not_crash) terminated the test process immediately:

      process didn't exit successfully ... (exit code: 0xc0000005, STATUS_ACCESS_VIOLATION)

    • Similarly, an unaligned placed heap (step = 32, start = P + 24, P + 65536 unmapped) has last = 2048, reading [P + 65528 .. P + 65540) (4 bytes past the 64 KiB boundary into unmapped memory).
  2. Source-level — TOCTOU STATUS_ACCESS_VIOLATION after releasing SHADER_HEAPS (descriptor.rs:82-99):
    Dropping SHADER_HEAPS before scanning lets a concurrent title thread execute Heap::drop() (Release()) and VirtualFree / XMemUnmapPhysicalPages between read_into and classify_range's raw pointer reads (while sync_heaps_with holds self.made and VIEWS).

  3. Source-level — Stale slot overwrite race in HostHeap::mirror & widened Resource* UAF (descriptor/host.rs:265-275, 650-660, resource.rs:1428):

    • HostHeap::mirror reads [tag, i, generation] before locking self.made. Now that mirror and sync_heaps_with no longer share SHADER_HEAPS, mirror can overwrite a newer descriptor synced by sync_heaps_with with a stale local read.
    • Batching up to 2,048 cloned Views past the VIEWS unlock widens the Resource* UAF window inside make_marked against concurrent Drop for Resource.

(Proposed / uncompiled fix direction:) replace the 4-byte read_into probe with a single full-page read_into into a reusable scratch Vec<u8> + safe classify_bytes (same syscall count, per-slot 12-byte fallback on partial reads, zero raw pointer dereferences), add an Arc<AtomicBool> liveness guard, lock self.made before reading the title slot in HostHeap::mirror, and re-validate/hold VIEWS around Resource* dereferences in apply_view.

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 b42604b6 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: first run 703 passed, 0 failed, 10 ignored. In the second run one test failed, and it is one this PR adds: descriptor::tests::dirty_page_sync_leaves_shader_heaps_unlocked_and_skips_unchanged panicked at descriptor.rs:896 with "SHADER_HEAPS held during scan". SHADER_HEAPS is a global lock, so I suspect another test of the crate takes it at the same moment (tests of one crate run in parallel); I have not confirmed which. That makes the test race when the suite runs concurrently; it passed in the first run. The title was not run, so this says nothing about in-game effect. No game data.

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

… and serialize mirror with VIEWS

Addresses all three review findings on Marvisak#2170:
- Replace the 4-byte read_into probe + raw pointer dereferences in classify_range with a single safe full-page read_into into a reusable scratch Vec<u8> (falling back to 4 KiB OS-page and per-slot 12-byte read_into slices on partial MEM_DECOMMIT holes or unaligned boundary straddles) and safe byte-slice scan_bytes/classify_bytes.
- Add an Arc<AtomicBool> alive guard on Heap (cleared under SHADER_HEAPS in Heap::drop) so in-flight sync_heaps_with stops before touching freed pages.
- Lock self.made before reading the title slot (via safe read_into) in HostHeap::mirror so mirror and mirror_bytes serialize strictly on self.made, and apply changed views under VIEWS directly in both mirror and mirror_bytes (zero View::clone in mirror_bytes and no stale Resource* window against concurrent Drop for Resource).
- Add regression tests sync_heaps_handles_partial_4k_decommit_and_unaligned_straddle and sync_heaps_aborts_when_heap_drops_concurrently.

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

Addresses all three review findings on Marvisak#2170:
- Replace the 4-byte read_into probe + raw pointer dereferences in classify_range with a single safe full-page read_into into a reusable scratch Vec<u8> (falling back to 4 KiB OS-page and per-slot 12-byte read_into slices on partial MEM_DECOMMIT holes or unaligned boundary straddles) and safe byte-slice scan_bytes/classify_bytes.
- Add an Arc<AtomicBool> alive guard on Heap (cleared under SHADER_HEAPS in Heap::drop) so in-flight sync_heaps_with stops before touching freed pages.
- Lock self.made before reading the title slot (via safe read_into) in HostHeap::mirror so mirror and mirror_bytes serialize strictly on self.made, and apply changed views under VIEWS directly in both mirror and mirror_bytes (zero View::clone in mirror_bytes and no stale Resource* window against concurrent Drop for Resource).
- Add regression tests sync_heaps_handles_partial_4k_decommit_and_unaligned_straddle and sync_heaps_aborts_when_heap_drops_concurrently.

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

RVZO6 commented Nov 25, 2026

Copy link
Copy Markdown
Author

Thanks @nathanbzrr for the RX 7600 audit and crash repro — all three findings are fixed in cf9c011:

  1. Safe read_into full-page copy + 4 KiB / per-slot fallback (descriptor.rs, descriptor/host.rs):
    • Replaced the 4-byte probe + raw pointer dereferences in classify_range with a single full-page read_into into a reusable scratch Vec<u8> (same 1 syscall per committed dirty 64 KiB page) and safe byte-slice parsing (scan_bytes / classify_bytes).
    • When a 64 KiB read_into fails (partial 4 KiB MEM_DECOMMIT hole or unaligned boundary straddle), falls back to 4 KiB OS-page reads and per-slot 12-byte reads across 4 KiB boundaries with zero raw pointer dereferences.
  2. Heap lifetime guard (descriptor.rs):
    • Added alive: Arc<AtomicBool> on Heap (set to false under SHADER_HEAPS in Heap::drop) checked before reading/mirroring each page in sync_heaps_with.
  3. Serialized HostHeap::mirror & VIEWS-held apply_view (descriptor/host.rs):
    • HostHeap::mirror now locks self.made before reading the title slot (via safe read_into) so mirror and mirror_bytes serialize strictly on self.made.
    • Both mirror and mirror_bytes apply changed slots directly under VIEWS (zero View::clone in mirror_bytes and closing the Resource* UAF window against concurrent Drop for Resource).
  4. Regression tests: Added descriptor::tests::sync_heaps_handles_partial_4k_decommit_and_unaligned_straddle and descriptor::tests::sync_heaps_aborts_when_heap_drops_concurrently.

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)

@wbkepler

Copy link
Copy Markdown

Live check of this PR (head cf9c011) on Windows 11 / RTX 5090, merged into our integration build, which also carries #1779 (view heaps on hosts capped at 1M descriptors, through a 1,024-slot view-block remap). The two conflict in descriptor/host.rs. This is how I resolved it, in case it helps once either one lands:

  • Keyed through the block map. mirror_bytes compares each title slot with what its host slot holds now (through the block map; a slot whose view is not made yet still counts as held, so it gets visited and given back). mirror and the bulk path share one set_slot, so a block left without views still goes back.
  • No view made under VIEWS. An earlier resolution made the changed slots inside the with_views scan, and it stalled the title before the world in a live run: on our build, making a view can reach code that takes VIEWS again, and std mutexes don't re-enter. The scan now only collects the changed slots under VIEWS (cloning just those) and makes them after the lock is released. It might be worth checking whether any make_marked path on main can reach VIEWS too.

Measured on the same build and settings, 300 s runs, averaged over the last 12 five-second windows in the world (~5,000 draws/frame):

sync_heaps per frame
before (per-slot mirror) 64.8 ms
with this PR 59.0 ms

The world loaded and the run lasted the full 300 s with no stall, device removal or panic. cargo test -p victory-gpu --lib descriptor passes 19/19, including the new tests. The scan itself is no longer the cost. Per frame it reads about 212 dirty pages and 434k slots, but about 103k of those slots really changed (the title rewrites them), so what's left is making those views, not finding them.

AI-assisted check (Claude Code); Windows 11 / RTX 5090.

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.

6 participants