Skip to content

GPU: a refresh batch takes the written pages of all its copies in one round of the guard lock - #3585

Open
neonbyte1 wants to merge 1 commit into
Marvisak:mainfrom
neonbyte1:pr/batched-refresh-take
Open

neonbyte1 wants to merge 1 commit into
Marvisak:mainfrom
neonbyte1:pr/batched-refresh-take

Conversation

@neonbyte1

Copy link
Copy Markdown

What's wrong

A submission's refreshes are batched per copy (Batch, crates/victory-gpu/src/host.rs:2399), but Batch::flush (host.rs:2440) then brings each copy up to date on its own: shadow.update(from, to - from) per copy (host.rs:2447) → Shadow::update_tracked (shadow.rs:607) → Tracked::take_split (watch.rs:478). Each take with a written page in its range takes the global guard lock (watch.rs:503), guards the pages' other mappings, makes the pages read-only and drops them from the copy's changed set.

The copies only ever read pages recorded as written, so the volume is small (~130 MB a frame here). The cost is the lock: a world frame makes one round of watch::GUARDS per copy with written pages, 3,229 rounds a frame in our runs. The title's write-fault handler and marked copy-back hold the same lock, so these rounds mostly wait: 7.8 ms a frame in change checks: … waiting for the guard lock, on the submitting thread, before ExecuteCommandLists.

(The copies per frame line's MB checked — 6.3 GB a frame here — is the span asked, not bytes compared: take_split looks only at the copy's set of written pages in it.)

The fix

Batch::flush works in three phases:

  1. Look up (shadow::plan → Tracked::written): for each copy, the written pages in its asked range, read under the copy's own set lock only. A copy with nothing written there stops here. Memory that is not tracked is copied whole, as before.
  2. Take once (shadow::refresh_planned → watch::take_written): the whole pages of all copies, sorted and deduplicated, in one hold of the guard lock. Each page's other mappings are guarded once, consecutive pages across copies share one VirtualProtect, then each copy's set drops the pages taken.
  3. Copy (Shadow::copy_taken, the former tail of update_tracked): per copy, one copy per contiguous run, zeros for unmapped runs, untracked parts whole, snapshot sync where this submission's shaders write.

Tracked::take_split is now written + take_written for one tracker, and Shadow::update is plan + refresh_planned for one copy, so there is one take and one refresh path. No switch: the guarantee is the one a single take gives (below), the existing take tests now run through take_written, and the change was measured in the title behind a switch first.

