Skip to content

GPU: a marked page's copy-back writes only the bytes the shaders changed, with plain stores - #2918

Open
ZeOs360 wants to merge 3 commits into
Marvisak:mainfrom
ZeOs360:pr/marked-copyback-v8
Open

ZeOs360 wants to merge 3 commits into
Marvisak:mainfrom
ZeOs360:pr/marked-copyback-v8

Conversation

@ZeOs360

@ZeOs360 ZeOs360 commented Nov 25, 2026 •

Copy link
Copy Markdown

What

After a submission whose shaders marked a page as written through views,
Shadow::copy_back_marked writes the copy's whole 64 KiB page into title
memory when the title had not written the page since the copy took it
(the saved == None arm). The title's threads write those pages too, since
its records share the GPU heap. A title write that lands after that check
and before the write is put back to the copy's older bytes. Where the page
was saved, the merged page is written whole as well, so a title write
between its read and the write is undone the same way. This is the
failure Shadow::copy_back already merges against: its comment records the
copy's bytes going back over a fence list the title then read as -1.

This PR changes the copy-back to:

  • read the page while it is still armed, then ask under the guard lock what
    the title did to it (Tracked::finish, which replaces unarm and
    saved). A title write lands wholly before that (the page changed, its
    bytes from before saved if armed) or after it;
  • write only the runs of bytes the shaders changed, compared against those
    bytes from before, with no runs joined across gaps. A title write
    anywhere else in the page stays, and one made after the read is not undone;
  • keep upstream's rule that only a copy holding the whole page takes it,
    and guard it first and read it again after, so the copy also gets a title
    write that landed meanwhile.

Why plain stores

Exact runs are many and small. In the prologue's intro on 940d32f there
were about 3.3 million runs per frame, about 3.6 bytes each (on current
main, 1,400 to 1,900 runs per marked page, 7 to 10 bytes each). One
ReadProcessMemory per run (about 0.4 µs each, more under load) made the
marked copy-back take 1.1 to 3.5 s per frame for 1 to 11 MB (measured on
940d32f).

The runs are written with plain stores. The first commit does it with
watch::store, a rep movsb routine with unwind data. A destination page
that is not writable faults into the existing write handler:

  • a page we guarded is opened, and the store goes on, as for a title write;
  • any other page (nothing mapped, read-only, one that cannot be read in, or
    a title's own guard page) ends the store. The handler resumes the routine
    at its end, and what is left goes through the kernel (host::write_mapped)
    as before.

The second commit makes exact runs cheaper:

  • watch::store_runs writes all of a page's runs in one call (runs of up
    to 16 bytes a byte at a time, longer ones with rep movsb). A fault ends
    the call, which returns the run it was at; that run and the rest go
    through the kernel.
  • changed_runs compares 64 bytes at once (SSE2) into a mask of the bytes
    that differ, and reads the runs from the mask's runs of set bits: a few
    steps per run, none per byte (tested against the byte-by-byte search).
  • A copy holding the whole page reads it again after the guard anyway, so
    the runs are merged only where it holds the page in part or cannot read
    it again. The page and the list of runs are kept by the thread, not made
    per page.

Cost in the intro's scene, averaged over the frames that copied back more
than 500 marked pages (one run of the game each; the third commit changes
only tests):

on 13f91ca on 219878a
main (whole-page writes) 58 µs 51 µs
this PR, first commit 104 µs
this PR, first two commits 55 µs 64 µs

On the current base exact runs cost about 13 µs a page more than the
whole-page write: about 16 ms a frame at about 1,200 marked pages, on
frames of a second or more. The runs differ from run to run of the game
(1,400 to 1,900 a page), so these single runs are rough.

Relation to other PRs

Tests

  • shadow::tests::marked_copy_back_keeps_a_title_write_made_meanwhile
    writes the page from the title while the copy-back runs, once while the
    page is armed and once after the copy-back asked. With the whole-page
    write, both cases fail, and the title's bytes come back as ff ff ff ff.
    With this change both pass.
  • watch::tests::stores_mark_guarded_pages_and_stop_at_unwritable_ones
    writes short and long runs and covers four destinations: a guarded page
    (opened and marked changed, also from inside rep movsb), a read-only
    page, a decommitted page, and a title guard page, plus empty and reversed
    runs.
  • shadow::tests::changed_runs_are_those_byte_by_byte checks the
    64-byte search against the byte-by-byte one on random data of many
    lengths and densities, and on runs at block edges, in the tail and in
    slices that do not start on 16 bytes.
  • The third commit makes the tests that work on registered copies of
    title memory themselves (eight in shadow, one in host) hold off
    submissions (Host::no_submissions, tests only), as Host::execute
    does around its own copy-back. Another test's submission in parallel
    could refresh their copies or take their marks meanwhile, which is why
    partial_refresh_under_marked_range_updates_saved_bytes sometimes failed
    on main; the longer copy-back of this PR made it and two more fail in
    13 of 30 parallel runs. With the lock: no failure in 40 parallel runs of
    the crate's tests.
  • cargo test -p victory-gpu: 234 passed. cargo clippy --workspace --all-targets -- -D warnings, with and without --all-features: clean.
    cargo xtask policy: ok.
  • Two victory-shader tests fail on my machine with a DXIL validation
    error (rectangles_get_their_fourth_corner,
    elements_sharing_a_row_keep_their_order). This PR does not touch that
    crate, and it is identical to main there.

