D3D12.X: flush tied texture downloads on SetEventOnCompletion and preserve u64::MAX removal #3389

Closed
Kalmarv wants to merge 1 commit from upstream-pr/3389 into main
Kalmarv commented 2026-11-29 12:40:41 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Kalmarv on 2026-11-29T12:40:41Z.


What changed

  • crates/xcl/src/hle/d3d12x/real.rs:
    • Added native_fence_set_event_on_completion to invoke the underlying PC ID3D12Fence::SetEventOnCompletion without re-entering XCL's hook for internal XCL wake events.
    • Updated fence_set_event_on_completion and fence_wait_fired so both blocking (event == NULL) and event-based (event != NULL) title waits flush and wait (bounded, with immediate exit on device removal u64::MAX) for GPU-to-CPU texture downloads tied to that fence/value before returning or signaling the title's event, dropping the cloned fence reference before SetEvent(w.title).
    • Activated event interception whenever sparse::readbacks_async() or title_textures::fence_event_intercept_needed() is true.
  • crates/xcl/src/hle/d3d12x/title_textures.rs:
    • Added FENCE_DOWNLOADS_CV, fence_event_intercept_needed, and wait_for_fence_downloads / wait_for_fence_downloads_with (notifying FENCE_DOWNLOADS_CV on finish_tie and both complete_fence_downloads completion paths, and using Release ordering on TEXTURES_LEN / GPU_WRITTEN updates).
    • Updated safe_fence_value to return u64::MAX immediately on device removal without poisoning SAFE_FENCE_VALUES or withholding removal behind pending downloads.
    • Switched internal PendingDownload::arm and tie_downloads event registration to real::native_fence_set_event_on_completion.
    • Added unit and real-GPU tests (safe_fence_value_preserves_device_removal_while_downloads_are_pending, wait_for_fence_downloads_waits_for_active_processing_and_exits_on_device_loss, fence_set_event_on_completion_publishes_gpu_texture_downloads).
  • crates/xcl/src/hle/d3d12x/fence_x.rs:
    • Updated FenceTable::refresh_one to publish u64::MAX to mirrored fence cells immediately on device removal even while texture downloads are pending.
    • Switched internal fence_x::arm registration to real::native_fence_set_event_on_completion.
    • Added refresh_publishes_device_removal_even_while_downloads_are_pending.

Why

  1. GPU-to-CPU texture downloads tied to a title fence were previously flushed only on GetCompletedValue and fence_x mirror refreshes, not on ID3D12Fence::SetEventOnCompletion (neither blocking event == NULL nor event-driven WaitForSingleObject). A title synchronizing GPU texture writes via SetEventOnCompletion could wake and read stale CPU texture memory before the tied download landed.
  2. When D3D12 device removal signaled GetCompletedValue() == u64::MAX while a texture download tie or processing pass was active, both title_textures::safe_fence_value and fence_x::FenceTable::refresh_one withheld u64::MAX behind complete_fence_downloads, potentially stalling title fence polls instead of surfacing device loss immediately.
  3. Internal XCL wake-event registrations in fence_x and title_textures went through the hooked SetEventOnCompletion vtable entry, causing unnecessary wrapper event / threadpool indirection when event interception was active.

Tested

Environment: Windows 11 Pro (Build 26200), AMD Ryzen 9 9950X, NVIDIA GeForce RTX 5070 Ti (driver 32.0.16.1074), rustc 1.99.0, DXC 1.9.2609.5.

  • cargo check --workspace --all-targets: passed (0 errors, 0 new warnings).
  • cargo test --workspace --no-run and cargo build --release -p xcl: passed.
  • Targeted unit + GPU tests on RTX 5070 Ti (cargo test -p xcl --lib "hle::d3d12x::fence_x::tests::" "hle::d3d12x::title_textures::tests::" filtered to the 13 fence/download tests): 13 passed, 0 failed (including all 4 new CPU and real-GPU tests covering SetEventOnCompletion(NULL), post-signal and wait-before-signal events, native bypass, active-processing wait, and u64::MAX device-removal propagation).
  • Full workspace GPU test suite (cargo test --workspace -- --test-threads=4, XCL_DXC_DIR set to DXC 1.9.2609.5): passed, exit 0, 0 failures.
  • 150 s real-title smoke run on daae6fd2 (note: 3 earlier runs hit the pre-existing main title watchdog crash during xcl-fences::write_changed_pages with 0 threads in our modified paths and 0 download-wait warnings; run 4 completed cleanly with 1765 frames, 0 removals, 0 crashes):
xcl-smoke v1
commit: daae6fd2ecd23746208eaafc87d2830fc4195dba
gpu: NVIDIA GeForce RTX 5070 Ti
title: ea3b5e4d
seconds: 150
exit: 0x0
frames shown: 1639 (PresentX 1639)
presents per 2 s (last 3): 0 0 0
device removals: 0
crashes: 0
peak commit: 34263 MB

Main-ancestor baseline on the same machine (f0e8fdd5):

xcl-smoke v1
commit: f0e8fdd5c3942ddd399d5ee11384c8595c5aacff
gpu: NVIDIA GeForce RTX 5070 Ti
title: ea3b5e4d
seconds: 150
exit: 0x0
frames shown: 1695 (PresentX 1695)
presents per 2 s (last 3): 0 0 0
device removals: 0
crashes: 0
peak commit: 31546 MB

Not tested

  • AMD or Intel GPUs, native wave64 hardware, Linux/Wine/vkd3d-proton, and other retail titles beyond the single 150 s smoke target.
  • A live hardware TDR / DXGI_ERROR_DEVICE_REMOVED event during an active multi-megabyte texture download (the u64::MAX removal paths are verified by synthetic CPU tests).

AI use