Why no write is missed. A page leaves a copy's set only under the guard lock, once it is guarded at every mapping (pages that can't be guarded stay changed and are still copied). Copies are read after the take. So a title write before the guard is in the copy; a write after it faults and marks the page again. Writers that don't fault (kernel reads, DirectStorage, remaps, copy-back) mark under the guard lock, so before the page leaves the set (it's in the copy) or after (it's changed again). A page written between the look-up and the take isn't in the plan and stays changed. A page only partly in the asked range is copied in part and stays changed. The window between take and copy is longer than before, but correctness never depended on its length.

The copies line gets N guard-lock rounds next to the guard-lock wait (C::TakeRounds, diagnostics only).

Run splitting looks up unmapped pages by binary search, removing the O(n²) unmapped.contains that #3156 also fixes.

Tests

CPU only, watch.rs:

  • a_batched_take_takes_the_written_pages_of_every_tracker:
    • nested, overlapping and mid-page trackers in one take each get their runs;
    • one guard-lock round; 8 consecutive pages in one protection change; a page two trackers share guarded once (3 calls for pages 1, 3 and 6);
    • pages outside an ask, and partial pages, stay changed;
    • a page written between look-up and take stays changed;
    • a write to an open page before the take is covered; a write after it faults.
  • batched_refreshes_under_concurrent_writes_lose_no_write:
    • 8 writer threads over a 32-page pool and both mappings of twin views;
    • 7 overlapping trackers (one starts mid-page, one ends mid-page, two on the twin views);
    • 300 rounds of batched refreshes over random asked ranges, copying what each take returns;
    • afterwards, every page where a copy differs from title memory is still changed, and one last refresh leaves every copy equal and clean.
  • Deliberate bugs, each caught:
    • take without guarding (taken = whole): both tests fail;
    • drop pages only partly asked from the sets: the concurrent test fails.

GPU, skipped without a device: host::batch::overlapping_copies_in_one_batch_each_take_the_written_pages (two overlapping copies in one batch, each gets its written pages; a later write is seen by both). The existing a_copy_is_refreshed_once_per_submission_by_the_pages_written covers one copy.

In the title

RTX 5090, Linux, GE-Proton11-14 Wine with its vkd3d-proton. Stack as listed in #3425, plus overlap and our pending early-release/barrier changes. Prison yard, diag build, two adjacent on/off pairs of the same exe (the change behind a switch there), 420 s each:

pair 1 pair 2 mean
frame, before 178.8 ms 199.6 ms
frame, with this 175.1 ms 182.4 ms −10.5 ms
preparing, before 71.4 ms 78.3 ms
preparing, with this 64.7 ms 67.3 ms −8.9 ms
guard-lock rounds by refresh takes 3,229 → 31

Pictures unchanged.

Related

None of them batches takes across copies.

Verification

  • cargo clippy --workspace --all-targets -- -D warnings, with and without --features diagnostics (x86_64-pc-windows-msvc): clean.
  • cargo xtask policy: asset policy: 191 files ok.
  • No formatting-only hunks against origin/main.
  • cargo test -p victory-gpu --lib watch:: under Wine, with and without diagnostics: 17 passed. Also passes on the default parallel test threads: the round and protection counts the batch test checks are per thread.
  • The two deliberate-bug builds: the first fails both new tests (left: (1, 0) and page … differs from its copy and is not changed); the second fails the concurrent one.
  • Device tests on this commit (RTX 5090, GE-Proton11-14 vkd3d-proton, --test-threads=1, filters host::batch:: shadow:: watch:: host::title_copies:: --skip shadow::run_tests): 31 passed, 0 failed. That is host::batch 2 (both batch tests), host::title_copies 2, shadow::tests 9 plus 1 other shadow:: test, and watch::tests 17.

AI-assisted (Claude); measured on my machine, no game data shared.

… round of the guard lock

Batch::flush brought each copy up to date on its own: a Tracked::take_split
per copy, each with written pages taking the global guard lock that the
title's write faults and marked copy-back hold too. A world frame made
~3,200 such rounds and spent ~8 ms of its preparing waiting for the lock.

Now a flush looks up each copy's written pages in its range under the
copy's own lock (shadow::plan, Tracked::written), takes the pages of all
of them in one hold of the guard lock (watch::take_written: other mappings
guarded once per page, one protection change per run of consecutive pages
across copies), then copies each copy's runs (Shadow::copy_taken).
take_split and Shadow::update are the same path for one tracker or copy.
The copies line counts the guard-lock rounds of takes.

Tests: watch::tests::a_batched_take_takes_the_written_pages_of_every_tracker,
watch::tests::batched_refreshes_under_concurrent_writes_lose_no_write,
host::batch::overlapping_copies_in_one_batch_each_take_the_written_pages.
@pickles976

pickles976 commented Nov 27, 2026 •

Copy link
Copy Markdown

Offscreen Wine/NVIDIA verification of exact production af08b8b11f28adeb1e355620cfa7ea20751e8491. Only local test-only changes make both host::batch fixtures require a physical NVIDIA DXGI adapter and successful host-copy allocation/mapping instead of returning early.

cargo test -p victory-gpu --features diagnostics --lib -- watch::tests:: host::batch:: --nocapture --test-threads=1: 19 passed, 0 failed/ignored, 0.78 s after a fresh intended-worktree 9.08 s build.

  • All 17 watch tests pass, including the new one-round/coalesced-protection assertions and the 8-writer / 7-tracker / twin-mapping concurrent fixture (300 debug refresh rounds). After writers stop, any stale copy byte remains marked dirty; final refresh leaves complete copies equal and trackers clean.
  • Both host batch tests pass: overlapping copies take shared and distinct changed pages, refreshes are deduplicated within a submission, and subsequent writes remain visible to both trackers.

Coverage distinction: these tests initialize the real RTX 4060 Laptop D3D12 device and inspect persistent host-buffer mappings. They do not dispatch a shader or submit a GPU command list. This is guarding/copy-consistency coverage, not a GPU-execution, loading frame-time, contention, peak-RAM, or title performance measurement. I have not reproduced the separate RTX 5090 frame-time numbers or performed a matched parent benchmark here.

Environment: Linux 6.17, 16 GiB RAM, RTX 4060 Laptop 8 GiB/NVIDIA 590.48.1, Wine 11, NVIDIA masking disabled; diagnostic-relaxed-vtable vkd3d 2576c0b4adfae4a+ (not stock certification). Original scope/global safeguards retained. Evidence: .compat-runtime/logs/verify-pr3585-batched-refresh-20261127T194039Z/ (console, compilation provenance, result and resource samples). No production edits, title launch, imagery or assets published.

AI-assisted verification.

28 Nov CPU-only follow-through, same production af08b8b11f28adeb1e355620cfa7ea20751e8491: a temporary release-mode benchmark compares 64 singleton take_split calls against one take_written batch on the same head, not a parent/head comparison. Each case tracks 64 MiB (64 trackers × 16 tracked 64-KiB pages), alternates order for nine measured pairs after a warm-up pair, and checks every source word plus complete copy ranges/clean state. Writes/faults and word verification are outside the timer.

Layout Singleton median Batch median Guard-lock rounds Protection calls
Contiguous trackers 1.1300 ms 0.9646 ms 64 → 1 64 → 1
One tracked-page gap 1.2195 ms 1.1145 ms 64 → 1 64 → 64

The median reductions are 14.6% / 8.6% in this uncontended synthetic workload; ranges overlap, especially with gaps. This supports the batching mechanism but does not predict a title-frame gain: our actual scene has overlapping watches/protection/fault-handler time, contention and different ranges. No GPU device was initialized or command dispatched in this new measurement. Fresh intended-tree compile36.84s; benchmark1/1 pass in0.92s. The temporary probe was archived then removed, leaving production unchanged.

Evidence .compat-runtime/logs/verify-pr3585-protection-bench-20261128T074631Z/ contains command/provenance, raw per-leg timings, measurement JSON and probe source. Command: cargo test --release -p victory-gpu --features diagnostics --lib watch::tests::lab_protection_batch_measurement -- --ignored --exact --nocapture --test-threads=1 through the existing Windows-MSVC/Wine wrapper. Same Linux/Wine/16-GiB laptop environment; safety limits unchanged. Title promotion remains parked after a separately reported GPU timeout, not attributed to this unintegrated PR. AI-assisted measurement/report: omp, OpenAI GPT-6 Astra.

Mixed-runtime integration, 28 November 08:03 UTC

Ported this production change onto the existing dirty local runtime (base 3ed7d725f6895fe1a235eb6fa8ff2485261ca151), preserving its in-place early return, pending before-images and #3343 guard-opening path. This is not an exact-head result. The local Batch::flush adaptation borrows the refresh vector during planning, then drains it after dropping the plan, retaining its allocation instead of mem::take discarding capacity. The diagnostic counter array derives its size from the last counter variant. No shader changes or safety-cutoff changes.

  • watch::tests::: 19/19 pass, 0 ignored, 0.75 s after fresh intended-tree 7.42 s compilation. Includes batched concurrent writers/aliases, saved before-images, and existing guard-opening/decommitted-middle regressions. One fixture initializes the actual NVIDIA device: despite the evidence directory's cpu label, this invocation was not strictly CPU-only.
  • host::batch::: 2/2 pass, 0 ignored, 0.65 s after another fresh 7.42 s compilation. Both require physical NVIDIA identity and successful host-copy mapping. VICTORY_IN_PLACE=0; the overlapping copies each receive their changed pages and see subsequent writes. These fixtures allocate/map native resources and copy through CPU mappings; they do not execute command lists or dispatch shaders.

Same Wine 11 / RTX 4060 Laptop / NVIDIA 590.48.1 / diagnostic-relaxed vkd3d 2576c0b4adfae4a+ stack, not stock certification. Peak sampled GPU use 140/154 MiB; minimum available RAM 11067/11085 MiB. Evidence: verify-mixed3585-tracking-cpu-20261128T080113Z/ and verify-mixed3585-mapped-batch-20261128T080318Z/ (console.log, result.json).

Commands used the existing Wine wrapper, test -p victory-gpu --features diagnostics --lib watch::tests:: -- --nocapture --test-threads=1, then the same command with host::batch::. These are narrow correctness gates, not an in-title speedup or asynchronous GPU-lifetime certification. No new release/title run: the previously reported Xid109 / pending-submission stall still blocks runtime promotion; this report does not attribute it to this PR.

@neonbyte1

Copy link
Copy Markdown
Author

@pickles976 thanks for checking the exact head on a second NVIDIA card, and for spelling out the coverage boundary: right, these fixtures exercise the guard/copy consistency with a real device's host mappings, not GPU execution. The frame-time effect is only from our 5090 runs (two adjacent pairs) and is stated as such in the description.

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

@andrewpozdnakov7-jpg

Copy link
Copy Markdown
Contributor

I checked the diagnostics overlap with #3594. The exact heads af08b8b and 377cd2d conflict on the counter array length. Tested pair keeps TakeRounds and the three copy-back counters, deriving the array length from the final counter.

On Windows WARP the same two-frame synthetic window printed one guard-lock round per frame and copy-back averages of 1.0 eligible, 0.5 wrote bytes and 1.0 withheld. The next window printed zero for all four figures. The existing synthetic byte checks passed, and the diagnostics suite passed 249 project GPU tests plus the SDK identity check, with one ignored.

Strict GPU Clippy passed for default and all features. The asset policy check passed.

@neonbyte1 and the maintainers can use the tested conflict resolution if both changes are applied. Please retain Git authors on cherry-pick or rebase. If you fold my work into another commit, please include Co-authored-by: andrewpozdnakov7-jpg <andrewpozdnakov7-jpg@users.noreply.github.com>.

@neonbyte1

Copy link
Copy Markdown
Author

@andrewpozdnakov7-jpg thanks, that saves a rebase. I'll keep #3585 independent of #3594 (it's a one-line counter overlap, not a behaviour one); whichever lands second takes your 3cdd467 resolution, with your authorship kept. If #3594 merges first I'll rebase #3585 onto it the same way.

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

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.

3 participants