In game

Machine: RX 7800 XT 16 GB, Ryzen 5 5600, 16 GB RAM, Windows 11, Series X
profile, diagnostics builds. My own copy of the title was used; only log
lines, sizes and timings are reported here.

  • On 13f91ca with this PR, the intro's scene ran 493 s (one run
    with the first commit) without the -1 read, against 487 s for one stock
    run. Neither run hit it, so this says nothing either way about the crash;
    it shows the change runs in game.
  • On 940d32f, one of two stock runs hit a title read of address -1 at
    image+0x4f400a9, about 64 frames into the intro's scene. Builds with the
    view-mark fixes ran up to about 332 frames there without it. Those builds
    carried more than this change, so this does not show that this change
    alone removes that crash.
  • On main I make no in-game claim about the -1 read: one run
    cannot show whether it became rarer. The race is still in the code, and
    the test above reproduces it.
  • On every run on this 16 GB machine, CreateCommittedResource for
    shared (CUSTOM, L0) buffers began failing with E_OUTOFMEMORY after 2.5
    to 5 minutes, and the run ended 3.5 to 9.5 minutes in. This happens on
    main as well and is unrelated to this change. After the failures
    began, some runs stopped within a minute with "a host command list did
    not close" (once with E_OUTOFMEMORY as its error). That happened with
    this PR, and also with a build that does not contain it; stock main
    and the first commit alone ran about 6 more minutes, until the title
    stopped. So I take it to follow from the failed allocations, not from
    this change. The cost numbers above come from the first minutes in the
    intro, before a run was stopped by me or by that failure.

AI-assisted: written with Claude Code (Claude Opus 5.5) and reviewed by
Gemini 4 Neon. I read the code and the reviews, and ran the in-game tests
on my machine.

ZeOs360 and others added 3 commits November 26, 2026 00:03
After a submission whose shaders marked a page as written through views,
copy_back_marked wrote the copy's whole 64 KiB page into title memory
when the title had not written the page since the copy took it. The
title's threads write those pages too (its records share the GPU heap):
a title write landing after that check and before the write was put back
to the copy's older bytes. Where the page was saved, the merged page was
written whole too, so a title write between its read and the write was
undone the same way. Shadow::copy_back already merges for this reason:
its comment records the copy's bytes going back over a fence list the
title then read as -1.

The copy-back now
- reads the page while it is still armed, then asks under the guard lock
  what the title did to it (Tracked::finish, replacing unarm and saved):
  a title write lands wholly before that (the page changed, its bytes from
  before saved if armed) or after it;
- writes only the runs of bytes the shaders changed against those bytes
  from before, so a title write elsewhere in the page stays, and one after
  the read is not undone;
- has a copy holding the whole page take it, guarded and then read again,
  so the copy gets a title write that landed meanwhile.