Used an AI coding assistant to investigate the fence/download paths, draft the patch and synthetic CPU/GPU tests, and run local verification; all changes and test outputs were reviewed and verified on local hardware.

<!-- greyfinch-sync:ivall/xcl:issue:5550797855 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3389). Originally posted by [Kalmarv](https://github.com/Kalmarv) on 2026-11-29T12:40:41Z. --- **What changed** - `crates/xcl/src/hle/d3d12x/real.rs`: - Added `native_fence_set_event_on_completion` to invoke the underlying PC `ID3D12Fence::SetEventOnCompletion` without re-entering XCL's hook for internal XCL wake events. - Updated `fence_set_event_on_completion` and `fence_wait_fired` so both blocking (`event == NULL`) and event-based (`event != NULL`) title waits flush and wait (bounded, with immediate exit on device removal `u64::MAX`) for GPU-to-CPU texture downloads tied to that fence/value before returning or signaling the title's event, dropping the cloned fence reference before `SetEvent(w.title)`. - Activated event interception whenever `sparse::readbacks_async()` or `title_textures::fence_event_intercept_needed()` is true. - `crates/xcl/src/hle/d3d12x/title_textures.rs`: - Added `FENCE_DOWNLOADS_CV`, `fence_event_intercept_needed`, and `wait_for_fence_downloads` / `wait_for_fence_downloads_with` (notifying `FENCE_DOWNLOADS_CV` on `finish_tie` and both `complete_fence_downloads` completion paths, and using `Release` ordering on `TEXTURES_LEN` / `GPU_WRITTEN` updates). - Updated `safe_fence_value` to return `u64::MAX` immediately on device removal without poisoning `SAFE_FENCE_VALUES` or withholding removal behind pending downloads. - Switched internal `PendingDownload::arm` and `tie_downloads` event registration to `real::native_fence_set_event_on_completion`. - Added unit and real-GPU tests (`safe_fence_value_preserves_device_removal_while_downloads_are_pending`, `wait_for_fence_downloads_waits_for_active_processing_and_exits_on_device_loss`, `fence_set_event_on_completion_publishes_gpu_texture_downloads`). - `crates/xcl/src/hle/d3d12x/fence_x.rs`: - Updated `FenceTable::refresh_one` to publish `u64::MAX` to mirrored fence cells immediately on device removal even while texture downloads are pending. - Switched internal `fence_x::arm` registration to `real::native_fence_set_event_on_completion`. - Added `refresh_publishes_device_removal_even_while_downloads_are_pending`. **Why** 1. GPU-to-CPU texture downloads tied to a title fence were previously flushed only on `GetCompletedValue` and `fence_x` mirror refreshes, not on `ID3D12Fence::SetEventOnCompletion` (neither blocking `event == NULL` nor event-driven `WaitForSingleObject`). A title synchronizing GPU texture writes via `SetEventOnCompletion` could wake and read stale CPU texture memory before the tied download landed. 2. When D3D12 device removal signaled `GetCompletedValue() == u64::MAX` while a texture download tie or processing pass was active, both `title_textures::safe_fence_value` and `fence_x::FenceTable::refresh_one` withheld `u64::MAX` behind `complete_fence_downloads`, potentially stalling title fence polls instead of surfacing device loss immediately. 3. Internal XCL wake-event registrations in `fence_x` and `title_textures` went through the hooked `SetEventOnCompletion` vtable entry, causing unnecessary wrapper event / threadpool indirection when event interception was active. **Tested** Environment: Windows 11 Pro (Build 26200), AMD Ryzen 9 9950X, NVIDIA GeForce RTX 5070 Ti (driver 32.0.16.1074), rustc 1.99.0, DXC 1.9.2609.5. - `cargo check --workspace --all-targets`: passed (0 errors, 0 new warnings). - `cargo test --workspace --no-run` and `cargo build --release -p xcl`: passed. - Targeted unit + GPU tests on RTX 5070 Ti (`cargo test -p xcl --lib "hle::d3d12x::fence_x::tests::" "hle::d3d12x::title_textures::tests::"` filtered to the 13 fence/download tests): 13 passed, 0 failed (including all 4 new CPU and real-GPU tests covering `SetEventOnCompletion(NULL)`, post-signal and wait-before-signal events, native bypass, active-processing wait, and `u64::MAX` device-removal propagation). - Full workspace GPU test suite (`cargo test --workspace -- --test-threads=4`, `XCL_DXC_DIR` set to DXC 1.9.2609.5): passed, exit 0, 0 failures. - 150 s real-title smoke run on `daae6fd2` (note: 3 earlier runs hit the pre-existing `main` title watchdog crash during `xcl-fences::write_changed_pages` with 0 threads in our modified paths and 0 download-wait warnings; run 4 completed cleanly with 1765 frames, 0 removals, 0 crashes): ``` xcl-smoke v1 commit: daae6fd2ecd23746208eaafc87d2830fc4195dba gpu: NVIDIA GeForce RTX 5070 Ti title: ea3b5e4d seconds: 150 exit: 0x0 frames shown: 1639 (PresentX 1639) presents per 2 s (last 3): 0 0 0 device removals: 0 crashes: 0 peak commit: 34263 MB ``` Main-ancestor baseline on the same machine (`f0e8fdd5`): ``` xcl-smoke v1 commit: f0e8fdd5c3942ddd399d5ee11384c8595c5aacff gpu: NVIDIA GeForce RTX 5070 Ti title: ea3b5e4d seconds: 150 exit: 0x0 frames shown: 1695 (PresentX 1695) presents per 2 s (last 3): 0 0 0 device removals: 0 crashes: 0 peak commit: 31546 MB ``` **Not tested** - AMD or Intel GPUs, native wave64 hardware, Linux/Wine/vkd3d-proton, and other retail titles beyond the single 150 s smoke target. - A live hardware TDR / `DXGI_ERROR_DEVICE_REMOVED` event during an active multi-megabyte texture download (the `u64::MAX` removal paths are verified by synthetic CPU tests). **AI use** Used an AI coding assistant to investigate the fence/download paths, draft the patch and synthetic CPU/GPU tests, and run local verification; all changes and test outputs were reviewed and verified on local hardware.
saintwolf commented 2026-11-29 14:20:56 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by saintwolf on 2026-11-29T14:20:56Z.


Reviewed and tested at daae6fd2.

Code review findings

  1. Aliasing UB in fence_wait_fired (crates/xcl/src/hle/d3d12x/real.rs): Converting ctx via let mut w = Box::from_raw(ctx as *mut FenceWait); at the top of fence_wait_fired — before the while w.wait.load(Ordering::Acquire) == 0 spinloop — creates a unique Box<FenceWait> while fence_set_event_on_completion on the calling thread may still be concurrently writing (*w).wait.store(wh as usize, Ordering::Release) through the raw pointer. The original code deliberately kept w as *mut FenceWait until after wh != 0 and UnregisterWaitEx, only calling drop(Box::from_raw(w)) at the very end. Please keep raw-pointer access ((*w).fence.take() etc.) until after the spinloop finishes.
  2. Thread-pool + CreateEventW overhead on every non-null SetEventOnCompletion (crates/xcl/src/hle/d3d12x/title_textures.rs): fence_event_intercept_needed() returns true whenever TEXTURES_LEN != 0, which is permanently true as soon as any title texture is registered. That forces every non-null SetEventOnCompletion call in the title to allocate a Win32 CreateEventW, clone an ID3D12Fence, heap-allocate Box<FenceWait>, and go through RegisterWaitForSingleObject / thread pool even when GPU_WRITTEN == 0 and no downloads exist.

Tested locally

  • Windows 11 (build 26300), NVIDIA GeForce RTX 4070 SUPER (driver 32.0.16.2140), AMD Ryzen 7 7800X3D, rustc 1.100.0.
  • cargo test -p xcl --lib hle::d3d12x::fence_x::tests::refresh_publishes_device_removal -- --test-threads=1: 1 passed, 0 failed.
  • cargo test -p xcl --lib hle::d3d12x::title_textures::tests::safe_fence_value_preserves_device_removal -- --test-threads=1: 1 passed, 0 failed.
  • cargo test -p xcl --lib hle::d3d12x::title_textures::tests::wait_for_fence_downloads_waits_for_active_processing -- --test-threads=1: 1 passed, 0 failed.
  • cargo test -p xcl --lib hle::d3d12x::title_textures::tests::fence_set_event_on_completion_publishes_gpu_texture_downloads -- --test-threads=1: 1 passed, 0 failed.

AI use

  • Antigravity (Gemini 4 Neon) assisted with code review and drafting; all builds and tests were executed locally on the hardware above.
<!-- greyfinch-sync:ivall/xcl:comment:7257232965 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3389#issuecomment-7257232965). Originally posted by [saintwolf](https://github.com/saintwolf) on 2026-11-29T14:20:56Z. --- Reviewed and tested at `daae6fd2`. ### Code review findings 1. **Aliasing UB in `fence_wait_fired` (`crates/xcl/src/hle/d3d12x/real.rs`)**: Converting `ctx` via `let mut w = Box::from_raw(ctx as *mut FenceWait);` at the **top** of `fence_wait_fired` — **before** the `while w.wait.load(Ordering::Acquire) == 0` spinloop — creates a unique `Box<FenceWait>` while `fence_set_event_on_completion` on the calling thread may still be concurrently writing `(*w).wait.store(wh as usize, Ordering::Release)` through the raw pointer. The original code deliberately kept `w` as `*mut FenceWait` until *after* `wh != 0` and `UnregisterWaitEx`, only calling `drop(Box::from_raw(w))` at the very end. Please keep raw-pointer access (`(*w).fence.take()` etc.) until after the spinloop finishes. 2. **Thread-pool + `CreateEventW` overhead on every non-null `SetEventOnCompletion` (`crates/xcl/src/hle/d3d12x/title_textures.rs`)**: `fence_event_intercept_needed()` returns `true` whenever `TEXTURES_LEN != 0`, which is permanently true as soon as any title texture is registered. That forces every non-null `SetEventOnCompletion` call in the title to allocate a Win32 `CreateEventW`, clone an `ID3D12Fence`, heap-allocate `Box<FenceWait>`, and go through `RegisterWaitForSingleObject` / thread pool even when `GPU_WRITTEN == 0` and no downloads exist. ### Tested locally - Windows 11 (build 26300), NVIDIA GeForce RTX 4070 SUPER (driver `32.0.16.2140`), AMD Ryzen 7 7800X3D, `rustc 1.100.0`. - `cargo test -p xcl --lib hle::d3d12x::fence_x::tests::refresh_publishes_device_removal -- --test-threads=1`: **1 passed, 0 failed**. - `cargo test -p xcl --lib hle::d3d12x::title_textures::tests::safe_fence_value_preserves_device_removal -- --test-threads=1`: **1 passed, 0 failed**. - `cargo test -p xcl --lib hle::d3d12x::title_textures::tests::wait_for_fence_downloads_waits_for_active_processing -- --test-threads=1`: **1 passed, 0 failed**. - `cargo test -p xcl --lib hle::d3d12x::title_textures::tests::fence_set_event_on_completion_publishes_gpu_texture_downloads -- --test-threads=1`: **1 passed, 0 failed**. ### AI use - Antigravity (Gemini 4 Neon) assisted with code review and drafting; all builds and tests were executed locally on the hardware above.
andrewDoing commented 2026-11-29 19:33:08 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by andrewDoing on 2026-11-29T19:33:08Z.


I checked the blocking SetEventOnCompletion(value, NULL) path with a real D3D12 texture readback and a late destination on RTX 5070. I tested main 0fe06eb0 and the same main with the three-file PR delta applied (head daae6fd2, GitHub merge delta 7a649b0e..f68cd29b). Native GPU completion was already 1 before each title wait. The CPU destination was reserved-only, and a separate thread committed it on the controlled schedule without making any new GPU submission.

Path Time in blocking call Destination when the call returned
Main 0.027 ms Still reserved at return
PR applied, destination committed about 120 ms later 130.096 ms Committed, all 4,096 texels already published
PR applied, destination held beyond the bound 2,009.927 ms Still reserved at return, call returned success

The short-delay case confirms the bounded retry can publish a tied download without another GPU submission. In the timeout case, after committing the address I saw zero expected texels before a manual retry and all 4,096 after it. The timeout still returns native success, so code relying on that return alone cannot distinguish it from the published case.

cargo test --offline --locked -p xcl --lib -- gpu_blocking_fence_wait_with_late_texture_destination --test-threads=1 --nocapture: one pass per case, zero skips. RTX 5070 12 GB (616.92), Ryzen 7 5700X3D, Windows 11 26300.10075, Rust 1.100.0, debug. The test covers the blocking path and synthetic destination timing. It does not exercise thread-pool event interception or a retail title. Codex with GPT-6.2 Sol adapted and ran the fixture.

<!-- greyfinch-sync:ivall/xcl:comment:7261369411 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3389#issuecomment-7261369411). Originally posted by [andrewDoing](https://github.com/andrewDoing) on 2026-11-29T19:33:08Z. --- I checked the blocking `SetEventOnCompletion(value, NULL)` path with a real D3D12 texture readback and a late destination on RTX 5070. I tested main `0fe06eb0` and the same main with the three-file PR delta applied (head `daae6fd2`, GitHub merge delta `7a649b0e..f68cd29b`). Native GPU completion was already 1 before each title wait. The CPU destination was reserved-only, and a separate thread committed it on the controlled schedule without making any new GPU submission. | Path | Time in blocking call | Destination when the call returned | | --- | ---: | --- | | Main | 0.027 ms | Still reserved at return | | PR applied, destination committed about 120 ms later | 130.096 ms | Committed, all 4,096 texels already published | | PR applied, destination held beyond the bound | 2,009.927 ms | Still reserved at return, call returned success | The short-delay case confirms the bounded retry can publish a tied download without another GPU submission. In the timeout case, after committing the address I saw zero expected texels before a manual retry and all 4,096 after it. The timeout still returns native success, so code relying on that return alone cannot distinguish it from the published case. `cargo test --offline --locked -p xcl --lib -- gpu_blocking_fence_wait_with_late_texture_destination --test-threads=1 --nocapture`: one pass per case, zero skips. RTX 5070 12 GB (616.92), Ryzen 7 5700X3D, Windows 11 26300.10075, Rust 1.100.0, debug. The test covers the blocking path and synthetic destination timing. It does not exercise thread-pool event interception or a retail title. Codex with GPT-6.2 Sol adapted and ran the fixture.
Foniass commented 2026-12-01 03:28:01 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-01T03:28:01Z.


Review (head e348eb0d, diff read, not a merge-check: the PR description check fails, so not built or run here yet):

  • The PR's smoke block is on daae6fd2, not the head e348eb0d, which is why PR description fails. The description also says 3 of 4 runs crashed in xcl-fences::write_changed_pages and calls that a pre-existing crash on main, but the main run shown is clean. Since this PR now drives that same publish path from title threads and thread-pool callbacks too, a main run that shows the crash (or a clean PR run) is needed to rule it out.
  • Cost on the default path, not measured. The wrapper turns on as soon as any title texture is registered (real.rs ~11931, title_textures.rs ~4186-4190), which is nearly always in a game. Every title wait with an event then costs an extra event, a thread-pool wait and a thread hop, including XCL's own waits on title fences (cpu_writes.rs ~74).
  • 2 s stall with busy retry. If a download can't be written (page not committed or not writable, or Err), each wait on that fence holds a title thread or pool worker for up to 2 s, redoing the readback and re-layout about every 1 ms, then fires the event with stale data anyway (title_textures.rs ~4199-4240). On main event waits weren't delayed. A bounded single retry, or firing at once and logging, would avoid that.
  • The GPU test can pass on main: tie_downloads also wakes the xcl-fences thread, which publishes the same downloads concurrently. It skips with println! instead of skip_test.
  • The wait context now holds a fence reference (real.rs ~11952), so a wait whose value is never reached keeps the fence and its device alive.
  • Scope: the u64::MAX fix is independent of the download flush and could be its own PR. AI use names no tool or model, and Tested has no pass/fail/ignored counts.

Fine: the u64::MAX (device removed) handling is right and its unit tests fail on main. No lock-order inversion found. The native SetEventOnCompletion helper follows native_fence_completed, and the fence reference is dropped before the title's event is set.

AI review: Claude Code (Claude Opus 5.5), posted by Foniass without a human check of each point.

<!-- greyfinch-sync:ivall/xcl:comment:7299734300 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3389#issuecomment-7299734300). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-01T03:28:01Z. --- Review (head e348eb0d, diff read, not a merge-check: the `PR description` check fails, so not built or run here yet): - **The PR's smoke block is on daae6fd2, not the head e348eb0d**, which is why `PR description` fails. The description also says 3 of 4 runs crashed in `xcl-fences::write_changed_pages` and calls that a pre-existing crash on main, but the main run shown is clean. Since this PR now drives that same publish path from title threads and thread-pool callbacks too, a main run that shows the crash (or a clean PR run) is needed to rule it out. - **Cost on the default path, not measured.** The wrapper turns on as soon as any title texture is registered (`real.rs` ~11931, `title_textures.rs` ~4186-4190), which is nearly always in a game. Every title wait with an event then costs an extra event, a thread-pool wait and a thread hop, including XCL's own waits on title fences (`cpu_writes.rs` ~74). - **2 s stall with busy retry.** If a download can't be written (page not committed or not writable, or `Err`), each wait on that fence holds a title thread or pool worker for up to 2 s, redoing the readback and re-layout about every 1 ms, then fires the event with stale data anyway (`title_textures.rs` ~4199-4240). On main event waits weren't delayed. A bounded single retry, or firing at once and logging, would avoid that. - The GPU test can pass on main: `tie_downloads` also wakes the `xcl-fences` thread, which publishes the same downloads concurrently. It skips with `println!` instead of `skip_test`. - The wait context now holds a fence reference (`real.rs` ~11952), so a wait whose value is never reached keeps the fence and its device alive. - Scope: the `u64::MAX` fix is independent of the download flush and could be its own PR. AI use names no tool or model, and **Tested** has no pass/fail/ignored counts. Fine: the `u64::MAX` (device removed) handling is right and its unit tests fail on main. No lock-order inversion found. The native SetEventOnCompletion helper follows `native_fence_completed`, and the fence reference is dropped before the title's event is set. AI review: Claude Code (Claude Opus 5.5), posted by Foniass without a human check of each point.
Foniass commented 2026-12-01 15:47:49 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-01T15:47:49Z.


Test report (not a merge-check: PR description red)
base: b2b1f109d2
head: e348eb0dc2
merge: clean
build: cargo build --workspace -> ok
tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 2906 passed, 0 failed, 51 ignored; SKIPPED: 28 (20 no wave64, 2 no d3d12SDKLayers.dll, 1 no D3D12 debug layer, 1 no heap windows, 1 cannot disable the driver cache, 3 others; the same set as on main); failing: none
review: not repeated here; my review of this same head is at https://github.com/xcl-dev/xcl/pull/3389#issuecomment-7299734300, and its findings stand. This run adds what reading couldn't: whether the change merges, builds and passes the whole suite on current main.
performance: no smoke run.
assessment: merges, builds and passes the whole suite on current main; the findings in my review stand
hardware / tool and model: RTX 5070 Ti (driver 621.14), Ryzen 7 7800X3D, Windows 11 26300 / Claude Code with Claude Opus 5.5

AI-written and posted by Foniass without a human check of each point.

<!-- greyfinch-sync:ivall/xcl:comment:7316520121 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3389#issuecomment-7316520121). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-01T15:47:49Z. --- Test report (not a merge-check: `PR description` red) base: b2b1f109d27e746a62ec95b04dd1f9924452e682 head: e348eb0dc23c002ff2112351a50553dc2c19a3c9 merge: clean build: cargo build --workspace -> ok tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 2906 passed, 0 failed, 51 ignored; SKIPPED: 28 (20 no wave64, 2 no d3d12SDKLayers.dll, 1 no D3D12 debug layer, 1 no heap windows, 1 cannot disable the driver cache, 3 others; the same set as on main); failing: none review: not repeated here; my review of this same head is at https://github.com/xcl-dev/xcl/pull/3389#issuecomment-7299734300, and its findings stand. This run adds what reading couldn't: whether the change merges, builds and passes the whole suite on current main. performance: no smoke run. assessment: merges, builds and passes the whole suite on current main; the findings in my review stand hardware / tool and model: RTX 5070 Ti (driver 621.14), Ryzen 7 7800X3D, Windows 11 26300 / Claude Code with Claude Opus 5.5 AI-written and posted by Foniass without a human check of each point.
bmjask commented 2026-12-02 03:13:26 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T03:13:26Z.

Review: COMMENTED


Review of e348eb0d: 4 finding(s). 4 are inline.


These findings come from an AI-assisted review (Claude Code) and focus on correctness. Each is a candidate; please check it before acting on it.

<!-- greyfinch-sync:ivall/xcl:review:6144176930 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3389#pullrequestreview-6144176930). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T03:13:26Z. **Review:** COMMENTED --- Review of `e348eb0d`: 4 finding(s). 4 are inline. --- _These findings come from an AI-assisted review (Claude Code) and focus on correctness. Each is a candidate; please check it before acting on it._
bmjask commented 2026-12-02 03:13:27 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T03:13:27Z.

Code review location: crates/xcl/src/hle/d3d12x/title_textures.rs; line 4186

@@ -4169,22 +4176,102 @@ pub(super) fn complete_fence_downloads(fence: usize, value: u64) -> bool {
             note_safe_value(&mut SAFE_FENCE_VALUES.lock().unwrap(), fence, value);
         }
         DOWNLOADS_PENDING.store(state.any_pending(), Ordering::Release);
+        FENCE_DOWNLOADS_CV.notify_all();
     }
     ok
 }
 
