Skip to content

D3D12.X: sparse readbacks don't wait for a queue held by a later signal - #433

Open
Kalmarv wants to merge 1 commit into
xcl-dev:mainfrom
Kalmarv:fix/sparse-readback-without-cpu-wait
Open

Kalmarv wants to merge 1 commit into
xcl-dev:mainfrom
Kalmarv:fix/sparse-readback-without-cpu-wait

Conversation

@Kalmarv

@Kalmarv Kalmarv commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

After a title's ExecuteCommandLists whose lists write sparse windows on the GPU (Write32/64BitValue…X, FillMemoryWith32BitValueX, CopyMemoryToMemoryX), sparse::readback_after_execute copies those bytes back to the CPU's view. It waited on the CPU for the title's queue to get there, inside the title's call and while holding the sparse lock. A queue may GPU-wait for a fence that a later submit signals; async compute does this. The wait then never ends, the later submit never comes, and every other submit stops at the sparse lock. Part of #262, which covers the other half of the sparse windows' cross-queue problem: the CPU-write uploads.

What is in it

  • crates/xcl/src/hle/d3d12x/sparse.rs:
    • The copy back is recorded on the title's queue after its lists: a list of that queue's type, copying into a readback buffer of its own. That queue then signals a fence of its own.
    • The copy is still waited for in the call, as on main, so the bytes are in the CPU's view when the title's own fence after that work completes. Two exceptions hand it to a worker thread, which lands it once the GPU gets there, in submission order:
      • the queue has a wait that hasn't completed, so it may be held by a later submit;
      • an earlier copy back of that queue hasn't landed yet.
    • The stale-read window this opens exists only where main hangs.
    • The rb_fence that all title queues signalled is gone. Its values could complete out of order across queues.
    • A copy back's buffer and list stay alive until its fence has reached the value. Its fence exists before the copy is submitted, and if the Signal fails they are never released (from review).
    • A noted wait is kept only while it hasn't completed: a queue's completed waits go when it is given the next one, and it keeps one entry per fence, the highest value (from review).
  • crates/xcl/src/hle/d3d12x/real.rs: the queue's Wait is noted, both from the PC method (a new override) and from the console's queue slots. XCL's own waits, made inside its own uploads, are not noted. A queue the title releases has its noted waits forgotten (sparse::forget_queue from q_release).
  • Comparison with cpu_writes.rs: it does bottom-of-pipe writes outside unified memory always on a worker, after the GPU. So there a CPU read right after the title's fence wait can always see the old value, and the worker writes anyway after 10 s. This PR keeps that window to the case where main hangs.
  • Tests in crates/xcl/tests/, each in its own process, with the device adopted as the title's:
    • sparse_readback_waits.rs: queue A waits for F, runs a list writing 8 bytes of a sparse window, and is read back; queue B then submits and signals F. A must finish within 5 s, and the bytes must land.
    • sparse_readback_lands.rs: 20 times, a list writes 8 bytes, the title waits for its own fence and reads them at once.
  • Unit test noted_queue_waits_stay_one_per_fence in sparse.rs: 1,000 waits on one fence keep one entry, a second fence makes two, completed waits go, a released queue has none. It fails without the bound (1,000 entries).

Tested

