Skip to content

D3D12.X: run sparse::readback_after_execute asynchronously per queue - #1732

Open
gustavsi wants to merge 4 commits into
xcl-dev:mainfrom
gustavsi:wine/async-sparse-readback
Open

gustavsi wants to merge 4 commits into
xcl-dev:mainfrom
gustavsi:wine/async-sparse-readback

Conversation

@gustavsi

@gustavsi gustavsi commented Nov 24, 2026 •

Copy link
Copy Markdown

Move sparse::readback_after_execute off sparse::State::queue and out from under STATE.lock() into per-queue FIFO background workers, completing asynchronously when the queue has an unsatisfied title/wait-before-signal GPU queue.Wait (avoiding CPU/GPU deadlocks on wait-before-signal Wait64BitValueX) and synchronously otherwise (preserving immediate CPU visibility after a GPU fence wait). Part of #1452.

Stacked on #877; only the top commit (c992ec81) belongs here.

Previously, sparse::readback_after_execute locked STATE, called s.queue.Wait(&s.rb_fence, v), and synchronously executed s.readback_ranges(&merged) (s.wait_for(s.value) with a 5,000 ms timeout) inside ExecuteCommandLists. When an async compute queue carried both a sparse memory write and a wait-before-signal Wait64BitValueX whose producer direct queue had not yet been submitted on the same thread, this deadlocked both the submitter thread (preventing submission of the producer queue) and sparse::State::queue for 5,000 ms per submit, triggering repeated xcl-sync-watchdog timeouts and causing a retail title's stall watchdog to abort after 5–6 consecutive submits.

With per-queue FIFO workers waiting on a raw per-queue fence outside STATE.lock() before invoking readback_ranges, sparse::State::queue is never stalled behind a blocked title queue. Active unsatisfied title queue.Wait calls and unsubmitted wait-before-signal Wait64BitValueX bridges are tracked via sparse::note_queue_wait (ignoring XCL's own internal fences such as sparse::before_execute's s.fence so an in-flight internal upload under XCL_D3D12_DEBUG=1 never causes readback_after_execute to return before CopyBufferRegion completes, fixing the Write32BitValueBottomOfPipeX zero-read reported by @razormontana).

If a fence wait times out after 5,000 ms (while the device is still alive), the worker wakes any synchronous caller with RbStatus::Deferred (never falsely claiming RbStatus::Completed) and retains the job in a per-worker FIFO deferred: VecDeque<RbJob> queue, polling and draining it in order once the fence completes so CPU coherence is never silently lost (fixing @bmjask's P1).

To prevent an asynchronous or deferred readback from overwriting a newer CPU write made after the submit (flagged by @GreemSC), readback_after_execute snapshots the per-64-byte-segment CPU hashes of the committed target ranges when recording the job. At copy-back time, readback_ranges skips any segment whose current CPU bytes differ from the snapshot (unless they match an intervening readback recorded while multiple jobs are in flight, so consecutive deferred readbacks on the same range still land) and leaves sent dirty for any skipped 64-byte chunk so the next before_execute uploads the CPU's newer bytes.

What is in it

  • crates/xcl/src/hle/d3d12x/sparse.rs:
    • Add per-queue RB_QUEUES map (RbQueueState holding a raw ID3D12Fence via super::real::create_raw_fence, monotonic fence value, and channel sender to a dedicated xcl-sparse-rb-<queue> FIFO worker thread) and QUEUE_WAITS tracking (note_queue_wait, queue_has_unsatisfied_wait, forget_queue).
    • Have readback_after_execute filter/merge sparse ranges using uma::get(), signal the queue's fence, register new queues with s.note_queue(queue) (preserving D3D12.X: quarantine unmapped parked sparse tiles behind GPU fences #2345's parked-tile quarantine tracking), snapshot committed 64-byte-bounded segment hashes (State::snapshot_ranges) under STATE.lock(), and enqueue an RbJob without holding STATE across GPU waits — returning immediately if queue_has_unsatisfied_wait is true, or waiting on the job's RbStatus condvar outside STATE.lock() otherwise (logging when a synchronous wait is deferred instead of completed).
    • Have State::readback_ranges check the recorded RbSnapshot (and a bounded last_rb map active only while multiple readback jobs are in flight) before copying each 64-byte-bounded segment, skipping CPU-modified segments without marking their 64-byte chunk clean in sent, and flushing staging with at least one tile of headroom so staging flushes never split a 64-byte segment.
    • Have each worker (spawn_rb_worker_with) wait on its fence outside STATE.lock() (5,000 ms timeout). On completion, drain any earlier deferred jobs first in FIFO order, run readback_ranges, and report RbStatus::Completed; on timeout (while GetCompletedValue() != u64::MAX), report RbStatus::Deferred and retain the job in deferred: VecDeque<RbJob> so it retries every 20 ms (and on subsequent jobs / bounded teardown drain) until the fence completes.
    • Add unit tests:
      • readback_after_execute_does_not_block_on_stalled_queue
      • internal_fence_wait_keeps_readback_synchronous
      • timeout_then_completes_still_reads_back_cpu_memory
      • deferred_readback_preserves_newer_cpu_writes
  • crates/xcl/src/hle/d3d12x/real.rs & crates/xcl/src/hle/d3d12x/list_x.rs:
    • Record active unsatisfied title queue.Wait calls (is_fence in q_wait_pc and queue_dispatch) and unsubmitted Wait64BitValueX GPU bridges (unsubmitted in try_gpu_wait) via sparse::note_queue_wait, and clean up per-queue state in q_release via sparse::forget_queue.

