Skip to content

GPU: a copy-back still pending when the title takes the range back writes nothing - #3036

Closed
HoLa-Lee wants to merge 1 commit into
Marvisak:mainfrom
HoLa-Lee:gpu/no-copy-back-after-release
Closed

HoLa-Lee wants to merge 1 commit into
Marvisak:mainfrom
HoLa-Lee:gpu/no-copy-back-after-release

Conversation

@HoLa-Lee

Copy link
Copy Markdown

What this fixes

FIND-14 in the coordination thread: watch.rs documents that "memory freed and
allocated again while a tracker holds it is not seen", and nothing connected that
with Shadow's pending snapshot. A copy holds the address it was registered with
and writes back through it, so a title range freed and re-used between a
submission and its copy-back can have that submission's shader bytes written into
whatever took the addresses.

Reproduced with no game and no AMD card, in the test this PR adds: register a
page of title memory, take the submission's snapshot, let a shader write one byte
into the copy, unregister and VirtualFree the range, take the same addresses
again with VirtualAlloc filled with 0xEE, then run the copy-back. Before the
change:

left: 153   (0x99 - what the shader wrote for a submission that is over)
right: 238  (0xEE - what the title's next use of the address held)

The change

Shadow carries a flag that unregister sets; copy_back_or_not returns before
touching anything once it is set. A copy whose title buffer is gone writes
nothing back, and stays alive for the lists that still hold it - its own bytes
are the lists' to use, the title's memory is not.

cargo test -p victory-gpu --lib --profile diag --features diagnostics
245 passed, 2 failed, 1 ignored

The 2 are the FIND-9 view-heap pair on this NVIDIA host, which is #2937's.

What this does not claim

#2025's intermittent corruption was AMD and intermittent. This is one way
stale shader bytes can land in re-used title memory, deterministically and on any
host; it is not proof that it is that report's mechanism. What it gives #2025 is
a reproduction of the class, with no game - which is what FIND-14 asked for
("a synthetic concurrency test exercising remap-during-pending-copy-back if
someone wants to pursue it without the game").

Note on the test's setup

It only observes the hazard when the allocator hands the same address back
(q == p); when it does not, the test frees the new allocation, prints that it
was not observed and returns, rather than writing through an address that belongs
to nobody - which would be the same bug in the test. On this machine the same
address comes back every run.

…ites nothing

FIND-14 in the coordination thread: `watch.rs` documents that "memory freed and
allocated again while a tracker holds it is not seen", and nothing connects that
with `Shadow`'s pending snapshot - the copy holds the address it was registered
with and writes back through it. So a title range freed and re-used between a
submission and its copy-back can have that submission's shader bytes written
into whatever took the addresses.

Reproduced with no game and no AMD card, in the test this commit adds: register
a page of title memory, take the submission's snapshot, let a shader write one
byte into the copy, `unregister` and `VirtualFree` the range, take the same
addresses again with `VirtualAlloc` and fill them with 0xEE, then run the
copy-back. Before the change that byte is 0x99 - the shader's - inside the
title's new allocation:

    left: 153   (0x99: what the shader wrote for a submission that is over)
    right: 238  (0xEE: what the title's next use of the address held)

`Shadow` now carries a flag that `unregister` sets, and `copy_back_or_not`
returns before touching anything once it is set: a copy whose title buffer is
gone writes nothing back, and stays alive for the lists that still hold it - its
own bytes are the lists' to use, the title's memory is not.

    cargo test -p victory-gpu --lib --profile diag --features diagnostics
    245 passed, 2 failed, 1 ignored
    (the 2 are the FIND-9 view-heap pair, which is Marvisak#2937's, not this commit's)
    cargo clippy -p victory-gpu --all-features -- -D warnings: clean

Whether this is the mechanism behind Marvisak#2025's intermittent corruption is not
claimed: it is one way stale shader bytes reach re-used title memory, and Marvisak#2025
was AMD and intermittent. What it gives Marvisak#2025 is a reproduction of the class on
any host, with no game.
@pickles976

Copy link
Copy Markdown

Verified ordinary path; remaining stale write through marked-page path. Exact runtime head 0014e65fa78ea59d9418da3b4f89d4d7937616a7, RTX 4060 Laptop GPU 8 GiB / 16 GiB RAM, Linux + Wine 11.0 / vkd3d-proton 3.2.0 / NVIDIA 590.48.01.

Local test-only changes: require host buffer/mark allocation (no GPU skip), request the exact freed address with VirtualAlloc(p, ...) and assert it was returned, then exercise both the original ordinary copy-back and a marked-page variant. No production source changes. Fresh Windows-MSVC test build from this checkout; one test thread; actual NVIDIA adapter enumerated. Result:

marked=false, reused=0x7ffffefe0000, byte24=0xee  PASS
marked=true,  reused=0x7ffffefe0000, byte24=0x99  FAIL
left: 153
right: 238
1 passed; 1 failed; 0 ignored

The marked case uses the actual copy_back_marks(&[], false) dispatcher, not just a direct call to the leaf function:

  1. pool(1) / register / find (required host allocation) / copy.update(p, PAGE).
  2. copy.writing(p, 64, true); guest byte p+32 = 0x44 to fault/save the pre-write page used by marked merging.
  3. base = copy.marks.unwrap(); set that page bit in bitmap(false) using the same fixture technique as marks_of_shaders_using_title_memory_are_held_back.
  4. copy.write_host(p+24, &[0x99]) to simulate the shader's changed byte.
  5. unregister(p, p); assert VirtualFree(p, 0, MEM_RELEASE) succeeds.
  6. q = VirtualAlloc(p, PAGE, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE); assert q == p; fill the entire new allocation with 0xEE.
  7. copy_back_marks(&[], false); byte24 becomes 0x99, not the required 0xEE. The stale Arc<Shadow> remains alive, as a pending list may hold it.

Root: the new gone gate is only in copy_back_or_not. The live weak-owner registry can still upgrade this shadow in copy_back_marks, which calls copy_back_marked; that function never checks gone. The normal host submission calls marked copy-back before ordinary copy-back, so the latter returning zero cannot protect the newly reused memory. Relevant head locations: shadow.rs:503-544, 938-968; host.rs:1389-1405.

Suggested fix: include marked-page writes in the same retirement/lifetime protocol; add this marked remap test alongside the existing ordinary one. A separate source-review concern, not concurrency-tested here: a single pre-write atomic check does not serialize an unregister/remap that happens after that check. Retirement needs a shared exclusion/generation protocol covering validation through the guest write, with consistent lock ordering; switching Relaxed to SeqCst alone would not close that interleaving. Preserve snapshot/pending cleanup when suppressing writes too (the new early return bypasses it until shadow destruction).

Command through local Wine runner: cargo test --locked --target x86_64-pc-windows-msvc -p victory-gpu --lib a_pending_copy_back -- --nocapture --test-threads=1. Local log verify-pr3036-wine-retired-copyback.log; the marked variant is a_pending_copy_back_marked_after_reuse in local VIctory-pr3036/. These are real host buffers and simulated shader writes/mark bits, not GPU shader execution, an AMD reproduction, or a gameplay result. No title assets used. AI-assisted verification and report: OpenAI Codex.

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

LGTM — real stale-write hazard closed: pending copy-backs held Arc'd shadows that still wrote through the released range's address. gone is set in unregister and short-circuits copy_back_or_not; the test replays VA reuse and asserts the new owner's byte survives. Graceful skip without a GPU and on non-reuse.

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

Good catch on suppressing stale write-backs after a buffer is unregistered, but there are a few issues in crates/victory-gpu/src/shadow.rs:

  1. Early return leaks snapshot buffers and leaves pending / armed state stuck (shadow.rs:418-420, 478-488):
    Returning 0 at the top of copy_back_or_not bypasses pending.remove(&(address, address + len)), compared.clear(), segments.drain(..) -> give_back(bytes), and t.disarm(). Because Arc<Shadow> remains alive as long as command lists reference it, those snapshot buffers stay pinned out of the pool and the tracker remains armed. Gate only the write-back branch (e.g. back && !self.gone.load(Ordering::Acquire)) so cleanup at lines 478–488 always runs, just like keep_writes.
  2. Other title-memory write-back paths on Shadow are uncovered (copy_back_page at shadow.rs:208, copy_back_marked at shadow.rs:503):
    • copy_back_marks (shadow.rs:926-956) upgrades Weak<Shadow> from MARKS.owners, which still succeeds while any command list holds Arc<Shadow> after unregister, and then calls copy.copy_back_marked(page).
    • memory.rs:690 iterates copies[k] captured before submission and calls copies[k].copy_back_page(at as usize).
      Both paths also write back to title memory via crate::host::write_mapped and should check self.gone (and copy_back_marked should still drop any saved bytes / avoid leaving stale armed state when gone).
  3. Non-deterministic regression test (shadow.rs:1690-1732):
    VirtualAlloc(std::ptr::null(), len, ...) at line 1709 is not guaranteed to reuse p, and lines 1713–1721 return early without failing whenever q != p — so the test can silently skip copy.copy_back(p, 64) and the assert_eq!(after, 0xee) check. Passing p as *const _ as the preferred address (or also testing directly on p while still mapped after unregister, verifying both that bytes stay untouched and that pending/snapshots are drained) would make it deterministic.
  4. Minor: Prefer Ordering::Release in unregister (shadow.rs:1024) and Ordering::Acquire in the copy-back checks for cross-thread visibility, and remove the unexplained (FIND-14) reference in the comment at line 417.

@pawrenity

Copy link
Copy Markdown

FIND-14: side-by-side check of #3036 and #2612

Hardware: NVIDIA GeForce RTX 4070, Windows 11 (native D3D12, MSVC). Base: origin/main 63bcca4, which is the merge base of both PRs. All test runs below used --locked --lib on victory-gpu, with every targeted test run alone under --test-threads=1. No title data was used.

In the cross-tests I added x_ tests to the shadow.rs test module. Their "no host GPU" early returns (and #3036's "address not reused" return) panic instead of returning, so a pass always means the assertion actually ran. The tests:

#3036 #2612
Head 0014e65 8a998fc
Own tests on head 1/1 pass 6/6 pass
Full victory-gpu lib 230 pass. 2 fail, the known NVIDIA view-heap pair (also failing on main) 235 pass. Same 2 known failures
Own test fails on main (test only) yes: R1 gives 0x99, expected 0xEE yes: M1 and M2 fail (the other 4 need #2612's APIs)
Negative control n/a Disabling the recheck in watch::write_back fails all 3 pause-and-remap tests
R1 (release, then reuse; ordinary path) pass fail (0x99)
R2 (release, then reuse; marked path) fail (0x99) fail (0x99)
R3 (release, then reuse; copy_back_page) fail (0x99) fail (0x99)
M1/M2 (remap reported while the buffer is still registered) fail (both) pass
K (release without free) fail: byte dropped (0x00, expected 0x99) pass
clippy -D warnings, all targets and features clean (victory-gpu) clean (victory-gpu, victory-hle). victory-hle xmem tests: 14 pass
Merges onto origin/main clean clean. #3036 and #2612 conflict with each other in shadow.rs

#3036: defects

  1. Only copy_back_or_not checks gone (shadow.rs:418). The marked path (copy_back_marked, shadow.rs:503, reached through copy_back_marks) and copy_back_page (shadow.rs:208) still write into the reused memory (R2 and R3). This confirms the marked-path report already posted on this PR, now on native Windows.
  2. The fix keys on the release of a buffer object (unregister), not on the memory. A remap under a buffer that is still registered is not covered (M1/M2 fail). Remaps come from XMemMapPhysicalPages, map_alias and title_memory_remapped. The fix also has no notion of a partial range: one release suppresses the whole copy.
  3. A behaviour change: releasing a buffer whose memory stays live now drops that submission's shader writes (K: main writes 0x99, GPU: a copy-back still pending when the title takes the range back writes nothing #3036 leaves 0x00). Main's comment on unregister says lists that still hold the copy keep it alive. I have not verified whether titles release buffers this way while a submission is pending.
  4. (From reading the code only; not reproduced.) gone is loaded once, Relaxed, before the copy-back starts. An unregister followed by a free after that check, but before write_mapped, is not excluded. The early return also skips pending.remove, give_back of the snapshot and disarm (shadow.rs:479 onward) until the Shadow drops.

#2612: defects and gaps

  1. Coverage is limited to memory changes that are reported through title_memory_remapped. A free followed by reuse that nobody reports gets no protection on any path (R1, R2 and R3 fail). (From reading the code only): XMemFreeDefault (xmem.rs:334) and XMemVirtualAlloc (xmem.rs:87) do not report, so this applies to an XMemFree followed by a new allocation at the same address. This is the same gap already raised for XMemVirtualAlloc on this PR.
  2. (From reading the code only; not a correctness defect.) copy_back_or_not inlines a copy of merge_writeback (shadow.rs:457). It is equivalent, but writeback_merge_matches_bytewise_oracle no longer covers it, which the maintainer triage already asked to revert. write_back and Tracked::taken lock MAPPING without re-entry, so neither may be reached while a Remapping guard is held. I found no such path, but the invariant is not documented.
  3. It handles both a partial-range remap and a race between copy-back and remap. Remapped state is kept per page, so the other pages still write back (M1 asserts this). The write is rechecked under MAPPING, which the remap paths also take, and the negative control above shows the three pause-and-remap tests depend on that recheck.

Recommendation
On this evidence, #2612 is the stronger base. It covers all three copy-back paths for remaps that are reported, handles partial ranges, and serialises the write against the remap. #3036 covers only the ordinary path, misses remaps, and drops legitimate writes when a buffer object is released while its memory stays live (K). Neither PR closes a free followed by reuse that is never reported (R2 and R3 fail on both). The narrowest way to close it seems to be reporting frees and new allocations from XMemFree / XMemVirtualAlloc through title_memory_remapped, which would put them on #2612's existing gate. That suggestion is untested. I would not merge #3036 as it stands. Its test (R1, with the early returns turned into panics) is useful and could be added to #2612 together with such a report.

AI-assisted (Claude Code).

LAKSHYA-cmd-tech added a commit to LAKSHYA-cmd-tech/VIctory that referenced this pull request Nov 26, 2026
…watch-and-file-sharing

GPU, HLE: guard pending shadow copy-backs on buffer release and share DirectStorage file opens (Marvisak#3036, Marvisak#3018)

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

A Windows 10 data point on whether the test observes the hazard, since it returns early when the address isn't reused: RTX 3080, Windows 10 22H2, a_pending_copy_back_does_not_write_into_memory_the_title_took_back run alone 10 times each.

address reused result
this PR (0014e65) 10/10 10/10 pass
same test with the gone check removed (= main's behaviour) 10/10 10/10 fail, left: 153 (0x99), right: 238 (0xEE)

So on Windows 10 too, VirtualAlloc(null, ...) returns the freed address every time and the test catches the stale write. This doesn't change the open points above (the marked and copy_back_page paths, and the cleanup the early return skips).

ashrafsdrop pushed a commit to ashrafsdrop/VIctory that referenced this pull request Nov 26, 2026
Memory the title frees with XMemFree (no hook) or XMemFreeDefault and gets
back from the next allocation at the same address was never reported to
title_memory_remapped: the host heap hands out a freed block again without
a word. A copy-back still pending for the freed memory then put the shaders' bytes into
the new memory, on all three paths (a declared range's snapshot, a marked
page, a page at a computed address). Committed resources get their memory
from XMemAlloc too, and give it back through XMemFree when released.

XMemFreeDefault now reports the memory as remapped before it frees it,
holding the mapping lock (title_memory_remapping) across the report and the
free, as Upload's drop does:
- a 32-bit block: its whole reservation, walked region by region (guards
  and protection changes split it);
- a heap block: only the host pages it fills. Its first and last page may
  hold other blocks of the heap, still in use; a block inside one page
  reports nothing, so small frees cost nothing.

Not covered: a title allocator hook (__XMemAllocationHooks__) frees and
reuses memory we do not see, and so do the host's VirtualFree and
NtFreeVirtualMemory. XMemFreePhysicalPages needs no report: freed pages
stay shown by their views until unmapped, and unmapping reports.

Tests: freed_memory_is_reported_to_the_gpu_side (xmem) checks each range
reported; memory_freed_and_allocated_again_keeps_the_new_bytes_once_reported
(shadow, WARP) frees and reallocates a three-page copy at the same address
while each copy-back path is pending. Reported, all three keep the title's
new bytes and the next refresh takes them; unreported (the control), the
shaders' bytes land in the new memory on all three.

This commit also adds host::tests::no_submission, so that parallel
submissions cannot take the marks the test sets.

Thanks to pawrenity's comparison of Marvisak#2612 and Marvisak#3036 for the free-and-reuse
case.

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

Copy link
Copy Markdown

One way to close the K case (release without free) and the marked-path report above, tried in another tree (Windows 11, RTX 3080 Ti, cargo test -p victory-gpu --lib passes, 329 tests, with and without GPU upload heaps).

  • Set gone where memory is freed, not in unregister: Memory's Drop (committed resources and heaps) and the upload block's Drop before VirtualFree call freed(start, len). Releasing a placed or title-mapped resource then still writes back.
  • unregister keeps a Weak of the released copy in a second map, so a heap freed after its placed resources' objects still finds their copies.
  • freed also marks the single-view copies in the range (EXACT) and removes them, so the next buffer at those addresses does not pick up a quiet copy.
  • Check the flag in the compare step shared with the per-page copy-back and at the top of the marked-page run, and treat copy_back_or_not as keep_writes when set, so pending ranges and snapshots are still released.

Tests there: a pending ordinary copy-back after free and reuse writes nothing; a marked page writes nothing (without the check it wrote 65536 bytes into the freed page); a release whose memory stays still writes back; a view copy of freed bytes is marked and the next view gets a new copy.

Not covered: a remap under a still registered buffer (M1/M2 above), memory the title unmaps itself, a copy-back already under way when the memory is freed, and there is no test that goes through a real placed-resource heap release. The tree differs from this branch (its marked path is organised differently), so this is a description rather than a patch. No title data in the tests.

AI assistance: written and tested with Claude Code.

ashrafsdrop pushed a commit to ashrafsdrop/VIctory that referenced this pull request Nov 26, 2026
Memory the title frees with XMemFree (no hook) or XMemFreeDefault and gets
back from the next allocation at the same address was never reported to
title_memory_remapped: the host heap hands out a freed block again without
a word. A copy-back still pending for the freed memory then put the shaders' bytes into
the new memory, on all three paths (a declared range's snapshot, a marked
page, a page at a computed address). Committed resources get their memory
from XMemAlloc too, and give it back through XMemFree when released.

XMemFreeDefault now reports the memory as remapped before it frees it,
holding the mapping lock (title_memory_remapping) across the report and the
free, as Upload's drop does:
- a 32-bit block: its whole reservation, walked region by region (guards
  and protection changes split it);
- a heap block: only the host pages it fills. Its first and last page may
  hold other blocks of the heap, still in use; a block inside one page
  reports nothing, so small frees cost nothing.

Not covered: a title allocator hook (__XMemAllocationHooks__) frees and
reuses memory we do not see, and so do the host's VirtualFree and
NtFreeVirtualMemory. XMemFreePhysicalPages needs no report: freed pages
stay shown by their views until unmapped, and unmapping reports.

Tests: freed_memory_is_reported_to_the_gpu_side (xmem) checks each range
reported; memory_freed_and_allocated_again_keeps_the_new_bytes_once_reported
(shadow, WARP) frees and reallocates a three-page copy at the same address
while each copy-back path is pending. Reported, all three keep the title's
new bytes and the next refresh takes them; unreported (the control), the
shaders' bytes land in the new memory on all three.

This commit also adds host::tests::no_submission, so that parallel
submissions cannot take the marks the test sets.

Thanks to pawrenity's comparison of Marvisak#2612 and Marvisak#3036 for the free-and-reuse
case.

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

Copy link
Copy Markdown
Owner

Automated triage for the maintainers.

The test is a useful reproduction of FIND-14, but the fix in crates/victory-gpu/src/shadow.rs is incomplete, and it changes behaviour that main relies on:

  • The gone flag is checked only in Shadow::copy_back_or_not. Shadow::copy_back_marked, which is reached through copy_back_marks, and Shadow::copy_back_page still write through the old address. The marked path runs before the ordinary copy-back on a host submission, so a reused page can still get the stale bytes. The two verification comments above reproduce this.
  • The early return skips the cleanup at the end of copy_back_or_not. That cleanup does pending.remove, give_back of the snapshot segments and Tracked::disarm. Snapshots stay held until the Shadow drops. If the copy-back must be suppressed, it should still go through the keep_writes path (back = false) so this state is released.
  • unregister now sets gone when the buffer object is released, not when its memory is freed. On main, unregister documents that "lists that still hold its copy keep it alive". With this change, a release whose memory stays mapped (for example a placed or aliased resource) loses that submission's shader writes.
  • GPU: skip pending copy-backs and clear saved snapshots on remapped pages #2612 covers the same finding (FIND-14) on all three copy-back paths for reported remaps, and the two PRs conflict in shadow.rs. Please coordinate with it. One option is to move this PR's test there, together with a report of frees and reallocations.

What would change the verdict: set the flag where memory is actually freed, or route it through title_memory_remapped; gate the marked and per-page paths too; keep the pending and snapshot cleanup; add the marked-path variant of the test.


Generated by Claude Code

@HoLa-Lee

Copy link
Copy Markdown
Author

Closing in favour of #2612, and all three review points are right.

  • gone covers one of three paths. copy_back_marked (through copy_back_marks) and copy_back_page write through the old address too, and the marked path runs first on a host submission - @pickles976 reproduced exactly that (marked=true), and it is the same hole.
  • The early return skips the cleanup (pending.remove, the snapshot's give_back, Tracked::disarm), so snapshots stay held until the Shadow drops. Suppression has to go through the back = false path, not around it.
  • unregister is the wrong hook. It fires when the buffer object is released, and main documents that "lists that still hold its copy keep it alive" - so a placed or aliased resource whose memory stays mapped loses that submission's shader writes. The flag belongs where memory is actually freed.

#2612 does the first and third at the right place (the runtime's title_memory_remapped), which is why it should land and this should not: two fixes for one finding, conflicting in shadow.rs, is worse than one.

What this PR has that #2612 does not, and I have handed over rather than dropped: the reproduction. On #2612's own head 4f47bdc it fails -

left: 153   (0x99 - the shader's byte from a submission that is over)
right: 238  (0xEE - what the title's next use of the address held)
  • because a release and re-take of the same addresses is not a remap and never reaches title_memory_remapped. That is the gap the triage calls "keep the pending and snapshot cleanup ... route it through title_memory_remapped" and @Machad3x calls the K case; the test is now offered on GPU: skip pending copy-backs and clear saved snapshots on remapped pages #2612 with the exact bytes and the trigger, and its author can take it as-is or have it as a separate test-only PR against main.

Thanks to @pickles976, @pawrenity, @Machad3x and the triage for three independent reproductions of the same hole - the honest outcome is one fix, and #2612 is it.

@HoLa-Lee HoLa-Lee closed this Nov 26, 2026
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.

8 participants