3 runs each main 9ab7d76 every copy back on the worker (first version) this PR (19004e1)
cargo test -p xcl --test sparse_readback_waits hangs 3/3 — passes 3/3
cargo test -p xcl --test sparse_readback_lands passes 3/3 fails 3/3 (old bytes in round 0) passes 3/3
  • hle::d3d12x::sparse::tests, inside the whole suite on c20dd22: 15 passed, 1 ignored.
  • cargo test --workspace -- --test-threads=4:
  • Independent run by @nullmarsh (D3D12.X: sparse readbacks don't wait for a queue held by a later signal #433 (comment)): AMD Radeon RX 9060 XT (RDNA4, driver 32.0.32029.2010), Ryzen 7 5800X3D, Windows 11 26200, Rust 1.100.0, debug, 7709697 merged onto main a6f5f7a. scripts/test.ps1: 0 failed, no SKIPPED GPU tests; both new tests pass. With real.rs and sparse.rs back on main, a_readback_behind_a_wait_for_a_later_signal_does_not_hang fails after 5.4 s.
  • Regression run by @srcamarda (D3D12.X: sparse readbacks don't wait for a queue held by a later signal #433 (comment)): AMD Radeon RX 7800 XT (RDNA3, driver 32.0.32029.2010), Ryzen 5 5600G, 32 GB, Windows 11 Pro 26300, release builds, scripts/smoke.ps1 -Seconds 90, each binary run twice. main 508a0c7: 2343 / 2361 frames, peak commit 15764 / 15674 MB. This PR at 7184866: 2356 / 2383 frames, peak commit 16491 / 16373 MB. No crash or device removal in any run. He puts the higher peak commit down to that head's base, 9ab7d76, 55 commits behind main; c20dd22 is on b7aa9f3.
  • Independent run by @TheHoracio (D3D12.X: sparse readbacks don't wait for a queue held by a later signal #433 (comment)): AMD Radeon RX 7800 XT (RDNA3, driver 32.0.32015.7029), debug, 7709697 on 9ab7d76. cargo test --workspace --no-fail-fast -- --test-threads=4: 653 passed, 0 failed, 40 ignored, no SKIPPED GPU tests; both new tests pass.

Regression run

Our own runs, one after the other on the machine under Tested (RTX 5070 Ti, AMD Ryzen 9 9950X), release builds, no uncommitted changes: main at b7aa9f3 (this PR's base), then this PR's head. 98 % of main's frames, 101 % of its peak commit.

main:

xcl-smoke v1
commit: b7aa9f3bd212088e0d927439284dc5ed325ce3c7
gpu: NVIDIA GeForce RTX 5070 Ti
title: ea3b5e4d
seconds: 60
exit: 0x0
frames shown: 1320 (PresentX 1321)
presents per 2 s (last 3): 35 35 53
device removals: 0
crashes: 0
peak commit: 27047 MB

PR:

xcl-smoke v1
commit: c20dd224f1487b5dfa982df8ac157b1a6c17f8ba
gpu: NVIDIA GeForce RTX 5070 Ti
title: ea3b5e4d
seconds: 60
exit: 0x0
frames shown: 1299 (PresentX 1300)
presents per 2 s (last 3): 38 39 30
device removals: 0
crashes: 0
peak commit: 27293 MB

Not tested

  • Whether the title reaches the readback path in the smoke runs above: not checked.
  • A queue whose earlier wait hasn't completed still gets the asynchronous copy, as does any queue with an unlanded copy, even when nothing would have hung. A CPU read right after the title's fence wait can then see the old bytes, until the worker lands them.
  • One worker lands copies in submission order, so a long-held queue delays the landing for other queues. cpu_writes has the same property.
  • A readback buffer and a command list are made per readback submit; there is no pooling.

Size: 499 changed lines (+457 / -42), 245 of them tests. Over the ~400 target because of the tests: the fix and its review changes are about 250 lines in two files, and splitting the tests from the fix would leave the fix without the test that shows the hang.

AI use

  • Claude Code, Claude Opus 5.5: the code, the tests, the runs and this description.

🤖 Generated with Claude Code

@ghost

ghost commented Nov 24, 2026

Copy link
Copy Markdown

AMD run, since Not tested lists AMD: 7709697 merged onto main a6f5f7a (clean merge): pass on RDNA4, and the hang test fails without the real.rs / sparse.rs changes.

Tested

  • AMD Radeon RX 9060 XT (RDNA4), driver 32.0.32029.2010; Ryzen 7 5800X3D; Windows 11 Pro 26200; Rust 1.100.0; DXC 1.9.2602.17; debug build.
  • .\scripts\test.ps1: passes, 0 failed; no SKIPPED GPU tests.
  • cargo test -p xcl --test sparse_readback_lands --test sparse_readback_waits: both pass. XCL_REQUIRE_GPU=wave64,mesh cargo test -p xcl --lib sparse: 13 passed, 1 ignored (early_commit_timing).
  • Negative control: the merged tree with real.rs and sparse.rs back on main, new test files kept. a_readback_behind_a_wait_for_a_later_signal_does_not_hang fails after 5.4 s with queue A did not finish in 5 s: the readback waits on the CPU for A, which waits for B's later submit. gpu_writes_are_there_when_the_titles_fence_completes passes either way.

Not tested

  • A retail title (smoke.ps1); NVIDIA.

AI use

  • Claude Code (Claude Opus 5.5) ran the commands and wrote this report from the logs; I checked it before posting.

@TheHoracio

TheHoracio commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Test report on AMD RDNA3: RX 7800 XT (16 GB), driver 32.0.32015.7029, Ryzen 7 9800X3D, Windows 11 Pro 10.0.26300, Rust 1.100.0 MSVC, DXC 1.9.2602.17, debug build. No retail data was used.

Tested: the PR head 7709697 as it is (on its base 9ab7d76, not merged onto current main).

  • cargo build --workspace, then cargo test --workspace --no-fail-fast -- --test-threads=4: 653 passed, 0 failed, 40 ignored, no SKIPPED tests.
  • Both new tests pass: a_readback_behind_a_wait_for_a_later_signal_does_not_hang (sparse_readback_waits) and gpu_writes_are_there_when_the_titles_fence_completes (sparse_readback_lands). The suite did not hang.

Not tested: a regression run on a title, a release build, and the head merged onto current main.

AI use: Claude Code ran the commands and drafted this comment; the runs are real runs on the hardware above.

@Cattn

Cattn commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

From a static review (no builds or runs) of 7709697:

readback_on submits the copy before creating or signaling its fence. If either operation fails, the early return drops the readback buffer and command allocator while the GPU may still be using them. In land, SetEventOnCompletion can fail and let execution reach Map and copy back while the fence is still pending. These are GPU-ordering and resource-lifetime bugs, and I found no indication of malicious code.

Keep the submitted resources alive until GPU completion is confirmed, and require that confirmation before copying back.

super::title_textures::own_work(|| queue.ExecuteCommandLists(&[Some(l)]));
let q = queue.as_raw() as usize;
if !self.rb_fences.contains_key(&q) {
let f: ID3D12Fence = self.dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?;
self.rb_fences.insert(q, (f, 0));
}
let (fence, value) = self.rb_fences.get_mut(&q)?;
*value += 1;
queue.Signal(&*fence, *value).ok()?;
Some(Readback { queue: q, fence: fence.clone(), value: *value, buf, parts, _list: (alloc, list) })

unsafe fn land(&self) {
use windows::Win32::System::Threading::{CreateEventW, WaitForSingleObject};
if self.fence.GetCompletedValue() < self.value {
let Ok(event) = CreateEventW(None, false, false, None) else { return };
while self.fence.GetCompletedValue() < self.value && self.fence.SetEventOnCompletion(self.value, event).is_ok() {
WaitForSingleObject(event, 10_000);
}
let _ = CloseHandle(event);
}
let mut p = std::ptr::null_mut();
if self.fence.GetCompletedValue() == u64::MAX || self.buf.Map(0, None, Some(&mut p)).is_err() {
return;
}
if let Some(s) = STATE.lock().unwrap().as_mut() {
s.copy_back(p as *const u8, &self.parts);
}
self.buf.Unmap(0, None);

Review by Claude Code (Claude Opus 5.5) with a gpt-6.2-sol audit subagent; I checked each point against the code.

Kalmarv added a commit to Kalmarv/xcl that referenced this pull request Nov 24, 2026
After a title's ExecuteCommandLists whose lists write sparse windows on the
GPU, readback_after_execute made XCL's queue wait for the title's queue
(through one rb_fence shared by all title queues) and then waited on the CPU
for the copy, inside the title's call and under the sparse lock. A queue may
GPU-wait for a fence that a later submit signals (async compute): the CPU
wait then never ends, and the later submit never comes. Values of the shared
fence signalled from several queues could also complete out of order.

The copy back is now recorded on the title's queue after its lists (a list of
the queue's type, into a readback buffer of its own), followed by a signal of
a fence of that queue's own. It is still waited for in the call, so the bytes
are in the CPU's view when the title's own fence after the work completes -
unless a wait the queue was given has not completed (Wait is noted, from the
PC method and from the console's queue slots; XCL's own waits are not), or an
earlier copy back of that queue is not landed yet. Then a worker thread lands
it, in submission order, once the GPU is there.

The fence exists before anything is submitted, and a copy back is landed
only once its fence has reached the value (looking again every millisecond
when there is no event to wait on), so its buffer and list live until the GPU
is done with them; if the Signal after the copy fails, nothing can tell when
it is done and they are never released (review on xcl-dev#433).

Tests (own processes, the device adopted as the title's):
- sparse_readback_waits: queue A waits for F, runs a list writing 8 bytes of a
  sparse window and is read back; queue B then submits and signals F. Main
  hangs (A not done after 5 s); here A finishes and the bytes land.
- sparse_readback_lands: 20 times a list writes 8 bytes, the title waits for
  its fence and reads them at once. Passes on main and here; fails in round 0
  when every copy back goes to the worker.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
@Kalmarv
Kalmarv force-pushed the fix/sparse-readback-without-cpu-wait branch from 7709697 to 7184866 Compare November 24, 2026 01:06
@Kalmarv

Kalmarv commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

Thanks, both points were right. They're fixed in 7184866, squashed into the PR's commit:

  • readback_on: the fence is now created before anything is submitted. If the Signal after the copy fails, nothing can tell when the copy is done, so the readback buffer and command list are deliberately leaked instead of released.
  • land: it returns only once the fence has reached the value, so the buffer is mapped and copied back only after the GPU is done with it. When SetEventOnCompletion fails, it now polls every millisecond instead of going ahead. CreateEventW failing had the same problem (it returned and dropped the buffer while the copy could still be pending), and it now polls the same way.

No test covers these paths: the failures of CreateFence, Signal, CreateEventW and SetEventOnCompletion can't be forced in a synthetic test. The existing tests and the whole suite were run again on the new head (see the description).

🤖 Claude Opus 5.5

@srcamarda

Copy link
Copy Markdown
Contributor

Regression run on a retail title, as asked under Regression run.

Tested

  • AMD Radeon RX 7800 XT (RDNA3), driver 32.0.32029.2010; Ryzen 5 5600G, 32 GB; Windows 11 Pro 26300; release builds
  • scripts/smoke.ps1 -Seconds 90, no input (the title stays on its account screen at 30 fps). Each binary was built from a clean checkout of its commit and run twice; the first run of each has a cold translation cache. Blocks below are from the second run.
  • main 508a0c7: 2343 / 2361 frames, peak 15764 / 15674 MB. This PR (7184866): 2356 / 2383 frames, peak 16491 / 16373 MB. No crash or device removal in any run.
  • This head is based on 9ab7d76, 55 commits behind main. Its peak commit is ~0.7 GB above main's here, most likely from the base: main's memory changes since then aren't in it. D3D12.X: the sparse state is replaced outside its lock #443 and D3D12.X: map a one-slice title texture's packed mips where D3D12 addresses them #470, both close to main, match main. A rebase would settle it.

Regression run

main:

xcl-smoke v1
commit: 508a0c74d7c0625d6d2de8d24494e69dc2e1926f
gpu: AMD Radeon RX 7800 XT
title: RetailGame_Dump
seconds: 90
exit: 0x0
frames shown: 2361 (PresentX 2361)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 15674 MB

this PR's head:

xcl-smoke v1
commit: 7184866fdc3821af42293f7296b0886b6cacb3ff
gpu: SudoMaker Virtual Display Adapter
title: RetailGame_Dump
seconds: 90
exit: 0x0
frames shown: 2383 (PresentX 2383)
presents per 2 s (last 3): 60 61 60
device removals: 0
crashes: 0
peak commit: 16373 MB

gpu: in this PR's block names a virtual display adapter: the head predates 97dc49c, which reads the adapter from report.json. XCL ran on the RX 7800 XT in every run.

Not tested

  • Whether this title takes the asynchronous readback path in these 90 s (the account screen) I did not check; the run is a regression check.
  • The whole test suite at this head (only the title runs).

AI use

  • Claude Code with Claude Opus 5.5 built both commits, ran the smoke runs and wrote this report; the runs are from my machine.

Kalmarv added a commit to Kalmarv/xcl that referenced this pull request Nov 24, 2026
After a title's ExecuteCommandLists whose lists write sparse windows on the
GPU, readback_after_execute made XCL's queue wait for the title's queue
(through one rb_fence shared by all title queues) and then waited on the CPU
for the copy, inside the title's call and under the sparse lock. A queue may
GPU-wait for a fence that a later submit signals (async compute): the CPU
wait then never ends, and the later submit never comes. Values of the shared
fence signalled from several queues could also complete out of order.

The copy back is now recorded on the title's queue after its lists (a list of
the queue's type, into a readback buffer of its own), followed by a signal of
a fence of that queue's own. It is still waited for in the call, so the bytes
are in the CPU's view when the title's own fence after the work completes -
unless a wait the queue was given has not completed (Wait is noted, from the
PC method and from the console's queue slots; XCL's own waits are not), or an
earlier copy back of that queue is not landed yet. Then a worker thread lands
it, in submission order, once the GPU is there.

The fence exists before anything is submitted, and a copy back is landed
only once its fence has reached the value (looking again every millisecond
when there is no event to wait on), so its buffer and list live until the GPU
is done with them; if the Signal after the copy fails, nothing can tell when
it is done and they are never released (review on xcl-dev#433).

Tests (own processes, the device adopted as the title's):
- sparse_readback_waits: queue A waits for F, runs a list writing 8 bytes of a
  sparse window and is read back; queue B then submits and signals F. Main
  hangs (A not done after 5 s); here A finishes and the bytes land.
- sparse_readback_lands: 20 times a list writes 8 bytes, the title waits for
  its fence and reads them at once. Passes on main and here; fails in round 0
  when every copy back goes to the worker.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
@Kalmarv
Kalmarv force-pushed the fix/sparse-readback-without-cpu-wait branch from 7184866 to 19004e1 Compare November 24, 2026 02:27
@upipibi upipibi mentioned this pull request Nov 24, 2026
@upipibi

upipibi commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

A small leak in 19004e1, found by reading the code (not run):

note_queue_wait (sparse.rs:1271-1276) pushes a Held(fence.clone(), value) for every title Wait that hasn't completed when it is called. It's called from q_wait (real.rs:4562) and from the console queue slot (real.rs:4669). Entries are only removed in may_be_held (:1279-1284), and that only runs from readback_after_execute when the same queue submits a sparse write. q_release doesn't clear the queue's entry either.

The usual cross-queue sync, computeQueue->Wait(graphicsFence, n) once per frame on a queue that never writes into a sparse window, or any title with no sparse windows at all (the note is taken before STATE is checked), adds one entry per frame for the whole run. Each entry keeps a COM reference on the title's fence, so the fence outlives the title's last Release. If that queue later does one sparse readback, retain walks the whole backlog under the WAITS lock.

Nothing crashes, but there's no upper bound. Possible fix: run the same retain in note_queue_wait before the push, drop the queue's entry in q_release, and skip the note while no sparse state exists.

AI-assisted (Claude Code), read-only review.

@juliptree

Copy link
Copy Markdown

Independent Windows validation on an RTX 5060 Ti (driver 616.92), Windows 11 build 26200, and Rust 1.100.0 MSVC. I ran both synthetic fixtures three times per revision, comparing PR head 19004e1 with base cb868b2. A separate probe verified the adapter selected by XCL’s device-creation path.

  • sparse_readback_waits: 3/3 passed on the PR, 0/3 on base. On the PR, Queue A completed within five seconds and the CPU read the expected bytes each time. On base, all three runs failed the fixture’s five-second queue assertion before the byte check. The processes exited after cleanup.
  • sparse_readback_lands: 3/3 passed on both revisions. All 20 immediate CPU reads per run matched the expected bytes.
    No skips or process timeouts. I copied the two unchanged fixtures into the base worktree. When Cargo stalled linking the base lands fixture, I built it with rustc --test against the base’s Cargo-built libraries. Synthetic coverage only. AI-assisted by Codex (GPT-6).

@bstillbstill

Copy link
Copy Markdown

Test report: 19004e1 with #533 on NVIDIA RTX 3090 Ti (Windows), retail title of #505. It builds and passes on current main; the readback stall the title hits on this machine is in the Map path, which this PR does not change.

Build: main 09940bb + #533 001e37d + this PR, merged locally (4dc8428). This PR conflicts with main in one place in sparse.rs: main added pub fn queue() between readback_after_execute's doc comment and the function, where this PR rewrote that comment. I kept main's queue() as it is and put this PR's comment back on readback_after_execute; no code lines were touched.

Result: compared with #533 alone (details and table in my comment on #533), the title went from an abort at 107.8 s to 118.8 s. The stall before the abort is the same kind, though: 5 × sparse: the queue has not reached fence value 39956 after 5 s (at 39951) from 93 s to 113 s. Thread dumps at 90 s and 105 s show:

  • one title thread in real::res_map → sparse::readback_now → State::readback_ranges → State::wait_for, holding STATE;
  • the title's submitting thread in q_execute_command_lists → sparse::before_execute / sparse::queue() → Mutex::lock_contended.

So the Map readback (readback_now) has the same problem this PR solves for readback_after_execute: it waits on the CPU, under the sparse lock, for a queue that may need a later submit.

I tried that locally: a change that lets readback_now wait for the GPU without STATE (own readback buffer and list; its unit test fails without it). On top of #533 + this PR, the title aborted at 109.7 s instead, and the stall moved, not away. Now the submitting thread itself waits in before_execute → State::upload_dirty (sparse.rs:1189, the ring wait) for the sparse queue, 6 × has not reached fence value 36294 after 5 s (at 36293) from 84 s. A res_release → forget_buffer thread waits on the lock behind it. With this PR, nothing makes the sparse queue Wait any more, yet it stops one value short for 25+ s. Just before, at 70 s, #795's cycle breaker logged six Write64 Signal … would close a GPU cycle (waiters=[q3]) – signalled on CPU, and presents went to 0 at 72 s. Local video memory was 14.9 of 24 GB and commit 31.8 GB, so the memory budget is not the reason. I don't know yet what holds the sparse queue's own work.

Tested

  • NVIDIA GeForce RTX 3090 Ti (driver 32.0.16.2101), Intel i9-13900K, 32 GB RAM, Windows 11 build 26300, Rust 1.100.0 MSVC.
  • cargo build --workspace && cargo test --workspace -- --test-threads=4 on 4dc8428 (debug): 723 passed, 0 failed, 41 ignored, including sparse_readback_lands and sparse_readback_waits; SKIPPED: gpu_geometry_wave32_prefix_count_over_a_mask, gpu_wave32_program_in_wave64_hardware (no wave64).
  • Title: two 300 s runs, scripted A presses. The first ended at 60.06 s in ntdll.dll, 57 ms after a scheduled thread dump, and is left out (see the D3D12.X: bound compute pipeline waits so slow compiles do not trip wa… #533 comment).

Not tested: this PR without #533; AMD / Intel; Linux.

Test runs, analysis and this comment by Claude Code (Claude Opus 5.5); I checked the logs it is based on.

@freemanovec

Copy link
Copy Markdown

Written by an AI agent (Claude Code, Claude Opus 5.5) on this account, from runs on this machine.

A Linux / RDNA3 data point where this PR removes a stall the title hits there. One run per configuration, so treat the times as indicative.

Setup: RX 7900 XTX, Mesa 26.3.1 RADV, CachyOS (kernel 7.3.5), Wine 11.22 (kernel write watches), vkd3d-proton v3.1 with #257's patch and dxil-spirv 53aac41 (#611), DXVK from Proton Experimental. XCL release, x86_64-pc-windows-gnu (llvm-mingw), XCL_NETWORK=0, XCL_LATE_RELEASE=0. Tree: main a1672ef + #867 + #871 + #684. The newer retail game (#505), A pressed until it loads the world.

What stalls without this PR (measured with local timing logs, not in any PR): under Wine #871 places the title's overflow graphics heaps in the sparse windows, so the small GPU-written counters there go through sparse::readback_after_execute. Each such readback of 8–16 bytes took 2.0–5.0 s (13 times ≥ 100 ms in one run, several ending at the 5,000 ms wait_for timeout) while holding the sparse lock, and title threads in real::res_map → sparse::readback_now waited up to 4.9 s for that lock (7 times). A thread dump at the abort showed the title's queue thread in readback_ranges and two title threads blocked on the lock.

With this PR (cherry-picked; the conflict with #867's fence wrapping resolved by hand: q_wait_pc unwraps the fence and notes the wait with the raw fence, queue slot 15 notes the raw fence too):

tree "GPU Loc Sig" abort (#505)
without #433 170 s, 174 s, 279 s (three runs; the last with timing logs)
with #433 539 s; no Wait64BitValueX CPU timeout, 81,003 draws / 16,384 dispatches with translated pipelines, 0 skipped

The abort still comes ~40 s after the first ListX #101 call, as described in #505, and no title thread was inside XCL at that point.

With #891 and XCL_PSO_WAIT_MS=50 added on top of this PR, two runs ended with amdgpu GPU page faults from vkd3d-proton's queue thread and compute ring resets (one then the device removed, 0x887A0005). Without #433 (two runs with #891) and without #891 (the 539 s run) there were no faults; I have not found which change the faulting work comes from.

Tests (release, Wine, headless gamescope): --test sparse_readback_waits 1/0/0, --test sparse_readback_lands 1/0/0; lib filters hle::d3d12x::sparse::, hle::xg::, hle::d3d12x::pso_async:: 20 passed, 0 failed, 1 ignored. No SKIPPED.

Not run: Windows, NVIDIA, the full suite on this tree, more than one run per configuration.

@requiemsnkrp

Copy link
Copy Markdown
Contributor

Test report: this PR on an NVIDIA RTX 3060 (Windows), retail title of #505. The sparse-queue stall is gone in this run; the run then ends in a device removal instead.

Build: main 384f7f7 + #605 (c3d350a) + #495 (3ae0841) + this PR (19004e1), merged locally. The one conflict in sparse.rs is the same as @bstillbstill's: I kept main's queue() and put this PR's comment back on readback_after_execute. Two test constructors that main added since (in sparse.rs's tests) still built a State with rb_fence / rb_value; I changed them to rb_fences: FxHashMap::default().

Tested

  • NVIDIA GeForce RTX 3060 12 GB (driver 621.24), Ryzen 5 5600X, 16 GB RAM, Windows 11 Pro 26200, Rust 1.100.0 MSVC, release.
  • cargo test --release -p xcl --test sparse_readback_waits --test sparse_readback_lands: both pass. cargo test --release -p xcl --lib d3d12x::sparse: 13 passed, 0 failed, 1 ignored. The full suite was not run on this tree.
  • Retail title, Series X profile, XCL_NETWORK=0 XCL_ACTIVITY=1 XCL_PSO_WAIT_MS=50, input by hand, one run each:
without this PR (Series S profile, device_type = "lockhart") with this PR (Series X profile)
sparse: the queue has not reached fence value … after 5 s 5 (169–189 s, the sparse queue stuck at 140865) 0
GPU queue.Wait … did not complete within 5000 ms 30 0
would close a GPU cycle 16 0
busiest activity (2 s) windows 5,313 and 4,781 dispatches, no removal 7,028 dispatches, then the removal
end +0x23cf683 at 220.0 s 0x887a0005 at 98.5 s

The two runs differ in the console profile as well (I had switched to Series S for the run without this PR and back to Series X for this one), so the table is not a clean A/B. On main 384f7f7 alone, Series X, the run before both ended with 0x887a0007 at 110.1 s; I no longer have its log to count these lines.

  • The last activity (2 s) window before the removal has 7,028 dispatches (0 presents, 23 submits); the windows before it have 13–154. The same burst shape @am-cob counted before the faults in Retail title 1.0.2.1: GPU hang / crash at +0x23cf683 when the story loads (RTX 3070 Ti) #675. Local video memory was 14.1 GB on this 12 GB card.
  • The removal comes 4.5 s after the first ListX #101, with three Wait64BitValueX … bridged to GPU queue.Wait (… prod=qNone …; wait-before-signal) lines 0.1 s before it.

Not tested: more than one run of this tree; the same profile with and without this PR; whether this PR plays any part in the device removal (the Series X run on main alone also ended in a removal).

AI use: Claude Code (Claude Opus 5.5) merged and built the tree, ran the tests, read the logs and wrote this report; the title runs were made by hand on my PC.

@thehollowedone

Copy link
Copy Markdown

I checked deferred readback order at 19004e1 on Windows 11, RTX 3080 Ti (621.35), Rust 1.99.1 MSVC. The offline workspace build and both stock sparse readback tests passed.

The scratch fixture queued two different writes to the same sparse address on one direct queue, each behind a separate fence value. Both readback submissions returned before either value was signaled. After the compute queue signaled the first value, the CPU view showed the first write while the second was still held. After the second signal it showed the second write. The fixture sampled under the sparse-state lock and passed in all three processes, with no device removal.

Synthetic coverage only. AI-assisted. Codex (GPT-6) extended the fixture and ran the tests.

@Ali-AbdulHadii

Copy link
Copy Markdown

An independent repro of this on Linux, and an alternative fix.

Setup: RTX 5080 (NVIDIA 620.73.04), proton-cachyos-slr Wine, vkd3d-proton master 30b0eb9 + the repo patch. XCL: a local branch of main 47efa2e (+ #640, #765, #172 and others, without this PR), retail title 1.0.2.1 in its world.

What happened: at ~150 s the whole process froze for ~28 s, until the title's watchdog (+0x23cf683). XCL's own activity log stopped too. In the crash dump, xcl-activity waits for the sparse lock in sparse::pool_bytes, and the title's submitting thread is in sparse::before_execute waiting for an upload slot (sparse: the queue has not reached fence value 54578 after 5 s, logged at 154, 159 and 164 s). It ran right after the fence bridge had released cross-queue Wait64 waits that the title's graphics and compute queues held on each other. That is the "queue held by a later signal" case this PR describes.

Alternative fix tried locally: readback_after_execute signals rb_fence on the title's queue and returns. A worker thread waits for that fence, without the lock, then makes the copy back under the lock, one readback after another, in order. XCL's sparse queue then never waits for a title queue. The cost is that the CPU copy lands just after the GPU work instead of before the title's ExecuteCommandLists returns. XCL_SPARSE_SYNC_READBACK=1 keeps the old way.

After: much rarer, not gone. In 12 runs since, 10 logged no sparse: the queue has not reached …, and 2 logged it 3–4 times (no whole-process freeze seen). So something else still fills the upload slots. I have no unit test for the worker yet.

Not tested: Windows, AMD, this PR's own approach.

AI use: Claude Code (Claude Opus 5.5) diagnosed this, wrote the local change and this text; the user approved posting it.

@maephisto666

Copy link
Copy Markdown

A retail data point for this PR and #262: retail title 1.0.2.1 on NVIDIA, with thread dumps of the stall. The PR's tests do what they say on today's main. On the title, the sparse lock-up still happens, through readback_now, which this PR doesn't change.

Setup

  • RTX 5090 (wave32 only), driver 32.0.16.2124; Ryzen 9 9950X3D; 64 GB; Windows 11 26100; Rust 1.100.0; release builds; XCL_NETWORK=0.
  • 19004e1 rebased onto main 47efa2e. One conflict, in the doc comment above readback_after_execute, where main added pub fn queue(); both are kept. Two State test fixtures added on main since then needed the same rb_fence/rb_value → rb_fences change the PR makes to the existing one.
  • The title runs also carry local patches that are not upstream: a DirectStorage page-array fix, D3D12.X: title texture reads outside the coherent window use the safe copy #751, and diagnostics (thread dumps 48 frames deep, a log line on each sparse wait_for timeout naming the queue's last operations). None of them change the sparse code's behaviour.

Tests (47efa2e + this PR)

  • cargo test -p xcl --test sparse_readback_waits: fails on main after 5.3 s, passes with the PR 3/3.
  • cargo test --workspace -- --test-threads=4: 743 passed, 0 failed, 41 ignored; SKIPPED gpu_geometry_wave32_prefix_count_over_a_mask and gpu_wave32_program_in_wave64_hardware (no wave64).

On the title (4 runs with this PR, 2 without, same inputs)

frames stop sparse queue stops at title watchdog (+0x23cf683)
main 168 s 41365 216 s
main + this PR 168 s 40130 216 s
main + this PR 194 s 46473 243 s
main + this PR 260 s does not stop 288 s

When it happens, the sequence matches the issue:

  1. A title Map goes to res_map → sparse::readback_now → readback_ranges → State::wait_for, which waits on the sparse queue while holding STATE. wait_for times out 3× at 5 s, and the activity log is silent for those 15 s.
  2. Then STATE stays held for good. Without the PR it is held by XMemMapPhysicalPagesScatter → kernelx::home_again → sparse::committed → map_tiles → UpdateTileMappings, in a kernel wait inside the D3D12 runtime/driver. With the PR, by the title's submit thread in q_execute_command_lists → title_textures::refresh → sparse::before_execute → upload_dirty, which loops on wait_for until the 64 MB ring has room.
  3. Waiting for STATE: the title's submit thread (nested q_execute_command_lists from texture::upload_batch → late_release::drain_known → sparse::queue), res_release → forget_buffer, xcl-late-release, and a DirectStorage worker (write_physical_pages). Nothing is submitted any more, and the title's watchdog ends it.

What the stuck operation was, from the timeout log in the 243 s run:

  • The queue stops at 46473, and the operation after that value is a read-back list (the readback_ranges flush). The 8 UpdateTileMappings and 2 upload lists before it completed.
  • The device is not removed (GetDeviceRemovedReason is Ok).
  • Per-queue marker fences (late_release): the sparse queue and two title queues are up to date; four title queues are behind, all at the same value.

So a plain copy list on XCL's queue, which has no Wait in it with this PR, does not complete while four title queues are held. I don't know yet why: the driver ordering the copy behind the held queues' use of the same reserved buffer, or those queues waiting on the sparse fence. A run that logs every queue's pending waits at the timeout got no data: the stall did not happen in that run (the 288 s one).

In the 288 s run the title slows to 8 → 1 presents per 20 s instead. In every run about 180 compute pipelines are built after world entry, single builds 43–148 s in the driver, and ~30 xcl-pso-* threads mostly wait their turn. That may be what shifts the timing.

Not tested: AMD; more runs to say how often the lock-up happens; the synthetic case of a copy on one queue reading a reserved buffer while another queue using it is held.

AI use: Claude Code, Claude Opus 5.5. It rebased the PR, ran the tests and the title runs, read the thread dumps and wrote this report. The runs were on the hardware above.

@Kalmarv
Kalmarv force-pushed the fix/sparse-readback-without-cpu-wait branch from 19004e1 to 83bb744 Compare November 24, 2026 15:20
Kalmarv added a commit to Kalmarv/xcl that referenced this pull request Nov 24, 2026
After a title's ExecuteCommandLists whose lists write sparse windows on the
GPU, readback_after_execute made XCL's queue wait for the title's queue
(through one rb_fence shared by all title queues) and then waited on the CPU
for the copy, inside the title's call and under the sparse lock. A queue may
GPU-wait for a fence that a later submit signals (async compute): the CPU
wait then never ends, and the later submit never comes. Values of the shared
fence signalled from several queues could also complete out of order.

The copy back is now recorded on the title's queue after its lists (a list of
the queue's type, into a readback buffer of its own), followed by a signal of
a fence of that queue's own. It is still waited for in the call, so the bytes
are in the CPU's view when the title's own fence after the work completes -
unless a wait the queue was given has not completed (Wait is noted, from the
PC method and from the console's queue slots; XCL's own waits are not), or an
earlier copy back of that queue is not landed yet. Then a worker thread lands
it, in submission order, once the GPU is there.

The fence exists before anything is submitted, and a copy back is landed
only once its fence has reached the value (looking again every millisecond
when there is no event to wait on), so its buffer and list live until the GPU
is done with them; if the Signal after the copy fails, nothing can tell when
it is done and they are never released (review on xcl-dev#433).

A noted wait is kept only while it has not completed: a queue's completed
waits go when it is given the next one, of the waits for one fence only the
highest value is kept, and a queue the title releases is forgotten. A queue
that waits every frame and never reads back otherwise kept one entry, and a
reference on the title's fence, per frame (review on xcl-dev#433).

Tests (own processes, the device adopted as the title's):
- sparse_readback_waits: queue A waits for F, runs a list writing 8 bytes of a
  sparse window and is read back; queue B then submits and signals F. Main
  hangs (A not done after 5 s); here A finishes and the bytes land.
- sparse_readback_lands: 20 times a list writes 8 bytes, the title waits for
  its fence and reads them at once. Passes on main and here; fails in round 0
  when every copy back goes to the worker.
- noted_queue_waits_stay_one_per_fence (unit): 1,000 waits on one fence
  keep one entry; fails without the bound.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
@Kalmarv

Kalmarv commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto main 930e8b4 as 83bb744 (one commit; whole suite on an RTX 5070 Ti: 754 passed, 0 failed, 41 ignored, 2 SKIPPED for no wave64). The smoke pair for this head follows in the description. Replies to the open points:

@upipibi (WAITS leak): fixed as you read it. note_queue_wait drops the queue's completed waits before adding one and keeps one entry per fence (the highest value); q_release forgets a released queue's waits. New test noted_queue_waits_stay_one_per_fence (1,000 frame-style waits on one fence leave one entry); it fails without the fix.

@requiemsnkrp, @bstillbstill: the merge conflicts you described (the doc comment above readback_after_execute, and the test constructors still using rb_fence/rb_value) are resolved in this head.

@bstillbstill, @maephisto666: the lock-up that remains goes through readback_now (res_map) and upload_dirty, which this PR doesn't change; it needs its own PR. maephisto666's note that the stuck operation is a read-back list on XCL's queue while four title queues are held is a good lead for that one.

@Ali-AbdulHadii (alternative fix): we keep this approach for two reasons. Titles read GPU-written sparse memory on the CPU as soon as their own fence after the work completes; with every copy back on a worker the bytes land later, and sparse_readback_lands (write, wait for the title's fence, read at once) fails in round 0 that way. And one rb_fence signalled from several title queues can complete out of order, so each title queue gets its own fence.

@freemanovec, @requiemsnkrp (faults / removal on Linux and with #891): what we checked: the readback buffer, allocator and list live until their fence completes, and we found no path that frees them earlier. One ordering change: the copy now runs on the title's queue, so a later tile unmap on XCL's queue is not ordered after it. On a held queue the copy can read a tile already unmapped, which D3D12 defines as zero (tiled resources tier 2); the title's own lists on that queue read the windows with the same ordering. What we can't tell: we have no RADV machine and didn't check what RADV does on such a read, and the reports have no faulting address. The amdgpu fault lines (VA, client) next to the XCL log, or a run of this head and of main with the same profile and XCL_DRED=1, would show whether a copy list from this PR was running.

AI use: Claude Code (Claude Opus 5.5)

@upipibi

upipibi commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

Checked 83bb744's note_queue_wait and forget_queue: this closes the WAITS point. Completed waits are dropped before each new one, there is one entry per fence (at the highest value), and a released queue forgets its waits. Keeping only the highest value can make may_be_held say "held" a little longer, while a lower wait on the same fence is already done but the higher one is not. That is the conservative side, so readbacks are never let through early. Read, not run.

AI-assisted (Claude Code).

After a title's ExecuteCommandLists whose lists write sparse windows on the
GPU, readback_after_execute made XCL's queue wait for the title's queue
(through one rb_fence shared by all title queues) and then waited on the CPU
for the copy, inside the title's call and under the sparse lock. A queue may
GPU-wait for a fence that a later submit signals (async compute): the CPU
wait then never ends, and the later submit never comes. Values of the shared
fence signalled from several queues could also complete out of order.

The copy back is now recorded on the title's queue after its lists (a list of
the queue's type, into a readback buffer of its own), followed by a signal of
a fence of that queue's own. It is still waited for in the call, so the bytes
are in the CPU's view when the title's own fence after the work completes -
unless a wait the queue was given has not completed (Wait is noted, from the
PC method and from the console's queue slots; XCL's own waits are not), or an
earlier copy back of that queue is not landed yet. Then a worker thread lands
it, in submission order, once the GPU is there.

The fence exists before anything is submitted, and a copy back is landed
only once its fence has reached the value (looking again every millisecond
when there is no event to wait on), so its buffer and list live until the GPU
is done with them; if the Signal after the copy fails, nothing can tell when
it is done and they are never released (review on xcl-dev#433).

A noted wait is kept only while it has not completed: a queue's completed
waits go when it is given the next one, of the waits for one fence only the
highest value is kept, and a queue the title releases is forgotten. A queue
that waits every frame and never reads back otherwise kept one entry, and a
reference on the title's fence, per frame (review on xcl-dev#433).

Tests (own processes, the device adopted as the title's):
- sparse_readback_waits: queue A waits for F, runs a list writing 8 bytes of a
  sparse window and is read back; queue B then submits and signals F. Main
  hangs (A not done after 5 s); here A finishes and the bytes land.
- sparse_readback_lands: 20 times a list writes 8 bytes, the title waits for
  its fence and reads them at once. Passes on main and here; fails in round 0
  when every copy back goes to the worker.
- noted_queue_waits_stay_one_per_fence (unit): 1,000 waits on one fence
  keep one entry; fails without the bound.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
@vladbondarenko97

vladbondarenko97 commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Retail-title A/B on NVIDIA for this PR. GTA VI 1.0.2.1, RTX 3080 Ti 12 GB (driver 610.88), i7-12700KF, Windows 11, release build, XCL_PSO_WAIT_MS=50 XCL_PSO_TRACE=1, first-run input scripted, 900 s requested.

main b9b6ea6: frames stop at ~150 s. From 154 s sparse: the queue has not reached fence value … (at 40159) every 5 s with the sparse queue stuck at 40159; the label queue.Waits are released on CPU but the producers stay at completed=0x9da. The title's watchdog ends the run at 179.99 s (+0x2215c35, write at 0), ~30 s after the last present.

main 4178e88 + this PR (c20dd22, clean merge → 2c7f851):

  • No sparse: the queue has not reached line in the whole run, so on this card the sparse stall is gone.
  • Frames still stop (last presents in the 120–130 s window). At 137.6 s: Write64 Signal … on q2/ty2 would close a GPU cycle (waiters=[q3]) – signalled on CPU (q1 too), then at 141.9 s GPU queue.Wait … >= 0x98d did not complete within 5000 ms (waiter=q1/ty2, prod=qSome(3)/tySome(0)) and (waiter=q3/ty0, prod=qSome(0)/tySome(2)).
  • The run ends at 175.3 s with 0xc0000005 in game_scarlett_master.exe+0x23cf683 (write at address 0x0) (Retail title 1.0.2.1: GPU hang / crash at +0x23cf683 when the story loads (RTX 3070 Ti) #675's signature).
xcl-smoke v1
commit: 2c7f85138ba765b7453fb9bddbe9bb9e20219535
gpu: NVIDIA GeForce RTX 3080 Ti
title: GTA6.Xbox.v1.0.2.1
seconds: 900
exit: 0xc0000005
frames shown: none logged (the run did not reach its end)
presents per 2 s (last 3): 0 0 1
device removals: 0
crashes: 2
peak commit: 33599 MB

(2c7f851 is a local merge commit of this PR onto main, so the block is evidence, not this PR's required regression block.)

So on this title the PR removes the sparse-queue stall. Correction (edited): I first read what is left as a wait cycle among the title's queues; the thread dumps say otherwise. Symbolised with the release PDB, all three dumps (155.3, 170.1, 176.6 s) show:

  • one thread holding sparse::STATE inside UpdateTileMappings (blocked in the NVIDIA driver): kernelx::home_again → sparse::committed → commit_range → ensure_mapped → State::map_tiles;
  • the frame-loop thread waiting for STATE in real::res_release → sparse::forget_buffer;
  • xcl-activity waiting for it in pool_bytes (last activity line 146.354 s), and the title's watchdog firing ~29 s later.

The 5 s GPU-wait releases (141.9–150.1 s) had stopped by then. Local VRAM use was 14.1–14.4 GB on this 12 GB card from ~106 s (inferred cause of the slow driver call). That is #505's deadlock, which #1697 addresses; a run of main + this PR + #1697 is queued.

Not tested: AMD; this PR together with #1385 (they conflict in sparse.rs).

AI use: Claude Code (Claude Opus 5.5) ran the box, read the log and wrote this report.

wondercrash added a commit to wondercrash/xcl that referenced this pull request Nov 24, 2026
After a submission with GPU writes into sparse windows, the sparse queue waited for the
title queue and the submitting thread waited for the copy, up to 5 s per flush with the
sparse lock held. On a queue still held by a gate that is a stall until the gate's
release: the thread cannot submit the producer, and every title queue waits for the
sparse queue in before_execute. The rule from xcl-dev#708 only covered sparse lists at or after
the gated one in the same call. Two cases were left:

- KickoffX of a split list: a gate armed for an earlier segment was followed by the
  active segment's readback. The active segment's sparse flag now reaches the earlier
  segments' waits (execute_with_waits_before), which keep the bounded CPU wait.
- A later submission to a queue whose gate is still closed. wait_gate now counts the
  gates the CPU has not opened per queue (closed_on). For such a queue the copy back is
  recorded on the title queue itself, followed by a signal of a fence of its own, and a
  worker lands it in the CPU view once the GPU is there, in order (from xcl-dev#433, which does
  this for any queue with an unfinished wait). Later copies of that queue take the same
  way until the earlier ones landed. Other queues keep the synchronous readback.

A CPU read right after the title's own fence can see the old bytes of such a copy until
the worker lands it; before, the call stalled there instead.

Found in review (integ-review.md W2). Not run.

Assisted-by: omp (Claude Opus 5.5)
@throny throny added the goal:world-load Bears on the retail title getting past world loading label Nov 25, 2026
@vakaobr

vakaobr commented Nov 25, 2026

Copy link
Copy Markdown

Test report from macOS (CrossOver + D3DMetal): #433 at c20dd22 merged into main 568e7db, on its own and under #1329's copy path. @Kalmarv this is the host where #1329 turns the committed window into a copy in video memory by default, so the readbacks this PR fixes run there on every title.

Merge notes (local, not pushed):

On this host the tests need two other changes to run at all: #1789 (D3DMetal releases on a thread of its own, where the first read of XCL_LATE_RELEASE never returns) and @Ahmet-Dedeler's ddf3be7 (D3DMetal's object tables). Without them both tests hang before they reach the readback, on main and on this PR alike. Every tree below has both merged in.

Tested (MacBook Pro M5 Pro, macOS 27.2.1, CrossOver 26.3 with D3DMetal 3.0, Rosetta 2, Rust 1.100.0 x86_64-pc-windows-gnu, debug; each test in its own process, three times; each tree built in its own target directory, and I checked that only the PR's builds contain its code):

tree sparse_readback_waits sparse_readback_lands
main + this PR's two tests only fails 3/3 after 5.4 s: queue A did not finish in 5 s passes 3/3
+ this PR passes 3/3 passes 3/3
+ this PR + #1329's stack passes 3/3 passes 3/3
  • With a print in q_wait (removed again), the title thread's Wait reaches the new override on D3DMetal and the readback sees queue A as held, as designed.
  • On the last tree also: the seven UMA tests D3D12.X: the committed window gets a copy in video memory #1329 is about pass (copy path on), all hle::d3d12x::sparse::tests pass (noted_queue_waits_stay_one_per_fence included; the_sparse_state_is_replaced_outside_its_lock skips, no GPU UMA), and sparse_reinit passes.

Not tested: Windows, the whole suite, a title, @CharlyRien's per-queue variant.

AI use: Claude Code, Claude Opus 5.5 merged the trees, ran the tests above on this machine and wrote this report.

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

Labels

goal:world-load Bears on the retail title getting past world loading

Projects

None yet

Development

Successfully merging this pull request may close these issues.