Tested

  • Hardware / OS: AMD Radeon RX 9060 XT (16 GiB VRAM, RADV Mesa 26.2.7), Linux, GE-Proton11-14-x86_64, vkd3d-proton (-Db_ndebug=true), DXC 1.9.2609.5, cross-compiled x86_64-pc-windows-msvc (clang-cl + lld-link).
  • Restacked onto updated Memory: lazily map sparse VRAM tiles for Wine graphics heaps (#175) #877 (29352403, on main 08db8020 + D3D12.X: preserve native vtables and wrap fences for vkd3d-proton under Wine (#175) #867 d9e6ad51 + Memory: avoid amdgpu userptr stalls under Wine (#175) #871 a800c38a) at c992ec81 (no conflicts, commit diff unchanged) under GE-Proton11-14 (XCL_DXC_DIR set):
    • hle::d3d12x::sparse:: --test-threads=1: 22 passed, 0 failed, 1 ignored (including deferred_readback_preserves_newer_cpu_writes, timeout_then_completes_still_reads_back_cpu_memory, readback_after_execute_does_not_block_on_stalled_queue, and internal_fence_wait_keeps_readback_synchronous)
    • hle::d3d12x::list_x:: --test-threads=1: 40 passed, 0 failed, 0 ignored
    • hle::d3d12x::real:: --test-threads=1: 63 passed, 0 failed, 0 ignored
    • hle::d3d12x::vram:: --test-threads=1: 19 passed, 0 failed, 1 ignored
    • gpu::uma:: --test-threads=1: 12 passed, 0 failed, 0 ignored
    • hle::d3d12x::alloc_pool:: --test-threads=4 (× 3): 4 passed, 0 failed, 0 ignored each
    • --exact gpu_sparse_vram_descriptors_buffers_and_xmem gpu_valu_float_and_int: 2 passed, 0 failed, 0 SKIPPED
  • Retail title 60 s smoke run via unmodified pwsh ./scripts/smoke.ps1 (with GE-Proton11-14 wrapper): 1091 frames shown (PresentX 1091, 60 60 60/2 s), exit: 0x0, 0 crashes, 0 device removals.

Regression run
Produced under Wine (GE-Proton11-14, AMD Radeon RX 9060 XT, XCL_NETWORK=0 XCL_PSO_PRELOAD=0 XCL_RUN_SECONDS=60 XCL_ACTIVITY=1, VKD3D_CONFIG=""). The PR run used unmodified pwsh ./scripts/smoke.ps1 via a thin Wine wrapper; main (e0d93c84) crashed before writing report.json, so its block was extracted from the same xcl.log (peak commit: 0 MB is what Wine reports in xcl.log).

main (e0d93c84):

xcl-smoke v1
commit: e0d93c84ad8253f6e17738d14741c1bab7061127
gpu: AMD Radeon RX 9060 XT
title: retail-title
seconds: 60
exit: 0x3
frames shown: 0 (did not reach end)
presents per 2 s (last 3): 0 0
device removals: 0
crashes: 2
peak commit: 0 MB

This PR (c992ec81, stacked on #877):

xcl-smoke v1
commit: c992ec816f0f7ea5a293da889c315c22ed4d53b7
gpu: AMD Radeon RX 9060 XT
title: retail-title
seconds: 60
exit: 0x0
frames shown: 1091 (PresentX 1091)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 0 MB

Not tested

  • Native Windows locally (independently verified on Windows 11 / RTX 3060 Ti by @DavidM1911 before the timeout-retry and snapshot-guard updates; needs re-verification on Windows with XCL_D3D12_DEBUG=1).
  • NVIDIA Linux GPUs.

AI use

  • Antigravity (Gemini 4 Neon) implemented the RbSnapshot / last_rb CPU-write protection and deferred_readback_preserves_newer_cpu_writes regression test for @GreemSC's review, restacked onto updated Memory: lazily map sparse VRAM tiles for Wine graphics heaps (#175) #877 (29352403), ran the Proton tests and 60 s smoke run at c992ec81, and updated this description.
  • Claude Code (Claude Opus 5.5) ran the earlier c7fac707 restack verification.

anoyarou pushed a commit to anoyarou/xcl that referenced this pull request Nov 24, 2026
…cl-dev#1732)

sparse::readback_after_execute previously stalled sparse::State::queue
behind the title queue (s.queue.Wait) and synchronously blocked the
submitter thread inside STATE.lock() for up to 5000 ms (s.wait_for).
When an async compute queue carried both a sparse write and a
wait-before-signal Wait64BitValueX whose producer direct queue had not
yet been submitted on the same thread, this deadlocked both the
submitter thread (blocking submission of the producer queue) and
sparse::State::queue for 5000 ms per submit, triggering xcl-sync-watchdog
timeouts and the title's stall watchdog after 5-6 consecutive submits.

Dispatch sparse readbacks to per-queue background workers that wait on a
raw per-queue fence outside STATE.lock() before invoking readback_ranges,
never stalling sparse::State::queue or blocking ExecuteCommandLists.
@LocranKing

Copy link
Copy Markdown

Independent Windows release GPU check on NVIDIA RTX 3060 Ti (00eec16bbc2b41bc4f56d0f8486dfbcbe8073169, merge-base b7aa9f3bd212088e0d927439284dc5ed325ce3c7): test_title_runs_and_game_folder_is_untouched fails on Write32BitValueBottomOfPipeX: 0x0 (the 60 s retail smoke passes).

Setup

  • GPU: NVIDIA GeForce RTX 3060 Ti (8024 MiB VRAM, wave32), driver 32.0.16.2101
  • CPU / RAM: AMD Ryzen 5 5500 (6C/12T), 31.8 GB RAM
  • OS: Windows 11 Home Single Language, build 26200
  • Toolchain: rustc 1.100.0, DXC 1.9.2602.17, --release

Workspace tests (cargo test --workspace --release --no-fail-fast -- --test-threads=4)

  • Exit 101: 773 passed, 1 failed, 41 ignored across 20 result blocks (SKIPPED: 2 no wave64, 2 no D3D12 debug layer).
  • Failure in crates\xcl\tests\e2e.rs:132:5 (test_title_runs_and_game_folder_is_untouched):
    thread 'test_title_runs_and_game_folder_is_untouched' panicked at crates\xcl\tests\e2e.rs:132:5:
    failed checks in the test title:
    [FAIL] D3D12.X: console command list memory methods (writes, timestamp, fill, copy, KickoffX, Wait32/64): 
    Write32BitValueBottomOfPipeX: 0x0
    
    This looks directly related to moving sparse::readback_after_execute onto an asynchronous per-queue worker: after the title's GPU fence wait completes, the CPU reads 0x0 before the async readback copies the GPU write back to CPU memory.
  • Also note the PR branch currently includes two earlier Wine commits (b66a150, fbf1440) on top of b7aa9f3.

Regression run (scripts/smoke.ps1, 60 s, XCL_NETWORK=0, title folder name redacted)

  • PR head vs base b7aa9f3: 1585 / 1508 frames (105.1%), 15209 / 14730 MB peak commit (103.3%), 0 device removals, 0 crashes.

Base (main b7aa9f3):

xcl-smoke v1
commit: b7aa9f3bd212088e0d927439284dc5ed325ce3c7
gpu: NVIDIA GeForce RTX 3060 Ti
title: retail-1.0.2.1
seconds: 60
exit: 0x0
frames shown: 1508 (PresentX 1508)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 14730 MB

PR head (00eec16):

xcl-smoke v1
commit: 00eec16bbc2b41bc4f56d0f8486dfbcbe8073169
gpu: NVIDIA GeForce RTX 3060 Ti
title: retail-1.0.2.1
seconds: 60
exit: 0x0
frames shown: 1585 (PresentX 1585)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 15209 MB

Not tested: Linux / Wine, repeating e2e to measure flake rate vs deterministic failure, AMD / wave64 hardware.

AI use: Antigravity (Gemini 4 Neon) built and ran the workspace test suite and smoke pair on this hardware and drafted this report from the captured outputs; reviewed before posting. No game files attached.

anoyarou added a commit to anoyarou/xcl that referenced this pull request Nov 24, 2026
…pub(crate)

Fixes compilation errors on MSVC Windows target:

- D3D12.X: restores pub(crate) unsafe fn create_raw_fence in real.rs required
  by sparse::readback_after_execute (xcl-dev#1732). Creates an unproxied raw
  ID3D12Fence bypassing title vtable hooks so internal queue worker threads under
  Wine/vkd3d-proton signal native fences without hitting proxy mismatches.

- KernelX: restores pub(crate) visibility for commit_sparse in kernelx.rs
  (xcl-dev#549, xcl-dev#1298), required by DirectStorage's lazy MEM_RESERVE sparse
  window allocation in dstorage.rs and placeholder mappings.

- Recompiler: adds #[cfg(test)] gate above mod tests in emit.rs to silence unused
  PRELUDE_MEM import warnings in non-test release builds (xcl-dev#1524).

Assisted-by: Antigravity
anoyarou added a commit to anoyarou/xcl that referenced this pull request Nov 24, 2026
…driver gave up callback

Eliminates compiler warnings for unused items:

- D3D12.X: removes rb_fence and rb_value from sparse::State and test fixtures
  (xcl-dev#1732). Readback fences are now managed per-queue in RB_QUEUES
  by async readback workers, making the fields on State obsolete.

- D3D12.X: hooks note_driver_gave_up in real::translated_compute_pso_once when
  driver_compile_identified returns E_OUTOFMEMORY after DRIVER_GAVE_UP_AFTER
  (xcl-dev#1665, xcl-dev#1524), ensuring failed massive compute pipelines are
  persisted in used-pipelines.txt (!<key>) and eliminating dead code warnings.

Assisted-by: Antigravity
@gustavsi
gustavsi force-pushed the wine/async-sparse-readback branch from 00eec16 to 64cb447 Compare November 24, 2026 21:13
@gustavsi

Copy link
Copy Markdown
Author

Thanks @LocranKing for catching that on Windows!

Your diagnosis was spot on: when an unstalled queue (like testtitle's Write32BitValueBottomOfPipeX + wait(&queue, &fence, 1)) completes, the title's own GPU fence completed before the background worker finished readback_ranges.

Updated 64cb447 to track active unsatisfied queue.Wait calls (sparse::note_queue_wait in q_wait_pc and list_x::try_gpu_wait, cleaned up in q_release via sparse::forget_queue):

  • When queue has an unsatisfied queue.Wait (wait-before-signal Wait64BitValueX whose producer is not yet submitted), readback_after_execute returns immediately while the per-queue FIFO worker finishes asynchronously (never deadlocking the submitter thread or stalling sparse::State::queue).
  • When queue has no unsatisfied queue.Wait, readback_after_execute still waits on the queue's fence outside STATE.lock() and off sparse::State::queue, but waits for the FIFO worker's completion condvar before returning so CPU reads right after a GPU fence wait always observe the updated bytes.

(The two earlier commits b66a150 / fbf1440 are there because this PR is stacked on #877 for Wine smoke testing; only the top commit 64cb447 belongs to this PR.)

@DavidM1911

Copy link
Copy Markdown
Contributor

Verification on RTX 3060 Ti (Windows 11): merge conflict with current main in crates/xcl/src/hle/d3d12x/vram.rs — needs a rebase before it can be tested.

@gustavsi
gustavsi force-pushed the wine/async-sparse-readback branch from 64cb447 to e4d8229 Compare November 24, 2026 22:44
@gustavsi

Copy link
Copy Markdown
Author

Thanks @DavidM1911! Rebased the stack (#867 -> #871 -> #877 -> #1732) onto main 689f2db (HEAD e4d8229, resolving the vram.rs conflict) and re-verified unit/GPU tests and the 60 s smoke run under Wine — ready for Windows testing.

@JJAutoCompare

Copy link
Copy Markdown

XCL PR #1732 verification on Intel Arc A770

Head e4d8229650344e003513bd3775eb90502854c96b, detached and clean. STOR-WINLAB ran Windows x64 build 26200.9974 on an AMD x64 CPU and Intel Arc A770 (driver 32.0.101.9175). DXC 1.9.2609.5 and rustc 1.100.0 (0ef1bc386, x86_64-pc-windows-msvc). Debug profiles, with debug info and incremental compilation disabled.

Tested

  • cargo build --workspace and cargo test --workspace --no-run succeeded outside the Arc mutex. Cargo listed 19 test binaries.
  • Each focused run used cargo test -p xcl --lib hle::d3d12x::sparse::tests::<name> -- --exact. Each reported 1 passed, 0 failed, 0 ignored and 0 skip markers.
    • readback_after_execute_does_not_block_on_stalled_queue exercised sparse UMA on the A770. It asserted return in under one second with an unsignaled compute-queue fence, availability of STATE, and queue drain after the fence was signaled. It then exercised the unstalled call.
    • ensure_mapped_with_query_holes_skips_uncommitted_pages_on_readback checked that readback across sparse holes did not fault and that a write to a newly committed page was detected. Both D3D12 filters ran under the Arc mutex with XCL_ADAPTER=A770. The holes test selects the default D3D12 device with a WARP fallback internally.
    • lazy_range_helpers_track_tile_overlap_holes_and_nonzero_pages checked overlap, hole masks and nonzero-page detection with XCL_ADAPTER=NONE_CPU_ONLY outside the mutex.
  • cargo test --workspace --no-fail-fast -- --test-threads=4 ran once under Invoke-ArcTest.ps1 with XCL_ADAPTER=A770 and RUST_TEST_NOCAPTURE=1. Exit 101. All 20 result lines (19 binaries and one doctest suite) sum to 954 passed, 25 failed and 45 ignored. All three focused tests also passed in this run.

Workspace failures and skips

24 DXIL/recompiler tests failed (20 compute PSO rejections with 0x80070057 and four output mismatches). The title e2e failed its dynamic depth-bias check (blue pixel, expected green). The log contains 25 exact SKIPPED lines, excluded from coverage.

Not tested

Matched main run, retail-title smoke, sample-data coverage, Wine or other GPUs.

AI use

T3 Code / Codex (gpt-6.2-sol, reasoningEffort: high) ran the build and verification. Coordinator #2 (T3 Code / Antigravity, gemini-4-neon) verified counts against pr1732-suite.log and published.

@throny throny added the goal:world-load Bears on the retail title getting past world loading label Nov 25, 2026
@gustavsi
gustavsi force-pushed the wine/async-sparse-readback branch from e4d8229 to 2fb4601 Compare November 25, 2026 15:20
@gustavsi

Copy link
Copy Markdown
Author

Thanks @JJAutoCompare for verifying all three focused sparse::tests on Intel Arc A770!

Rebased onto main (06c9f55) + updated #877 (aec41e2) at 2fb4601, verified sparse:: 17/0/1, list_x:: 34/0, alloc_pool:: --test-threads=4 4/0 × 3, and a fresh 60 s smoke run (exit: 0x0, 1066 frames, 0 crashes, 0 removals).

@razormontana

Copy link
Copy Markdown
Contributor

Independent native Windows release test for #1732 on NVIDIA RTX 3070.

The synthetic title's D3D12 debug-layer run read 0x0 after Write32BitValueBottomOfPipeX, which expects 0x12345678 in tests/testtitle/src/gpu.rs. The assertion surfaced at crates/xcl/tests/e2e.rs:293. The parent stack passed all five isolated debug-layer trials. The PR head and its local merge each reproduced the zero read in all five trials.

Tested

  • NVIDIA GeForce RTX 3070 (8 GiB, driver 617.42), Intel Core i7-10700K, Windows 11 Pro 23H2 (22631.5335), Rust 1.100.0 x86_64-pc-windows-msvc, DXC 1.9.2602.17. Release builds ran in a standard user session with XCL_ADAPTER=3070 and XCL_NETWORK=0.
  • Parent stack aec41e2cd15e0dd81ec4c28d82ff4a26929e892a, PR head 2fb46019a11a3641453d7c2eef97e72fe894be20, and a cleanly applied local merge of that PR head into main snapshot 082944135cd2b96288470a595861fa608eee08dc (tree 52387c8562305f6f1dd1f58689f337e0a536109f). Each revision had its own Cargo target directory.
Test runs passing Parent stack PR head Local merge
test_title_runs_and_game_folder_is_untouched 3/3 5/5 3/3
readback_after_execute_does_not_block_on_stalled_queue Added by the PR 5/5 2/2
test_title_draws_with_a_root_signature_under_the_debug_layer, isolated 5/5 0/5 0/5
Entire e2e test binary, four test threads 3/3 1/3 0/3
  • The same zero read accounted for every failing E2E run in the table. The focused runs had zero GPU skips.
  • The PR-head workspace suite reported 1,268 passed, 1 failed, and 46 ignored across 23 test binaries. The sole failure was the same debug-layer E2E assertion. The pass count includes 26 runtime skip markers (21 lacking wave64, three unsupported per-lane shader forms, one reserved-cube-mips capability, and one lacking heap windows). External-sample variables were unset.

Commands used for the build, isolated tests, grouped E2E, and full suite:

cargo build --release --offline --locked --workspace
cargo test --release --offline --locked -p xcl --test e2e test_title_runs_and_game_folder_is_untouched -- --exact --test-threads=1 --show-output
cargo test --release --offline --locked -p xcl --lib hle::d3d12x::sparse::tests::readback_after_execute_does_not_block_on_stalled_queue -- --exact --test-threads=1 --show-output
cargo test --release --offline --locked -p xcl --test e2e test_title_draws_with_a_root_signature_under_the_debug_layer -- --exact --test-threads=1 --show-output
cargo test --release --offline --locked -p xcl --test e2e -- --test-threads=4 --show-output
cargo test --release --offline --locked --workspace --no-fail-fast -- --test-threads=4 --show-output

Not tested

  • Retail-title smoke tests, Wine or Proton, and other GPU adapters.

AI use

  • Codex (GPT-6.2) ran the test matrix and drafted this report.

@gustavsi
gustavsi force-pushed the wine/async-sparse-readback branch from 2fb4601 to 6fa3a01 Compare November 25, 2026 19:43
gustavsi added a commit to gustavsi/xcl that referenced this pull request Nov 25, 2026
…1946, xcl-dev#1803, xcl-dev#2297, xcl-dev#2320, xcl-dev#2333

Carries forward still-open high-value upstream PRs onto upstream/main (2898511)
+ our updated Wine PR stack (xcl-dev#867, xcl-dev#1395-successor, xcl-dev#871, xcl-dev#877, xcl-dev#1732).
Preserves UnadoptGuard in xcl-dev#2320 KickoffX reset_one.

Assisted-by: Antigravity (Gemini 4 Neon)
@gustavsi

Copy link
Copy Markdown
Author

Thanks @razormontana for catching and isolating the 5/5 XCL_D3D12_DEBUG=1 zero-read on Windows!

Root cause: sparse::before_execute calls queue.Wait(&s.fence, s.value) on the adopted title queue, which goes through real::q_wait_pc. Under XCL_D3D12_DEBUG=1, s.queue's upload was still in flight when readback_after_execute ran, so q_wait_pc had recorded XCL's own internal s.fence in QUEUE_WAITS, causing readback_after_execute to treat the queue as stalled and return before the readback worker finished CopyBufferRegion.

Rebased onto main (2898511, preserving #2345's s.note_queue(queue)) + updated #877 (2da0233) at 6fa3a01:

  • q_wait_pc now only records title fences (is_fence(fence)), never XCL's internal create_raw_fence waits; queue_dispatch tracks console title waits; try_gpu_wait only records unsubmitted wait-before-signal bridges.
  • Added regression test sparse::tests::internal_fence_wait_keeps_readback_synchronous verifying that an in-flight internal raw-fence queue.Wait does not mark the queue stalled and keeps readback_after_execute synchronous.
  • Verified under Proton (sparse:: 20/0/1, list_x:: 36/0, alloc_pool:: --test-threads=4 4/0 × 3) and a fresh 60 s pwsh ./scripts/smoke.ps1 run (exit: 0x0, 983 frames, 57 57 56/2 s, 0 crashes, 0 removals). Ready for a Windows debug-layer re-check!

@gustavsi
gustavsi force-pushed the wine/async-sparse-readback branch from 6fa3a01 to 1be3831 Compare November 25, 2026 20:32
gustavsi added a commit to gustavsi/xcl that referenced this pull request Nov 25, 2026
…1946, xcl-dev#1803, xcl-dev#2297, xcl-dev#2320, xcl-dev#2333

Carries forward still-open high-value upstream PRs onto upstream/main (2898511)
+ our updated Wine PR stack (xcl-dev#867, xcl-dev#1395-successor, xcl-dev#871, xcl-dev#877, xcl-dev#1732).
Preserves UnadoptGuard in xcl-dev#2320 KickoffX reset_one.

Assisted-by: Antigravity (Gemini 4 Neon)
@gustavsi

Copy link
Copy Markdown
Author

Rebased onto main (e0d93c84) + updated #867–#877 (08abaa07, picking up the UnadoptGuard/orig_fn race fix and #2118 guards) at 1be3831a, verified Proton tests (sparse:: 20/0/1, list_x:: 40/0, alloc_pool:: --test-threads=4 4/0 × 3) and a fresh 60 s pwsh ./scripts/smoke.ps1 run (exit: 0x0, 985 frames, 54 56 55/2 s, 0 crashes, 0 removals).

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

P1: a fence timeout can silently lose CPU coherence. The worker waits 5s, logs timeout and skips readback_ranges, but still marks job.done=true; readback_after_execute then returns after its synchronous wait believing immediate visibility is preserved. Timed-out jobs are never retried even if fence later completes. Retain/retry until fence completion or report/defer without claiming sync, with timeout-then-completes regression. The async visibility path also depends on #1993/#2009, whose fence-hook try-lock race remains unresolved.

@DavidM1911

Copy link
Copy Markdown
Contributor

Re-verification on RTX 3060 Ti (Windows 11), new head merged with current main:

  • cargo test -p xcl --lib: all passed, 0 failed, 27 ignored. The earlier merge conflict is resolved.

Thanks!

— Devin

@gustavsi
gustavsi force-pushed the wine/async-sparse-readback branch from 1be3831 to 87287c4 Compare November 26, 2026 02:21
@gustavsi

Copy link
Copy Markdown
Author

Thanks @bmjask for catching the timeout coherence bug and @DavidM1911 for the Windows 11 re-verification!

Addressed the P1 timeout coherence issue and rebased onto main (08db8020) + updated #867–#877 (a553a224) at 87287c44:

  • Explicit RbStatus::{Pending, Completed, Deferred}: RbJob::done now carries RbStatus instead of bool. When wait_fence_ms times out (or sees device removal u64::MAX), the worker notifies RbStatus::Deferred rather than claiming synchronous completion, and readback_after_execute logs that synchronous visibility was deferred instead of silently returning as completed.
  • Retain & retry until fence completion: timed-out jobs (while the device is alive) are pushed onto a per-worker FIFO deferred: VecDeque<RbJob> queue. The worker polls rx.recv_timeout(20 ms) while deferred is non-empty, drains ready jobs in FIFO order once fence.GetCompletedValue() >= value (and before any later job on the same monotonic fence, plus a bounded drain on queue teardown), so CPU coherence catches up once the fence completes.
  • Regression test: added sparse::tests::timeout_then_completes_still_reads_back_cpu_memory (factors spawn_rb_worker_with with a 50 ms timeout on a real raw D3D12 fence): verifies the timed-out job reports RbStatus::Deferred, does not run readback early, automatically runs once fence.Signal(1) fires after timeout, and preserves FIFO ordering for subsequent RbStatus::Completed jobs.
  • Verified under GE-Proton11-14 (RX 9060 XT): sparse:: 21/0/1, list_x:: 40/0, real:: 62/0, alloc_pool:: --test-threads=4 4/0 (× 3), plus a fresh 60 s pwsh ./scripts/smoke.ps1 run (exit: 0x0, 646 frames shown, 0 crashes, 0 device removals; block updated in PR description).

AI use: Antigravity (Gemini 4 Neon) implemented the RbStatus + deferred retry fix and regression test, rebased onto main + updated #877, ran the Proton tests and smoke run, and drafted this comment.

@GreemSC

GreemSC commented Nov 26, 2026

Copy link
Copy Markdown

A data point for this PR's idea, from amd-dev under Wine (RX 7900 XT, RADV), where rb_queue (253108c) replaced the per-queue readback but kept its problem.

What we saw on amd-dev c32c91a3 + the Wine stack (not this PR):

  • readback_after_execute waits for its readback, and when the submitting queue has an armed bridged Wait64 whose producer is not submitted yet, that readback can only finish after the title goes on. Here that was a 2 s Wait64BitValueX timeout on nearly every frame entering the world (40 in one run), the CPU waiting for a value the deferred readback would have delivered.
  • readback_now (Map) ordered behind every title queue (wait_title_queues_for_readback) waits for such a queue too: 6 real 5 s waits in a row, then the title's GPU watchdog (+0x23cf683).

What fixed it there, along this PR's lines (local tree, not a PR):

  • note_queue_wait / queue_has_unsatisfied_wait as here, recorded only under Wine;
  • when the submitting queue has such a wait: no wait for the readback; the queue signals a raw fence of its own (one per queue: a single fence signalled by several queues lets a fast queue complete a stalled one's value) and a worker reads the ranges back once it passes;
  • readback_now not ordered behind title queues under Wine;
  • after that: 0 Wait64 timeouts, 0 readback timeouts, 600 s into the playable part.

One thing to check in this PR's design and ours, found in review and not shown by a run: a readback done later snapshots the host chunk hashes when it is recorded, so a CPU write between the title's submit and the late readback could be overwritten.

Not tested: this PR itself on amd-dev; Windows.

AI use: Claude Code (Claude Opus 5.5) ran the runs and wrote this comment; a second pass (Claude Fable 5.2) reviewed the change.

@gustavsi
gustavsi force-pushed the wine/async-sparse-readback branch from c7fac70 to f14d697 Compare November 26, 2026 19:04
@gustavsi

Copy link
Copy Markdown
Author

Thanks @GreemSC for the amd-dev data point and for catching the late-readback overwrite race!

Fixed in f14d6976:

  • Snapshot at record time (State::snapshot_ranges): when readback_after_execute records a job, it hashes each committed 64-byte-bounded segment in the target ranges under STATE.lock() (skipping uncommitted pages/holes) and records rb_seq while bumping IN_FLIGHT_RB.
  • Guarded copy-back (State::readback_ranges): when the worker later copies bytes back, it checks each segment's current CPU hash against its snapshot. If the CPU modified those bytes in the interim, the segment is skipped (preserving the CPU's newer write) and that 64-byte chunk's sent hash is left dirty so the next before_execute uploads the CPU write to VRAM.
  • Consecutive deferred readbacks: while multiple readback jobs are concurrently in flight (IN_FLIGHT_RB > 1), copied segments are recorded in a bounded State::last_rb map (cleared as soon as no other job is in flight) keyed with rb_seq > snapshot.seq, so an earlier deferred readback's copy-back does not cause a subsequent deferred readback on the same range to mistake it for a CPU write.
  • Regression test: added sparse::tests::deferred_readback_preserves_newer_cpu_writes covering both CPU-write preservation (verifying the skipped chunk keeps the CPU's bytes and stays dirty in sent, while the untouched chunk receives VRAM data and syncs sent) and two consecutive deferred readbacks on the same range without an intervening CPU write.

Verified at f14d6976 under GE-Proton11-14 (AMD Radeon RX 9060 XT, RADV Mesa 26.2.7, XCL_DXC_DIR set):

  • hle::d3d12x::sparse:: --test-threads=1: 22 passed, 0 failed, 1 ignored
  • hle::d3d12x::list_x:: --test-threads=1: 40 passed, 0 failed, 0 ignored
  • hle::d3d12x::real:: --test-threads=1: 62 passed, 0 failed, 0 ignored
  • hle::d3d12x::vram:: --test-threads=1: 19 passed, 0 failed, 1 ignored
  • gpu::uma:: --test-threads=1: 12 passed, 0 failed, 0 ignored
  • hle::d3d12x::alloc_pool:: --test-threads=4 (× 3): 4 passed, 0 failed, 0 ignored each
  • --exact gpu_sparse_vram_descriptors_buffers_and_xmem gpu_valu_float_and_int: 2 passed, 0 failed, 0 SKIPPED
  • 60 s pwsh ./scripts/smoke.ps1 release run: exit: 0x0, 1063 frames shown (PresentX 1064, 60 59 60/2 s), 0 crashes, 0 device removals (PR description updated).

Not tested: native Windows locally; NVIDIA Linux GPUs.

AI use: Antigravity (Gemini 4 Neon) implemented the snapshot guard and regression test, ran the Proton tests and 60 s smoke run, and drafted this comment.

…er Wine (xcl-dev#175)

vkd3d-proton validates iface->lpVtbl on adopted D3D12 objects passed back into d3d12core.dll (command allocators, lists, heaps, resources, PSOs, and fences). On unmodified assertion-free vkd3d-proton (such as GE-Proton or -Db_ndebug=true builds), XCL's in-place vtable adoption causes CreateCommandList/Reset to fail with E_INVALIDARG and fence waits to reject adopted fences.

Under Wine (gated behind util::under_wine(), native Windows unchanged):
- UnadoptGuard temporarily restores the native vtable on adopted command allocators (including alloc_pool backings and reset_pc_allocator), command lists, heaps (CreatePlacedResource/CreatePlacedResource1), RTV resources, and PSOs around calls into d3d12core.dll.
- FenceProxy wraps title ID3D12Fence1 objects so the underlying PC fence keeps its native lpVtbl, unwrapping in queue Signal/Wait while preserving Fence::xcl-dev#12 completed_value_address and freeing on final Release.
- real::create_raw_fence creates un-proxied native ID3D12Fence objects for XCL's own internal queue tracking (late_release, alloc_pool, list_x, cpu_writes, present, vram, drain_gpu) so un-adopted internal queues like sparse::queue() never receive a FenceProxy.

Note: assert-enabled vkd3d-proton builds (such as stock Proton Experimental) still validate iface->lpVtbl inside an adopted object's own methods, so an assertion-free build (-Db_ndebug=true / GE-Proton) remains required for in-place adoption.

Assisted-by: Antigravity (Google DeepMind)
On Linux with amdgpu, a multi-GiB coherent UMA window imported via OpenExistingHeapFromAddress (VK_EXT_external_memory_host userptr) causes two severe stalls:
1. GetWriteWatch(WRITE_WATCH_FLAG_RESET) on the userptr range triggers amdgpu MMU-notifier evictions (~100-200 ms/submit).
2. A multi-GiB userptr BO stalls every Vulkan GPU submission (~150 ms/frame, dropping PresentX frames).

Under Wine (native Windows unchanged):
- Key the default 512 MiB coherent_hint() cap on AMD GPUs (DXGI VendorId 0x1002) under Wine so NVIDIA Linux keeps a full-size coherent window (unless XCL_COHERENT_MB is set).
- Allocate the coherent window without MEM_WRITE_WATCH and exclude it from watch_regions(), notifying title_textures on DirectStorage writes into it and hashing small/dynamic coherent textures with a 1/16 round-robin sweep for large ones.
- Route overflow PAGE_GRAPHICS_* title GPU heaps into the sparse VRAM windows so shaders still read them directly.

Assisted-by: Antigravity (Google DeepMind)
…#175)

Under Wine, overflow PAGE_GRAPHICS_* title heaps are routed to sparse VRAM
windows (xcl-dev#871). Eagerly mapping 64 KiB VRAM tiles for the full reserved
heap up front consumes ~3.2 GiB of local VRAM for zero-filled or never-
written pages before the title even leaves the menus.

Add sparse::alloc_lazy (used under util::under_wine() only; native Windows
unchanged):
- Commits CPU pages up front so host accesses never fault, while deferring
  64 KiB VRAM tile allocation until the first non-zero CPU write or GPU
  write target registration (placed buffers, buffer UAVs, and command-list
  memory writes via sparse::ensure_lazy_mapped).
- Unit tests cover lazy-range overlap, hole masks, non-zero page detection,
  and coalesced lazy tile allocation.

Assisted-by: Antigravity (Google DeepMind)
…g STATE or sparse::State::queue

sparse::readback_after_execute previously stalled sparse::State::queue
behind the title queue (s.queue.Wait) and synchronously blocked the
submitter thread inside STATE.lock() for up to 5000 ms (s.wait_for).
When an async compute queue carried both a sparse write and a
wait-before-signal Wait64BitValueX whose producer direct queue had not
yet been submitted on the same thread, this deadlocked both the
submitter thread (blocking submission of the producer queue) and
sparse::State::queue for 5000 ms per submit, triggering xcl-sync-watchdog
timeouts and the title's stall watchdog after 5-6 consecutive submits.

Dispatch sparse readbacks through per-queue FIFO background workers that
wait on a raw per-queue fence outside STATE.lock() before invoking
readback_ranges, never stalling sparse::State::queue. Track active
unsatisfied queue.Wait calls via note_queue_wait (in q_wait_pc and the
Wait64BitValueX GPU bridge, cleaned up in q_release via forget_queue):
when the queue has an unsatisfied Wait, readback_after_execute returns
immediately while the worker finishes asynchronously; when no
unsatisfied Wait is active, readback_after_execute waits on the worker's
completion condvar outside STATE.lock() so CPU reads immediately after a
GPU fence wait (such as Write32BitValueBottomOfPipeX in testtitle)
always observe the updated bytes.

Snapshot per-64-byte-segment CPU hashes when recording each readback job
and skip copying any segment whose CPU bytes changed before the worker
runs, so a late/deferred readback never overwrites a newer title CPU
write and leaves `sent` dirty for the next upload while still allowing
consecutive deferred readbacks on the same range to land.

Assisted-by: Antigravity (Gemini 4 Neon)
@Decodere

Copy link
Copy Markdown
Contributor

Independent RTX 4060 (8 GB) / Windows 11 release verification of PR #1732 updated head f14d6976dcbe99dba07a34cbc2295b1d8690bc61 (4 commits on merge-base 08db8020d323bf478964fcc586152cce54959cfc; parent da893f3a68333efa1f7c39c0e91e896fb48f6178). Measurements and targeted GPU/unit test results only; not a full source review.

Setup

  • GPU: NVIDIA GeForce RTX 4060 (8 GB / 7956 MiB reported by D3D12), driver 32.0.16.2114 (NVIDIA 621.14, WDDM 3.2)
  • CPU / RAM / OS: Intel Core i5-11400F (6 cores / 12 threads), 32 GB RAM (31.9 GiB usable), Windows 11 Home 26200
  • Toolchain / caches: rustc 1.100.0 (0ef1bc386 2026-11-09), DXC 1.9.2609.5, release builds, warm DXIL/pipeline caches, quiet machine (zero concurrent builds/tests during timed runs)
  • Workload: Retail workload title: 29640639 via scripts/smoke.ps1 -Seconds 60 (XCL_NETWORK=0, default flags, no input)

Targeted RTX 4060 release unit & GPU tests (f14d6976)

  • cargo test --release -p xcl --lib readback_after_execute_does_not_block_on_stalled_queue -- --nocapture: 1 passed, 0 failed, 0 ignored (0.36 s, 0 SKIPPED).
  • cargo test --release -p xcl --lib internal_fence_wait_keeps_readback_synchronous -- --nocapture: 1 passed, 0 failed, 0 ignored (0.39 s, 0 SKIPPED).
  • cargo test --release -p xcl --lib timeout_then_completes_still_reads_back_cpu_memory -- --nocapture: 1 passed, 0 failed, 0 ignored (0.40 s, 0 SKIPPED).
  • cargo test --release -p xcl --lib deferred_readback_preserves_newer_cpu_writes -- --nocapture: 1 passed, 0 failed, 0 ignored (0.36 s, 0 SKIPPED).
  • cargo test --release -p xcl --lib hle::d3d12x::sparse:: (3 consecutive parallel passes): 22 passed, 0 failed, 1 ignored (early_commit_timing ignored) on all 3 passes (0.61 s / 0.62 s / 0.58 s, 0 SKIPPED).
  • cargo test --release -p xcl --lib hle::d3d12x::list_x::: 40 passed, 0 failed, 0 ignored (0.71 s, 0 SKIPPED).
  • cargo test --release -p xcl --lib hle::d3d12x::real::: 62 passed, 0 failed, 0 ignored (0.37 s, 0 SKIPPED).

Paired 60 s RTX 4060 smoke (merge-base 08db8020 vs f14d6976)

Both runs completed cleanly at steady 60/2 s pacing with 0 device removals and 0 crashes (f14d6976 xcl.log: 6,176 / 6,116 MB peak/end local VRAM, 4,650 MB end non-local VRAM, 19,567 translated draws / 1,024 dispatches with 0 skipped, sparse windows: 4096 submits, 1388 MB of CPU writes uploaded, 240 ms spent, lock wait 1 ms, 0 watchdog timeouts).

Merge-base (08db8020):

xcl-smoke v1
commit: 08db8020d323bf478964fcc586152cce54959cfc
gpu: NVIDIA GeForce RTX 4060
title: 29640639
seconds: 60
exit: 0x0
frames shown: 1588 (PresentX 1588)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 14000 MB

PR #1732 head (f14d6976):

xcl-smoke v1
commit: f14d6976dcbe99dba07a34cbc2295b1d8690bc61
gpu: NVIDIA GeForce RTX 4060
title: 29640639
seconds: 60
exit: 0x0
frames shown: 1608 (PresentX 1609)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 13983 MB

Limits of coverage

  • Full workspace test suite was not run on f14d6976 (only the 4 new readback tests individually, 3 parallel passes of sparse::, list_x::, real::, release build, and paired 60 s smokes).
  • Tested on native Windows 11 / NVIDIA RTX 4060 only; the Wine / vkd3d-proton / amdgpu commits earlier in this 4-commit branch (e57cb659, 1a7f146b, da893f3a) were not exercised under Wine/Linux on this host, and live async compute wait-before-signal stalls were covered by the 4 targeted release tests above rather than live stalls in the 60 s smoke.

AI use

Ran the targeted release GPU/unit tests, release build, and paired quiet 60 s smoke runs with assistance from Google Antigravity (Gemini 4 Neon); all test counts, timings, memory/sparse metrics, and smoke blocks were extracted directly from cargo test, xcl.log, and scripts/smoke.ps1 outputs.

@GreemSC

GreemSC commented Nov 26, 2026

Copy link
Copy Markdown

@gustavsi thanks for the fix and the test. A note so you don't wait on me for it: our current Linux tree is on amd-dev, which has its own per-queue readback (rb_queue), so it doesn't carry #1732 any more; the amd-dev tree, with the deferred readbacks of a queue waiting on an unsubmitted producer, is on #846. I'll rerun f14d6976 on the main tree when that one runs again (it is stuck in #2555's shader preparation under Wine for now).

AI use: Claude Code (Claude Opus 5.5) wrote this reply.

@gustavsi
gustavsi force-pushed the wine/async-sparse-readback branch from f14d697 to c992ec8 Compare November 26, 2026 20:15
gustavsi added a commit to gustavsi/xcl that referenced this pull request Nov 26, 2026
…add XCL_PREPARE=0 opt-out

Bring fork main in sync with the latest upstream PR review fixes:
- xcl-dev#867: UnadoptGuard COM +1 refcount pin, under_wine() gate on
  create_raw_fence, and track_end_title_fence for list_x cell fences.
- xcl-dev#2477: skips_guard helper and 10 s deadline loop in concurrent
  in-place vtable test.
- xcl-dev#1732: RbStatus + retained FIFO deferred retry and per-64-byte-segment
  RbSnapshot/last_rb CPU-write protection for async/deferred readbacks.
- present/preparation: allow XCL_PREPARE=0 (matching upstream nvidia-dev)
  to skip startup shader preparation during smoke runs and quick iterations.

Assisted-by: Antigravity (Gemini 4 Neon)
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.

9 participants