+/// Whether `ID3D12Fence::SetEventOnCompletion` needs an XCL completion wrapper so GPU-to-CPU
+/// texture downloads tied to the fence land before the title's event fires.
+pub(super) fn fence_event_intercept_needed() -> bool {

fence_event_intercept_needed() is true almost all the time, because GPU_WRITTEN only goes up and TEXTURES_LEN != 0 once any texture is registered. So every title SetEventOnCompletion(value, event) now takes the wrapper path (CreateEventW + RegisterWaitForSingleObject + fence AddRef/Release), and the title's event is set from a thread-pool callback, even when no download is tied to that fence. Before, this only happened with readbacks_async(). It also changes behaviour: SetEventOnCompletion on an already-completed value followed by WaitForSingleObject(ev, 0) now returns WAIT_TIMEOUT, where native D3D12 sets the event synchronously. The smoke run's 1639 vs 1695 frames and +2.7 GB peak commit may be related. Intercepting only when a download is actually tied to that fence would avoid it.

<!-- greyfinch-sync:ivall/xcl:review-comment:4764232755 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3389#discussion_r4764232755). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T03:13:27Z. **Code review location:** `crates/xcl/src/hle/d3d12x/title_textures.rs`; line 4186 ~~~~diff @@ -4169,22 +4176,102 @@ pub(super) fn complete_fence_downloads(fence: usize, value: u64) -> bool { note_safe_value(&mut SAFE_FENCE_VALUES.lock().unwrap(), fence, value); } DOWNLOADS_PENDING.store(state.any_pending(), Ordering::Release); + FENCE_DOWNLOADS_CV.notify_all(); } ok } +/// Whether `ID3D12Fence::SetEventOnCompletion` needs an XCL completion wrapper so GPU-to-CPU +/// texture downloads tied to the fence land before the title's event fires. +pub(super) fn fence_event_intercept_needed() -> bool { ~~~~ --- `fence_event_intercept_needed()` is true almost all the time, because GPU_WRITTEN only goes up and TEXTURES_LEN != 0 once any texture is registered. So every title SetEventOnCompletion(value, event) now takes the wrapper path (CreateEventW + RegisterWaitForSingleObject + fence AddRef/Release), and the title's event is set from a thread-pool callback, even when no download is tied to that fence. Before, this only happened with readbacks_async(). It also changes behaviour: SetEventOnCompletion on an already-completed value followed by WaitForSingleObject(ev, 0) now returns WAIT_TIMEOUT, where native D3D12 sets the event synchronously. The smoke run's 1639 vs 1695 frames and +2.7 GB peak commit may be related. Intercepting only when a download is actually tied to that fence would avoid it.
bmjask commented 2026-12-02 03:13:27 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T03:13:27Z.

Code review location: crates/xcl/src/hle/d3d12x/real.rs; line 11931

@@ -11898,31 +11921,43 @@ unsafe extern "system" fn fence_wait_fired(ctx: *mut c_void, _timed_out: bool) {
     drop(Box::from_raw(w));
 }
 
-/// Fence::SetEventOnCompletion. Once copies back land asynchronously, the title's event is set
-/// after the fence is reached and the copies back it covers landed: the fence sets an event of
-/// XCL's own, and a thread-pool wait on that settles them and sets the title's. A null event
-/// (a blocking wait) settles them after it.
+/// Fence::SetEventOnCompletion. When sparse readbacks or GPU-to-CPU texture downloads can land
+/// asynchronously, the title's event is set only after the fence is reached and any copies/texture
+/// downloads it covers have landed: the fence sets an event of XCL's own, and a thread-pool wait
+/// on that settles them and sets the title's. A null event (a blocking wait) settles them after it.
 unsafe extern "system" fn fence_set_event_on_completion(this: *mut c_void, value: u64, event: *mut c_void) -> HRESULT {
     use windows_sys::Win32::System::Threading::{CreateEventW, RegisterWaitForSingleObject, UnregisterWaitEx, INFINITE, WT_EXECUTEONLYONCE};
     let f: unsafe extern "system" fn(*mut c_void, u64, *mut c_void) -> HRESULT = std::mem::transmute(orig_fn(this, pc_slot!("ID3D12Fence", "SetEventOnCompletion")));
-    if event.is_null() || !super::sparse::readbacks_async() {
+    if event.is_null() || (!super::sparse::readbacks_async() && !super::title_textures::fence_event_intercept_needed()) {

Whether to intercept is decided once, when SetEventOnCompletion is registered, so the fix misses a common order. At startup (TEXTURES_LEN == 0, nothing pending) the title calls SetEventOnCompletion(v, ev), then registers and GPU-writes a texture, then queue->Signal(fence, v) ties a download. The native event fires as soon as the GPU reaches v, and the title reads stale CPU texture memory, which is the bug this PR fixes.

<!-- greyfinch-sync:ivall/xcl:review-comment:4764232763 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3389#discussion_r4764232763). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T03:13:27Z. **Code review location:** `crates/xcl/src/hle/d3d12x/real.rs`; line 11931 ~~~~diff @@ -11898,31 +11921,43 @@ unsafe extern "system" fn fence_wait_fired(ctx: *mut c_void, _timed_out: bool) { drop(Box::from_raw(w)); } -/// Fence::SetEventOnCompletion. Once copies back land asynchronously, the title's event is set -/// after the fence is reached and the copies back it covers landed: the fence sets an event of -/// XCL's own, and a thread-pool wait on that settles them and sets the title's. A null event -/// (a blocking wait) settles them after it. +/// Fence::SetEventOnCompletion. When sparse readbacks or GPU-to-CPU texture downloads can land +/// asynchronously, the title's event is set only after the fence is reached and any copies/texture +/// downloads it covers have landed: the fence sets an event of XCL's own, and a thread-pool wait +/// on that settles them and sets the title's. A null event (a blocking wait) settles them after it. unsafe extern "system" fn fence_set_event_on_completion(this: *mut c_void, value: u64, event: *mut c_void) -> HRESULT { use windows_sys::Win32::System::Threading::{CreateEventW, RegisterWaitForSingleObject, UnregisterWaitEx, INFINITE, WT_EXECUTEONLYONCE}; let f: unsafe extern "system" fn(*mut c_void, u64, *mut c_void) -> HRESULT = std::mem::transmute(orig_fn(this, pc_slot!("ID3D12Fence", "SetEventOnCompletion"))); - if event.is_null() || !super::sparse::readbacks_async() { + if event.is_null() || (!super::sparse::readbacks_async() && !super::title_textures::fence_event_intercept_needed()) { ~~~~ --- Whether to intercept is decided once, when SetEventOnCompletion is registered, so the fix misses a common order. At startup (TEXTURES_LEN == 0, nothing pending) the title calls SetEventOnCompletion(v, ev), then registers and GPU-writes a texture, then `queue->Signal(fence, v)` ties a download. The native event fires as soon as the GPU reaches v, and the title reads stale CPU texture memory, which is the bug this PR fixes.
bmjask commented 2026-12-02 03:13:27 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T03:13:27Z.

Code review location: crates/xcl/src/hle/d3d12x/title_textures.rs; line 4237

@@ -4169,22 +4176,102 @@ pub(super) fn complete_fence_downloads(fence: usize, value: u64) -> bool {
             note_safe_value(&mut SAFE_FENCE_VALUES.lock().unwrap(), fence, value);
         }
         DOWNLOADS_PENDING.store(state.any_pending(), Ordering::Release);
+        FENCE_DOWNLOADS_CV.notify_all();
     }
     ok
 }
 
+/// Whether `ID3D12Fence::SetEventOnCompletion` needs an XCL completion wrapper so GPU-to-CPU
+/// texture downloads tied to the fence land before the title's event fires.
+pub(super) fn fence_event_intercept_needed() -> bool {
+    DOWNLOADS_PENDING.load(Ordering::Acquire)
+        || GPU_WRITTEN.load(Ordering::Acquire) != 0
+        || TEXTURES_LEN.load(Ordering::Acquire) != 0
+}
+
+/// Wait (bounded) until all GPU-to-CPU texture downloads tied to `(fence, <= value)` have been
+/// published into title memory, or until `device_lost` reports device removal (`u64::MAX`).
+pub(super) fn wait_for_fence_downloads(fence: usize, value: u64, device_lost: impl Fn() -> bool) -> bool {
+    wait_for_fence_downloads_with(fence, value, std::time::Duration::from_secs(2), device_lost)
+}
+
+fn wait_for_fence_downloads_with(
+    fence: usize,
+    value: u64,
+    timeout: std::time::Duration,
+    device_lost: impl Fn() -> bool,
+) -> bool {
+    if !DOWNLOADS_PENDING.load(Ordering::Acquire) {
+        return true;
+    }
+    if value == u64::MAX || device_lost() {
+        return false;
+    }
+    if complete_fence_downloads(fence, value) {
+        return true;
+    }
+    let deadline = std::time::Instant::now() + timeout;
+    loop {
+        let now = std::time::Instant::now();
+        if now >= deadline {
+            crate::xlog_warn!("D3D12.X: timed out waiting for texture downloads on fence {fence:#x} at {value:#x}");
+            return false;
+        }
+        let slice = deadline.saturating_duration_since(now).min(std::time::Duration::from_millis(1));
+        {
+            let state = FENCE_DOWNLOADS.lock().unwrap();
+            let busy = state.processing.contains(&fence) || state.tie_in_progress(fence);
+            let pending_for_value = matching_through(&state.batches, value, |batch| {
+                (batch.fence.as_raw() as usize == fence).then_some(batch.value)
+            });
+            if busy || pending_for_value {
+                let _ = FENCE_DOWNLOADS_CV.wait_timeout(state, slice).unwrap();
+            }
+        }
+        if !DOWNLOADS_PENDING.load(Ordering::Acquire) {
+            return true;
+        }
+        if device_lost() {
+            return false;
+        }
+        if complete_fence_downloads(fence, value) {

If publishing keeps failing (write_changed_pages returns false or publish_download errs, e.g. the title protected or unmapped a page), wait_for_fence_downloads_with calls complete_fence_downloads about every 1 ms for the full 2 s. Each pass redoes the readback Map/copy/reverse-layout/compare and logs another warning. A blocking SetEventOnCompletion(v, NULL) then burns a core for 2 s, writes up to ~2000 warnings, and stalls the title thread 2 s on every such wait, every frame if the title waits each frame. Before, GetCompletedValue just withheld the value cheaply.

<!-- greyfinch-sync:ivall/xcl:review-comment:4764232768 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3389#discussion_r4764232768). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T03:13:27Z. **Code review location:** `crates/xcl/src/hle/d3d12x/title_textures.rs`; line 4237 ~~~~diff @@ -4169,22 +4176,102 @@ pub(super) fn complete_fence_downloads(fence: usize, value: u64) -> bool { note_safe_value(&mut SAFE_FENCE_VALUES.lock().unwrap(), fence, value); } DOWNLOADS_PENDING.store(state.any_pending(), Ordering::Release); + FENCE_DOWNLOADS_CV.notify_all(); } ok } +/// Whether `ID3D12Fence::SetEventOnCompletion` needs an XCL completion wrapper so GPU-to-CPU +/// texture downloads tied to the fence land before the title's event fires. +pub(super) fn fence_event_intercept_needed() -> bool { + DOWNLOADS_PENDING.load(Ordering::Acquire) + || GPU_WRITTEN.load(Ordering::Acquire) != 0 + || TEXTURES_LEN.load(Ordering::Acquire) != 0 +} + +/// Wait (bounded) until all GPU-to-CPU texture downloads tied to `(fence, <= value)` have been +/// published into title memory, or until `device_lost` reports device removal (`u64::MAX`). +pub(super) fn wait_for_fence_downloads(fence: usize, value: u64, device_lost: impl Fn() -> bool) -> bool { + wait_for_fence_downloads_with(fence, value, std::time::Duration::from_secs(2), device_lost) +} + +fn wait_for_fence_downloads_with( + fence: usize, + value: u64, + timeout: std::time::Duration, + device_lost: impl Fn() -> bool, +) -> bool { + if !DOWNLOADS_PENDING.load(Ordering::Acquire) { + return true; + } + if value == u64::MAX || device_lost() { + return false; + } + if complete_fence_downloads(fence, value) { + return true; + } + let deadline = std::time::Instant::now() + timeout; + loop { + let now = std::time::Instant::now(); + if now >= deadline { + crate::xlog_warn!("D3D12.X: timed out waiting for texture downloads on fence {fence:#x} at {value:#x}"); + return false; + } + let slice = deadline.saturating_duration_since(now).min(std::time::Duration::from_millis(1)); + { + let state = FENCE_DOWNLOADS.lock().unwrap(); + let busy = state.processing.contains(&fence) || state.tie_in_progress(fence); + let pending_for_value = matching_through(&state.batches, value, |batch| { + (batch.fence.as_raw() as usize == fence).then_some(batch.value) + }); + if busy || pending_for_value { + let _ = FENCE_DOWNLOADS_CV.wait_timeout(state, slice).unwrap(); + } + } + if !DOWNLOADS_PENDING.load(Ordering::Acquire) { + return true; + } + if device_lost() { + return false; + } + if complete_fence_downloads(fence, value) { ~~~~ --- If publishing keeps failing (`write_changed_pages` returns false or `publish_download` errs, e.g. the title protected or unmapped a page), `wait_for_fence_downloads_with` calls `complete_fence_downloads` about every 1 ms for the full 2 s. Each pass redoes the readback Map/copy/reverse-layout/compare and logs another warning. A blocking SetEventOnCompletion(v, NULL) then burns a core for 2 s, writes up to ~2000 warnings, and stalls the title thread 2 s on every such wait, every frame if the title waits each frame. Before, GetCompletedValue just withheld the value cheaply.
bmjask commented 2026-12-02 03:13:27 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T03:13:27Z.

Code review location: crates/xcl/src/hle/d3d12x/real.rs; line 11906

@@ -11874,18 +11886,29 @@ unsafe extern "system" fn fence_get_completed_value(this: *mut c_void) -> u64 {
     super::title_textures::safe_fence_value(this as usize, v)
 }
 
-/// A `fence_set_event_on_completion` wait: the title's event, XCL's own event the fence sets, and
-/// the thread-pool wait on it (0 until registered)
+/// A `fence_set_event_on_completion` wait: the fence/value being awaited, the title's event,
+/// XCL's own event the fence sets, and the thread-pool wait on it (0 until registered).
 struct FenceWait {
+    fence: Option<ID3D12Fence>,
+    fence_key: usize,
+    value: u64,
     own: *mut c_void,
     title: *mut c_void,
     wait: AtomicUsize,
 }
 
 unsafe extern "system" fn fence_wait_fired(ctx: *mut c_void, _timed_out: bool) {
     use windows_sys::Win32::System::Threading::{SetEvent, UnregisterWaitEx};
+    // (a pointer, not a Box, until the registering thread has stored `wait`: it may still be
+    // writing it while this runs)
     let w = ctx as *mut FenceWait;
     super::sparse::settle_readbacks_try();
+    let _ = super::title_textures::wait_for_fence_downloads((*w).fence_key, (*w).value, || {

fence_wait_fired now blocks its thread-pool worker for up to 2 s in wait_for_fence_downloads, but the wait is registered without WT_EXECUTELONGFUNCTION (~11962). With several frame or async-compute waits in flight while downloads are slow, each callback holds a default pool worker the pool doesn't know is long-running. Other wait callbacks, including XCL's own, queue behind them, so title events are delayed far more than the download time.

<!-- greyfinch-sync:ivall/xcl:review-comment:4764232775 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3389#discussion_r4764232775). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T03:13:27Z. **Code review location:** `crates/xcl/src/hle/d3d12x/real.rs`; line 11906 ~~~~diff @@ -11874,18 +11886,29 @@ unsafe extern "system" fn fence_get_completed_value(this: *mut c_void) -> u64 { super::title_textures::safe_fence_value(this as usize, v) } -/// A `fence_set_event_on_completion` wait: the title's event, XCL's own event the fence sets, and -/// the thread-pool wait on it (0 until registered) +/// A `fence_set_event_on_completion` wait: the fence/value being awaited, the title's event, +/// XCL's own event the fence sets, and the thread-pool wait on it (0 until registered). struct FenceWait { + fence: Option<ID3D12Fence>, + fence_key: usize, + value: u64, own: *mut c_void, title: *mut c_void, wait: AtomicUsize, } unsafe extern "system" fn fence_wait_fired(ctx: *mut c_void, _timed_out: bool) { use windows_sys::Win32::System::Threading::{SetEvent, UnregisterWaitEx}; + // (a pointer, not a Box, until the registering thread has stored `wait`: it may still be + // writing it while this runs) let w = ctx as *mut FenceWait; super::sparse::settle_readbacks_try(); + let _ = super::title_textures::wait_for_fence_downloads((*w).fence_key, (*w).value, || { ~~~~ --- `fence_wait_fired` now blocks its thread-pool worker for up to 2 s in `wait_for_fence_downloads`, but the wait is registered without WT_EXECUTELONGFUNCTION (~11962). With several frame or async-compute waits in flight while downloads are slow, each callback holds a default pool worker the pool doesn't know is long-running. Other wait callbacks, including XCL's own, queue behind them, so title events are delayed far more than the download time.
Kalmarv commented 2026-12-02 19:39:37 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Kalmarv on 2026-12-02T19:39:37Z.


Closing: hot-path intercept blocking thread-pool workers up to 2 s with review findings and xcl-fences crashes in smoke.

<!-- greyfinch-sync:ivall/xcl:comment:7356522167 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3389#issuecomment-7356522167). Originally posted by [Kalmarv](https://github.com/Kalmarv) on 2026-12-02T19:39:37Z. --- Closing: hot-path intercept blocking thread-pool workers up to 2 s with review findings and `xcl-fences` crashes in smoke.

Pull request closed

Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
xcl-dev/xcl!3389
No description provided.