The runs are written with plain stores (watch::store, `rep movsb`), not
a ReadProcessMemory each: in the world there are millions a frame, a few
bytes each, and a system call apiece cost 1.1 to 3.5 s a frame. A
destination page that is not writable faults into the write handler: a
page we guarded is opened and the store goes on; any other (nothing mapped,
read-only, one that cannot be read in, a title's own guard page) ends the
store, which returns the bytes left, and those and the page's remaining
runs go through the kernel as before. The diagnostics line counts the
runs.

Tests: marked_copy_back_keeps_a_title_write_made_meanwhile writes the
page from the title while the copy-back runs, once while the page is
armed and once after the copy-back asked (both fail with the whole-page
write: the title's bytes come back as ff ff ff ff);
stores_mark_guarded_pages_and_stop_at_unwritable_ones. The tests of armed
runs and busy aliases ask Tracked::finish for the saved bytes; that
unarms the page, so the disarm check arms every page again first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… one call

The copy-back of marked pages writes only the runs of bytes the shaders
changed: in the world about 1,500 a page, 7 to 10 bytes each, spread over
most of it. Run by run it cost about 100 µs a page, against 58 µs for
writing the whole page (on 13f91ca). Three things went:

- A call per run: watch::store_runs writes all of a page's runs in one
  call. Runs of up to 16 bytes are copied a byte at a time, longer ones
  with `rep movsb`, whose start costs as much as a short run. A store that
  faults at a page that is not writable ends the call, which returns the
  run it was at; that run and the rest go through the kernel as before.
  The runs are `[usize; 2]`, whose layout is fixed, for the routine.
- A step per byte: changed_runs compares 64 bytes at once (SSE2) into a
  mask of the bytes that differ, and reads the runs from the mask's runs
  of set bits, a few steps per run and none per byte.
- Merging and allocating: a copy holding the whole page reads it again
  after the guard anyway, so the runs are merged into the bytes read only
  where it holds the page in part or cannot read it again; the page's
  bytes and the list of runs are kept by the thread, not made per page.

In the prologue's intro the marked copy-back costs about 64 µs a page,
against about 51 µs for writing whole pages (on 13f91ca: 55 against 58).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Host::execute prepares, runs and copies back under its submission lock.
Tests that register a copy of title memory and then update it or copy
it back themselves did not hold that lock, so a submission of another
test running in parallel could
- bring every registered copy up to date meanwhile (a submission using
  title memory, as the memory tests' do): it took the test's changed
  page, dropped the bytes saved of it and copied the title's bytes over
  the shaders';
- copy back the marked pages of the shared mark bitmaps, taking the
  marks a test had just set.

partial_refresh_under_marked_range_updates_saved_bytes failed that way
now and then on main (a shader byte read back as 0), and the exact-run
copy-back of the commits before, with its longer window, made it and
two more of these tests fail in over two-fifths of parallel runs (13 of
30). The tests that do this now hold the lock while they run
(Host::no_submissions, tests only): no failure in 40 parallel runs of
the crate's tests (nor in 65 more with only the four copy-back tests
holding it).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

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

Verified head eed0c767 cleanly merged onto origin/main (63bcca43) on Windows 11 x64 (NVIDIA GeForce RTX 5090 + D3D12 WARP + VICTORY_D3D12_DEBUG=1).

Safety & Concurrency Audit

  • Race-free snapshot & zero-write fast path: Reading the title page before Tracked::finish(page / PAGE) under guards() closes the race between reading title bytes and VEH write capture, and short-circuiting when runs.is_empty() && saved.is_none() (Untouched) skips unprotect/reprotect completely on unchanged pages.
  • x64 VEH global_asm! (watch::store_runs): Properly preserves callee-saved rdi/rsi/rbx with matching .seh_pushreg unwind metadata; on_write transparently marks GUARDS pages while store_failed safely redirects IN_PAGE_ERROR / GUARD_PAGE_VIOLATION / unmapped / foreign read-only faults to victory_gpu_store_runs_failed, letting the caller fall back to write_mapped for &runs[at..].
  • Cross-PR note (#2914): Semantically compatible with #2914's multi-threaded for_each_by_page (uses thread_local! static SCRATCH); both insert helpers right after forget_read in shadow.rs, so whichever lands second will only need a trivial context merge.

Local Verification (--features diagnostics, VICTORY_D3D12_DEBUG=1)

  • RTX 5090 & WARP: shadow:: + draw::tests + watch::tests 48/48 passed on both adapters (including all 3 new tests and all marked_subpage_uav_* tests), zero debug-layer errors.
  • cargo clippy --locked -p victory-gpu --tests -- -D warnings (default and --features diagnostics) & cargo xtask policy (191 files ok): clean.

Solid implementation and tests — looks ready to merge.

@Kajanos

Kajanos commented Nov 26, 2026

Copy link
Copy Markdown

Windows 11 / NVIDIA test run, head eed0c767c8 merged onto main 63bcca43c6.

Setup: Windows 11 Home build 26300, RTX 5080, NVIDIA 621.40, rustc 1.98.1 MSVC, VS 2022 Build Tools, Windows SDK 10.0.26100 (dxil.dll from the SDK).

  • cargo test --locked -p victory-gpu: 234 passed, 0 failed, 1 ignored (main: 231).

Not run: the retail title, clippy, and other crates.

AI-assisted (Claude Code)

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

Scoped review: writing only the changed byte-runs instead of whole pages is a real correctness win, not just perf — the title's threads write the same pages meanwhile and a whole-page copy-back can clobber their newer bytes (the fence-list-as-(-1) case the comment names). The Tracked::finish read-while-armed ordering keeps the 'bytes before the title's write' snapshot semantics. store_runs with the kernel fallback for unmapped tails is the right shape.

Note for reviewers: this composes cleanly with #2914 (my port of the page-threading change) — that PR parallelizes the outer loop only; copy_back_marked's signature and per-page exclusivity are unchanged, so the two merge in either order. The no_submissions test guard also fixes the same cross-test flake class #2888 addresses.

@MeMako

MeMako commented Nov 26, 2026

Copy link
Copy Markdown

Independent verification of eed0c76 on AMD Ryzen 9 7950X + AMD Radeon RX 9070 XT (adapter 0, driver 32.0.32029.2010, 32 GB RAM, Windows 11 10.0.26200 x64).

CI checks & tests:

  • cargo clippy -p victory-gpu -p victory --all-targets --locked -- -D warnings (and --all-features): pass
  • cargo test -p victory-gpu --locked: 243 passed, 0 failed (including marked_copy_back_keeps_a_title_write_made_meanwhile, stores_mark_guarded_pages_and_stop_at_unwritable_ones, and changed_runs_are_those_byte_by_byte)

Live title run (release build, warm shader & pipeline cache):
(Note: merged cleanly onto a local RX 9070 XT branch on 842b0cb with a separate-handle workaround equivalent to #2122, DYNAMIC = 1 << 19, #2051, #2472, and a local timing breakdown of copy_back_marks; before/after compared against the exact same branch without #2918.)

Metric (world frames, draws >= 500) Without #2918 (n=50) With #2918 (n=97)
Marked pages / frame (median) 2,444 2,662
Marked bytes written back / frame (median) 97.9 MB (whole pages) 35.5 MB (changed bytes only)
copy_back_marks time (median) 54.9 ms (22.9 µs/page) 81.7 ms (32.2 µs/page, +9.3 µs/page)
Title corruption crashes (read 0xffffffffffffffff) 1 (previous run also hit 1) 0 across 8+ minutes in world

Consistent with your Ryzen 5 5600 measurements (+13 µs/page vs +9.3 µs/page here on a 7950X), and eliminates ~62 MB/frame of whole-page overwrites over unchanged title memory.

No game data, shader names, or screenshots are included, per docs/asset-policy.md. Hardware runs were performed by me on my 7950X / RX 9070 XT; comment drafted with Antigravity.

Marvisak commented Nov 26, 2026 •

Copy link
Copy Markdown
Owner

Automated triage for the maintainers.

Needs work: needs the maintainer's decision (unchanged). Thanks for the comparison. I checked the one factual point that bears on the choice: #2242 currently does not merge with main (conflicts), while this PR merges cleanly. The head is unchanged, and the code in watch.rs and shadow.rs copy_back_marked still reads correctly.

The open questions are for the maintainer:

The measured cost per marked page (1.25x to 1.4x) is lower than what is reported for #2242.

CI: passing.


Generated by Claude Code

@ZeOs360

ZeOs360 commented Nov 26, 2026

Copy link
Copy Markdown
Author

To help with the choice the triage asks for, how this PR and #2242 differ:

this PR #2242
what goes back the exact runs the shaders changed runs, joined into one span when less than 256 bytes apart
a title write landing between the read and the write kept, outside the bytes the shaders changed the same, unless it falls in a gap between joined runs (the shortcut its description states)
paths copy_back_marked copy_back_marked, copy_back_page and the snapshot copy_back
how bytes are written plain stores (store_runs); at a page that is not writable they stop, and the rest goes through the kernel copy one kernel copy per span
cost measured in game about 1.25x per marked page (64 against 51 us, RX 7800 XT, one run each) and 1.4x (32.2 against 22.9 us, RX 9070 XT, MeMako's report above) about 2.7x per MB written back with #2280 on top, same tree, and 3.2x alone from a different tree and scene (RTX 5070, r4tedx's reports on #2242)
state merges cleanly needs a rebase (conflicts in shadow.rs)

On the global_asm!: exact runs need one write per run, and a kernel copy costs about 0.4 us each; r4tedx measured exact runs through it at 509 us per page with one changed word per 64 bytes (synthetic, on #2242). Plain stores need a way past a store into a page the title unmapped or protected meanwhile. Here the guard handler opens our own guarded pages as usual; any other write fault between the routine's labels moves RIP to the routine's exit, which returns the run it was at. r4tedx's fork branch perf/copy-back-spans, mentioned on #2242 before this PR, uses the same approach (an inline rep movsb that the handler steps past).

If you'd rather not have the assembly, this can go back to a kernel copy per run (at the cost above), or be closed in favor of #2242 once it is rebased, whichever you prefer. If this PR is the one you keep, I'll bring copy_back_page and the snapshot path over to the same pieces in a follow-up, which covers what #2242 adds.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants