Skip to content

D3D12.X: a new texture with lazy levels has its tiles mapped by a call - #3116

Closed
throny wants to merge 1 commit into
xcl-dev:mainfrom
throny:nvd-new-texture-mappings
Closed

throny wants to merge 1 commit into
xcl-dev:mainfrom
throny:nvd-new-texture-mappings

Conversation

@throny

@throny throny commented Nov 28, 2026 •

Copy link
Copy Markdown
Collaborator

With XCL_TEXTURE_LEVEL_PAGES=1, world entry on NVIDIA loses the device (0x887a0006, device hung) in a good share of launches. The cause, a reproduction without a title and the remedy were found by psuedo-tty in #2572 (comment): a list that is already submitted and reads a reserved texture created since, on which no tile-mapping call has run yet, takes a GPU page fault. A title makes a streamed texture and names it in a descriptor in one call while lists that read the descriptor are on its queues, and a texture with lazy levels gets its first mapping only with its first texels. This PR is that remedy for nvidia-dev. Part of #2572 / #505.

What is in it (one commit)

  • crates/xcl/src/hle/d3d12x/vram.rs: when a texture is placed with lazy levels, Pages::null_all maps all its tiles to no memory with one NULL-range UpdateTileMappings and signals the mapping fence, under the PAGES lock; then, outside the lock, wait_new_mappings waits for that fence value, 250 ms at most (a spin for the first half millisecond, yielding after it). The fence value moves on only when the Signal was made. A per-device counter and a test hook for it.
  • crates/xcl/src/hle/d3d12x/title_textures.rs: the existing level-pages GPU test also asserts that the placement made that call and that the mapping fence is done when the placement returns.
  • The branch that maps pages at once is left as it is: the fault is shown for textures with no mapping call, and a wait there would be on the default path of every GPU. psuedo-tty's patch waits there too; that can follow with a measurement.

Tested

  • RTX 4080 16 GB, NVIDIA driver 621.40, i9-12900K, 64 GB, Windows 11 Pro 26300, Rust 1.100.0.
  • World entry on a retail title, 5 minutes each, XCL_UMA_WINDOWS=16 XCL_UMA_DRIVER=mixed:1536:1792 XCL_TEXTURE_LEVEL_PAGES=1 XCL_CS_PSO_WAIT_MS=200 XCL_TWO_PASS_MB=3072, release, on 54225f58 plus three small local patches (the XG: fix CopyFromSubresource 7-argument ABI and guard destination span #684 crash fix, input timing, preparation skip):
    • this head's change: 0 of 10 lost the device; 2.2–2.7 presents/s in the world; about 131,000 new textures waited per run; the 250 ms cap was hit once in the ten runs;
    • without it, same build: 4 of 10 lost the device at 134–149 s, each with an NVIDIA Aftermath dump saying Error_DMA_PageFault, a read by the graphics engine in the last tile of a live BC1 texture created about 1.8 s before the dump; 2.1–2.6 presents/s in the six that survived;
    • an earlier form of the change (wait under the lock, on both branches): 0 of 10 as well, 76 µs per texture on average.
  • cargo test -p xcl --lib a_placed_texture_gets_the_pages_of_a_level_with_its_texels: passes; with the null_all call removed it fails (left: 0, right: 1).
  • cargo build --workspace && cargo test --workspace --no-fail-fast -- --test-threads=4 --skip uma_driver::tests::a_refused_gpu_upload_segment_becomes_custom --skip uma_driver::tests::mixed_window_keeps_its_bytes_and_the_gpu_sees_every_segment --skip uma_driver::tests::failed_restore_stops_before_importing_an_unbacked_window (debug): base 54225f58 1901 passed, 6 failed, 48 ignored; this head 1901 passed, 6 failed, 48 ignored; 27 SKIPPED lines on both. The 6 failures are the same on both: placed_title_textures_share_vram_and_preserve_pixels and three stream_recheck_* tests in title_textures, and d32s8_targets_take_their_own_size_of_video_memory and gpu_retire_queue_holds_heap_until_blocked_queue_passes_mark in vram.
  • Why the three skips: without them the xcl library test binary is terminated on the base and on this head alike (exit code 0x7C10003 after "coherent window could not be restored … after CreateCommandQueue"), twice on each tree here; KDenKC sees the same on an RTX 3090 and an RTX 5090 with driver 621.24 and skips the same three. Reported on [OFFICIAL] Merge queue: which PRs can be merged next, and how to claim a merge check #3041.

Regression run
On a commit of main, on the base commit (nvidia-dev, which this PR is against) and on this PR's head; same title, 120 s. The main block is the run of 2026-11-27 on 83b00818 on this machine (today's attempt to repeat it on that commit spent its whole start-up limit preparing shaders and showed no frame); the other two are from today.

xcl-smoke v1
commit: 83b008188efbf954b846667f48d75e3fa9310a01
gpu: NVIDIA GeForce RTX 4080
title: 21222967
seconds: 120
exit: 0x0
frames shown: 3391 (PresentX 3391)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 20174 MB
xcl-smoke v1
commit: 54225f5884a94cd23b7aab3f703a7c975070aa77
gpu: NVIDIA GeForce RTX 4080
title: 21222967
seconds: 120
exit: 0x0
frames shown: 3470 (PresentX 3470)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 20856 MB

This PR, fc2e9e94:

xcl-smoke v1
commit: fc2e9e94541bf365795d0f674fd7e4cf1700e06e
gpu: NVIDIA GeForce RTX 4080
title: 21222967
seconds: 120
exit: 0x0
frames shown: 3479 (PresentX 3479)
presents per 2 s (last 3): 60 60 61
device removals: 0
crashes: 0
peak commit: 20602 MB

Not tested

  • AMD and Intel, and NVIDIA drivers other than 621.40. The change runs on every vendor when XCL_TEXTURE_LEVEL_PAGES=1 is set; whether AMD needs it or pays for it is not measured (psuedo-tty points at D3D12.X: flush pending tile mappings before submit and fix VRAM unmap/retire races #2981 as possibly the same family on AMD).
  • The default path (XCL_TEXTURE_LEVEL_PAGES unset) is not changed by this PR; 6 of 6 world entries without level pages were clean here before, which is too few to say the non-lazy branch cannot fault.
  • Whether a shorter wait, or none after the NULL mapping call, is enough: psuedo-tty's probe shows the call must have run, not how little waiting suffices.
  • Placed buffers in the sparse windows and other reserved resources made and named at once.
  • A second NVIDIA card: @KDenKC, you offered a 3090 box for exactly this kind of check. The test is world entry with XCL_TEXTURE_LEVEL_PAGES=1, a handful of launches with and without this commit, counting device removals.

AI use

  • Claude Code with Claude Fable 5.2 ported the remedy to nvidia-dev, wrote the test change and this description, and ran the builds, world entries, suite and smoke runs on my hardware. An independent review by Claude Opus 5.5 led to three changes before this was opened (the wait moved out of the lock, yielding in place of a long spin, and the non-lazy branch left alone). The cause and the remedy are psuedo-tty's (Nvidia dev #2572).

🤖 Generated with Claude Code

On NVIDIA a list that is already submitted and reads a reserved texture
created since, on which no tile-mapping call has run yet, takes a GPU page
fault: the device hangs for the Windows time-out and is removed
(0x887a0006). A title makes a streamed texture and points a descriptor at
it in one call while lists that read the descriptor are on its queues, and
with XCL_TEXTURE_LEVEL_PAGES=1 a placed texture gets its first mapping only
with its first texels. World entry lost the device that way in 4 of 10
launches on an RTX 4080 (Aftermath: Error_DMA_PageFault, a read by the
graphics engine in the last tile of a live texture created at the fault).

Cause, a reproduction without a title and the remedy were found by
psuedo-tty (xcl-dev#2572, comment 7234070116). This is that remedy for the lazy
branch of place_on_pages on nvidia-dev: one NULL-range UpdateTileMappings
for the whole texture and a Signal on the mapping queue under the PAGES
lock, then, outside the lock, a wait of at most 250 ms for that fence value
(a short spin, then yielding). The fence value moves on only when the
Signal was made. The branch that maps pages at once is left as it is: the
fault was shown for textures with no mapping call, and a wait there would
be on the default path of every GPU.

The level-pages GPU test now also asserts that the placement made that
call and that the mapping fence is done when the placement returns; it
fails without the call.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@DarkPanda69

Copy link
Copy Markdown

AMD run (listed as untested) on an RX 9070 XT: the extended a_placed_texture_gets_the_pages_of_a_level_with_its_texels passes, with its new asserts that the new texture's tiles were mapped by a call that had run when the placement returned. Nothing else in vram::tests changes.

Tested: at the PR head fc2e9e9 against its merge-base, nvidia-dev 54225f5. Debug, Rust 1.100.0, Windows 11 Pro 26200, Ryzen 7 5800X, RX 9070 XT (RDNA4) driver 32.0.32029.2010.

  • cargo test -p xcl --lib -- hle::d3d12x::vram::tests a_placed_texture_gets_the_pages_of_a_level_with_its_texels --test-threads=1 --nocapture: merge-base 23 passed, 0 failed, 1 ignored; PR the same, no SKIPPED, with no result changes. Same counts with XCL_TEXTURE_LEVEL_PAGES=1 set (the test turns level pages on itself through LEVEL_PAGES_FOR_TEST).
  • Which card: the test makes its device on EnumAdapters1(0), which is the RX 9070 XT on this PC. So it ran on AMD every time, including a run with XCL_ADAPTER=3060, and the RTX 3060 in the same PC isn't covered.

I didn't measure whether AMD needs the mapping call or what it costs, only that the test passes there.

Not tested: the whole suite, a title with XCL_TEXTURE_LEVEL_PAGES=1, the RTX 3060 for this test, Intel.

AI use: Claude Code (Claude Opus 5.5) ran the tests on this machine and wrote this report.

@KDenKC

KDenKC commented Nov 28, 2026

Copy link
Copy Markdown
Contributor

@throny, on it. Two parts, both queued now:

  • In the title, on the RTX 5090 (32 GB, driver 621.24): your environment as posted (XCL_UMA_WINDOWS=16, mixed UMA, XCL_TEXTURE_LEVEL_PAGES=1, XCL_CS_PSO_WAIT_MS=200, XCL_TWO_PASS_MB=3072), 4 launches with fc2e9e94's change and 4 without, alternating, counting device removals and where each launch ends. That also covers a driver other than 621.40.
  • On the RTX 3090 (24 GB, 621.24): the whole suite at fc2e9e94 against nvidia-dev 54225f58. That box has too little RAM for the title, so it's tests only there.

We'll post both here as one Tested / Not tested report.

AI use: an agent swarm: Claude Fable 5.2, Claude Opus 5.5, GPT-6.2-Sol and Gemini 4 Neon.

@fromthemoonx

Copy link
Copy Markdown

A full suite count from a second NVIDIA card (RTX 3060, driver 610.88): the xcl lib binary runs to the end here on both trees, with the same result on the base 54225f5 and on this head. The 4 title_textures failures in your run show up here only when the title-run variables from your Tested section are set.

Tested: fc2e9e9 and its base nvidia-dev 54225f5. RTX 3060 12 GB (driver 610.88), Ryzen 7 5700X, 16 GB RAM, Windows 11 Pro 26300, Rust 1.100.0 MSVC, debug.

54225f5 fc2e9e9
cargo test --workspace --no-fail-fast -- --test-threads=4, no XCL_* set 1909 passed, 1 failed, 48 ignored; 28 SKIPPED lines the same: 1909 passed, 1 failed, 48 ignored; 28 SKIPPED
the 1 failure, watch::tests::a_thread_in_the_driver_is_seen_until_it_returns (watch.rs:623, unwrap() on Err(Any)) passes 3 of 3 alone passes 3 of 3 alone
a_placed_texture_gets_the_pages_of_a_level_with_its_texels alone – 3 of 3
title_textures:: + vram:: with XCL_TEXTURE_LEVEL_PAGES=1 3 failed: placed_title_textures_share_vram_and_preserve_pixels, stream_recheck_partial_upload_without_an_entry_queues_a_whole_upload, stream_recheck_schedule_catches_late_writes_and_resets_milestones the same 3
cargo test -p xcl --lib -- --test-threads=4 with XCL_UMA_WINDOWS=16 XCL_UMA_DRIVER=mixed:1536:1792 XCL_TEXTURE_LEVEL_PAGES=1 XCL_CS_PSO_WAIT_MS=200 XCL_TWO_PASS_MB=3072 – runs to the end: 1772 passed, 6 failed, 28 ignored. The 6 are your 4 (placed_title_textures_share_vram_and_preserve_pixels and three stream_recheck_*) plus a_dispatch_with_a_pipeline_still_building_waits_at_the_submit and put_off_dispatches_wait_at_the_submit_and_run_on_the_software_adapter. No termination.

So if those variables were set in the shell your suite ran in, they would explain the 4 failures. The 0x7C10003 termination did not happen here with or without them.

Not tested: world entry with XCL_TEXTURE_LEVEL_PAGES=1 (no title here), so nothing on the device removals this fixes; a release build; the base's termination on your card.

AI use: Claude Code (Claude Opus 5.5) ran the suites and wrote this report.

@thehollowedone

Copy link
Copy Markdown
Contributor

At head fc2e9e9, the normal mapping path works in the focused RTX test, but placement can still return a lazy reserved texture before its initial NULL mapping has completed.

wait_new_mappings breaks after 250 ms with no completion result. null_all also returns None if Signal fails. In both cases place_on_pages keeps bound = true and returns the successful CreateReservedResource HRESULT with the texture pointer. A consumer can then receive the same not-yet-mapped resource that caused the #2572 fault. The PR's own ten-run report says the timeout was reached once. A removed fence's GetCompletedValue sentinel also needs to be distinguished from a completed value.

Suggested resolution: publish the texture in targets and return success only after confirmed mapping-fence completion. On a timeout or failed signal, clear the output pointer, return a failure HRESULT, and keep the reserved resource alive until the already-queued mapping call retires or the device is removed. Keep bookkeeping and placement registration consistent on that failure path. A later successful signal on the same private queue can serve as the retirement mark after an earlier signal failure. This avoids trading a GPU fault for a resource-lifetime race.

Targeted regression to add

Gate the private mapping queue with a test-controlled fence before lazy placement. Hold it beyond 250 ms, assert that placement cannot return success or a usable texture and that target/page counters are unchanged, then release the gate and verify the retained resource retires. Release the gate even if an assertion fails. Separately inject a failed Signal and a removed-fence completion value. The existing test checks the normal mapping count and completion at return; it cannot reach these failure paths.

Tested: Windows 11 build 26300, RTX 3080 Ti 12 GB / driver 621.35, Ryzen 7 9800X3D, rustc 1.99.1 MSVC. On exact head, cargo test --offline --locked -j 4 -p xcl --lib a_placed_texture_gets_the_pages_of_a_level_with_its_texels -- --test-threads=1 --nocapture: 1 passed, 0 failed, 0 ignored, 0 skipped. This is normal-path coverage. Not tested: forced timeout, failed signal, full workspace suite, title run.

AI use: Codex (GPT-6.2 Sol) traced the placement path and ran the focused test; Codex (GPT-6.2 Astra) independently checked the D3D12 ordering and failure paths.

@thehollowedone

Copy link
Copy Markdown
Contributor

Follow-up to my earlier mapping-order review, tested against unchanged head fc2e9e9.

I reproduced the timeout on the RTX 3080 Ti (621.35) by holding the actual tile-mapping queue behind a fence. On the unchanged head plus the regression test, placement returned S_OK with a resource pointer after 250 ms while its first NULL mapping had not executed: 0 passed, 1 failed, 0 ignored, 0 skipped. A drop guard opens the gate even if an assertion fails. With the candidate, the same test passed 1/1, returning DXGI_ERROR_WAIT_TIMEOUT and a null pointer. It also injects a failure of the first queue Signal, checks that the unpublished resource stays alive, and verifies idle retirement after a later signal on the same queue. The existing lazy-level GPU test passed.

The candidate publishes the target and placement records only after the mapping fence confirms completion. On timeout or Signal failure, it retains the resource until a later proven queue mark or device removal, and drops completed references outside the page-map lock. It treats GetCompletedValue() == UINT64_MAX as device removal, not completion. While an unproven mapping is retained, another lazy placement on that device returns an error without allocating a new reserved resource.

Tested: Windows 11 build 26300, RTX 3080 Ti (621.35), Rust 1.99.1 MSVC. Focused vram, late_release, and existing lazy-texture tests: 28 passed, 0 failed, 1 ignored, 0 GPU skips. The ignored case is the existing mapping-churn benchmark. cargo test --offline --locked -j 4 --workspace --no-fail-fast -- --test-threads=4 on clean fc2e9e9: 1,907 passed, 3 failed, 48 ignored, 26 skip notices; on the candidate: 1,908 passed, 3 failed, 48 ignored, 26 skip notices. All three failure names match: console_mesh_caches_hlsl_compute_pass_in_memory_and_on_disk and two watch::tests timing cases. The candidate's extra pass is the new regression. git diff --check passed.

Still to test: a title A/B, AMD, actual device removal, and a clean-commit smoke pair. The 250 ms deadline is inherited from this PR. Returning an error at that deadline prevents premature use, but a real title could encounter a mapping that would complete later; the current runs do not establish the best recovery policy for that case. This is an adoptable candidate, not a merge-readiness claim.

Candidate and regression diff against fc2e9e9
diff --git a/crates/xcl/src/hle/d3d12x/late_release.rs b/crates/xcl/src/hle/d3d12x/late_release.rs
index 62cc1c76..7fdf9565 100644
--- a/crates/xcl/src/hle/d3d12x/late_release.rs
+++ b/crates/xcl/src/hle/d3d12x/late_release.rs
@@ -164,12 +164,15 @@ pub unsafe fn hold(res: usize, pinned: bool) {
 /// A thread of its own lets the held ones go: the title may release a resource and then wait
 /// for its memory without another submit (an imported heap pins the pages under its resources –
 /// unmapping them stood still while one was held "until the next submit").
-fn start_thread() {
+pub(super) fn start_thread() {
     static THREAD: std::sync::Once = std::sync::Once::new();
     THREAD.call_once(|| {
         let _ = std::thread::Builder::new().name("xcl-late-release".into()).spawn(|| loop {
             std::thread::sleep(TICK);
-            unsafe { drain_known(false) };
+            unsafe {
+                super::vram::retire_failed_mappings();
+                drain_known(false);
+            }
         });
     });
 }
diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs
index 8750a607..91475224 100644
--- a/crates/xcl/src/hle/d3d12x/vram.rs
+++ b/crates/xcl/src/hle/d3d12x/vram.rs
@@ -303,40 +303,61 @@ pub(super) fn level_pages() -> bool {
 #[cfg(test)]
 pub(super) static LEVEL_PAGES_FOR_TEST: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
 
+static FAILED_MAPPINGS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
+
+/// A title can stop submitting as soon as a placement fails. The late-release worker keeps
+/// polling the mapping queues even then. COM Release may reenter XCL, so drop outside PAGES.
+pub(super) unsafe fn retire_failed_mappings() {
+    use std::sync::atomic::Ordering::{Acquire, Release};
+    if !FAILED_MAPPINGS.load(Acquire) { return; }
+    let mut finished = Vec::new();
+    let mut pending = false;
+    {
+        let mut g = PAGES.lock().unwrap();
+        for pages in g.values_mut().flatten() {
+            finished.extend(pages.finished_failed_mappings());
+            pending |= !pages.failed_mappings.is_empty();
+        }
+        FAILED_MAPPINGS.store(pending, Release);
+    }
+}
+
 /// New placed textures whose first mapping call was waited for (`wait_new_mappings`): how many,
 /// the microseconds waited in all, and how many were not done within the wait.
 static NEW_MAPPINGS_WAITED: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
 
-/// The mapping call of a texture just placed (`Pages::null_all`) has run on the GPU before this
-/// returns, so that the title can name the texture in a descriptor: `MAPPED_WAIT` at most (a
-/// device that hangs is not waited for). Called without the `PAGES` lock. The call takes some
-/// tens of microseconds, so this spins for the first half millisecond and yields after that.
-unsafe fn wait_new_mappings(fence: &ID3D12Fence, value: u64) {
+/// Wait at most 250 ms for the first mapping, outside PAGES. A descriptor may name the
+/// texture only on success. Spin for the first half millisecond and yield after that.
+unsafe fn wait_new_mappings(fence: &ID3D12Fence, value: u64) -> Result<(), HRESULT> {
     const MAPPED_WAIT: std::time::Duration = std::time::Duration::from_millis(250);
     const SPIN: std::time::Duration = std::time::Duration::from_micros(500);
     use std::sync::atomic::Ordering::Relaxed;
     let start = std::time::Instant::now();
     // (`fence_completed`: XCL's own fence, without the title's hook)
-    while super::real::fence_completed(fence) < value {
+    let result = loop {
+        let completed = super::real::fence_completed(fence);
+        if completed == u64::MAX { break Err(windows::Win32::Graphics::Dxgi::DXGI_ERROR_DEVICE_REMOVED.0); }
+        if completed >= value { break Ok(()); }
         let waited = start.elapsed();
         if waited >= MAPPED_WAIT {
             if NEW_MAPPINGS_WAITED[2].fetch_add(1, Relaxed) < 8 {
-                crate::xlog_warn!("D3D12.X: a new texture's tile mappings were not done after {} ms: it is named all the same", MAPPED_WAIT.as_millis());
+                crate::xlog_warn!("D3D12.X: a new texture's tile mappings were not done after {} ms", MAPPED_WAIT.as_millis());
             }
-            break;
+            break Err(windows::Win32::Graphics::Dxgi::DXGI_ERROR_WAIT_TIMEOUT.0);
         }
         if waited < SPIN {
             std::hint::spin_loop();
         } else {
             std::thread::yield_now();
         }
-    }
+    };
     let waited = start.elapsed().as_micros() as u64;
     let n = NEW_MAPPINGS_WAITED[0].fetch_add(1, Relaxed) + 1;
     let us = NEW_MAPPINGS_WAITED[1].fetch_add(waited, Relaxed) + waited;
     if n.is_power_of_two() && n >= 1024 {
         crate::xlog_info!("D3D12.X: {n} new textures waited for their tile mappings so far, {} us each on average", us / n);
     }
+    result
 }
 
 /// For a test: how many new textures with lazy levels on `dev` had their tiles mapped to no
@@ -346,7 +367,8 @@ unsafe fn wait_new_mappings(fence: &ID3D12Fence, value: u64) {
 pub(super) fn new_textures_settled_for_test(dev: usize) -> Option<(u64, bool)> {
     let g = PAGES.lock().unwrap();
     let p = g.get(&dev)?.as_ref()?;
-    Some((p.new_settled, unsafe { super::real::fence_completed(&p.fence) } >= p.value))
+    let done = unsafe { super::real::fence_completed(&p.fence) };
+    Some((p.new_settled, done != u64::MAX && done >= p.value))
 }
 
 /// Of the textures with lazy levels there are now: how many, the tiles they stand for, and the
@@ -648,6 +670,12 @@ struct Pages {
     value: u64,
     /// new textures with lazy levels whose tiles a call mapped to no memory (`null_all`)
     new_settled: u64,
+    /// Unpublished resources still referenced by a queued NULL mapping after placement failed.
+    failed_mappings: Vec<ID3D12Resource>,
+    /// A successful signal on the mapping queue after every resource in failed_mappings.
+    failed_mark: Option<u64>,
+    #[cfg(test)]
+    fail_mapping_signals: u32,
     /// per-device timestamp of the last periodic reclaim check
     last_reclaim: std::time::Instant,
     /// pool heaps by `Tile` index (a reclaimed one's slot is empty, as `TilePool::live` has it)
@@ -697,6 +725,10 @@ impl Pages {
             fence,
             value: 0,
             new_settled: 0,
+            failed_mappings: Vec::new(),
+            failed_mark: None,
+            #[cfg(test)]
+            fail_mapping_signals: 0,
             last_reclaim: std::time::Instant::now(),
             pools: PoolHeaps::new(),
             pool: TilePool::new(),
@@ -822,7 +854,7 @@ impl Pages {
 
     /// Every tile of the new texture `res` mapped to no memory by a call, and the mapping fence
     /// signalled after it: the fence and the value `wait_new_mappings` waits for (outside the
-    /// `PAGES` lock), or `None` when the signal failed (a removed device: nothing to wait for).
+    /// `PAGES` lock), or the HRESULT from a failed signal.
     ///
     /// A title makes a streamed texture and points a descriptor at it in one go, while lists that
     /// read that descriptor are already on its queues. A reserved texture made a while ago and
@@ -833,15 +865,38 @@ impl Pages {
     /// only with its first texels, so its placement makes that call: one NULL range for the whole
     /// resource. Waiting for a fence alone or running an empty list does not help; one mapping
     /// call that has run does.
-    unsafe fn null_all(&mut self, res: &ID3D12Resource) -> Option<(ID3D12Fence, u64)> {
+    unsafe fn null_all(&mut self, res: &ID3D12Resource) -> Result<(ID3D12Fence, u64), HRESULT> {
         let flag = D3D12_TILE_RANGE_FLAG_NULL;
         self.queue.UpdateTileMappings(res, 1, None, None, None, 1, Some(&flag), None, None, D3D12_TILE_MAPPING_FLAG_NONE);
-        // (the value moves on only with a signal that was made: nobody waits for one that was not)
+        let value = self.signal_new_mapping()?;
+        Ok((self.fence.clone(), value))
+    }
+
+    unsafe fn signal_new_mapping(&mut self) -> Result<u64, HRESULT> {
+        #[cfg(test)]
+        if self.fail_mapping_signals > 0 {
+            self.fail_mapping_signals -= 1;
+            return Err(windows::Win32::Foundation::E_FAIL.0);
+        }
         let value = self.value + 1;
-        self.queue.Signal(&self.fence, value).ok()?;
+        self.queue.Signal(&self.fence, value).map_err(|e| e.code().0)?;
         self.value = value;
-        self.new_settled += 1;
-        Some((self.fence.clone(), value))
+        Ok(value)
+    }
+
+    /// The first signal may have failed after UpdateTileMappings. A fresh queue signal covers
+    /// all failed placements recorded so far. Drop completed COM references outside PAGES.
+    unsafe fn finished_failed_mappings(&mut self) -> Vec<ID3D12Resource> {
+        if self.failed_mappings.is_empty() { return Vec::new(); }
+        let done = super::real::fence_completed(&self.fence);
+        if done == u64::MAX || self.failed_mark.is_some_and(|v| done >= v) {
+            self.failed_mark = None;
+            return std::mem::take(&mut self.failed_mappings);
+        }
+        if self.failed_mark.is_none() {
+            self.failed_mark = self.signal_new_mapping().ok();
+        }
+        Vec::new()
     }
 
     fn release_tiles(&mut self, used: Vec<usize>, used_extra: Vec<(usize, usize)>, now: std::time::Instant, immediate_cool: bool) {
@@ -1073,9 +1128,14 @@ unsafe fn place_on_pages(
         }
     };
     let dev_key = dev.as_raw() as usize;
+    *ppv = std::ptr::null_mut();
+    if lazy { retire_failed_mappings(); }
     let is_reservable = {
         let mut g = PAGES.lock().unwrap();
         let pages = g.entry(dev_key).or_insert_with(|| Pages::new(dev)).as_mut()?;
+        if lazy && !pages.failed_mappings.is_empty() {
+            return Some(windows::Win32::Graphics::Dxgi::DXGI_ERROR_WAS_STILL_DRAWING.0);
+        }
         *pages.reservable_cache.entry((tiled.Format.0, tiled.SampleDesc.Count)).or_insert_with(|| reservable(dev, &tiled))
     };
     if !is_reservable {
@@ -1084,13 +1144,14 @@ unsafe fn place_on_pages(
     }
     // CreateReservedResource and GetResourceTiling do not touch `PAGES`; keep them outside the
     // lock so concurrent streaming threads, `before_execute`, and `page_bytes` do not serialize.
-    let hr = super::real::dev_create_reserved_resource(this, &tiled as *const _ as usize, state as usize, clear as usize, riid, ppv);
-    if hr < 0 || (*ppv).is_null() {
+    let mut raw = std::ptr::null_mut();
+    let hr = super::real::dev_create_reserved_resource(this, &tiled as *const _ as usize, state as usize, clear as usize, riid, &mut raw);
+    if hr < 0 || raw.is_null() {
         log(&format!("{hr:#x}"));
         return None;
     }
-    let raw = *ppv;
-    let res = ID3D12Resource::from_raw_borrowed(&raw)?;
+    let owned = ID3D12Resource::from_raw(raw);
+    let res = &owned;
     let mut total = 0u32;
     let levels = if lazy {
         let (levels, n) = level_tiling(dev, res, desc.MipLevels as u32);
@@ -1100,35 +1161,36 @@ unsafe fn place_on_pages(
         dev.GetResourceTiling(res, Some(&mut total), None, None, None, 0, std::ptr::null_mut());
         None
     };
-    let (bound, new_mappings) = {
-        let mut g = PAGES.lock().unwrap();
-        if let Some(Some(pages)) = g.get_mut(&dev_key) {
-            if levels.is_some() {
-                // no pages yet: a level gets its pages with its first texels (`map_levels`). Its
-                // tiles are mapped to no memory by a call all the same (`null_all`).
-                LEVEL_STATS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
-                LEVEL_STATS[1].fetch_add(total as u64, std::sync::atomic::Ordering::Relaxed);
-                pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used: Vec::new(), used_extra: Vec::new(), levels });
-                (true, pages.null_all(res))
-            } else if let Some((used, used_extra)) = pages.bind(dev, res, va, console_bytes, total) {
-                pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used, used_extra, levels: None });
-                (true, None)
-            } else {
-                (false, None)
-            }
-        } else {
-            (false, None)
-        }
+    let mut g = PAGES.lock().unwrap();
+    let pages = g.get_mut(&dev_key)?.as_mut()?;
+    let (used, used_extra) = if levels.is_some() {
+        if !pages.failed_mappings.is_empty() {
+            // No further lazy mappings until the previous one is safely retired.
+            return Some(windows::Win32::Graphics::Dxgi::DXGI_ERROR_WAS_STILL_DRAWING.0);
+        }
+        let signal = pages.null_all(res);
+        drop(g);
+        let ready = signal.and_then(|(f, v)| wait_new_mappings(&f, v));
+        g = PAGES.lock().unwrap();
+        let pages = g.get_mut(&dev_key).unwrap().as_mut().unwrap();
+        if let Err(hr) = ready {
+            pages.failed_mappings.push(owned);
+            pages.failed_mark = None;
+            FAILED_MAPPINGS.store(true, std::sync::atomic::Ordering::Release);
+            drop(g);
+            super::late_release::start_thread();
+            return Some(dev.GetDeviceRemovedReason().err().map_or(hr, |e| e.code().0));
+        }
+        pages.new_settled += 1;
+        LEVEL_STATS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+        LEVEL_STATS[1].fetch_add(total as u64, std::sync::atomic::Ordering::Relaxed);
+        (Vec::new(), Vec::new())
+    } else {
+        pages.bind(dev, res, va, console_bytes, total)?
     };
-    // (outside the lock: submits and releases of other threads take `PAGES` too)
-    if let Some((fence, value)) = new_mappings {
-        wait_new_mappings(&fence, value);
-    }
-    if !bound {
-        drop(windows::core::IUnknown::from_raw(raw));
-        *ppv = std::ptr::null_mut();
-        return None;
-    }
+    let pages = g.get_mut(&dev_key).unwrap().as_mut().unwrap();
+    pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used, used_extra, levels });
+    drop(g);
     PLACED_TEXTURES.lock().unwrap().get_or_insert_with(HashSet::new).insert(raw as usize);
     let (first, own) = owned_pages(va, console_bytes, total as usize).unwrap_or((va, 0));
     let kind = if gpu_owned(desc.Flags.0 as u32) { super::placements::Kind::Target } else { super::placements::Kind::Sampled };
@@ -1136,6 +1198,7 @@ unsafe fn place_on_pages(
     for r in super::placements::placed(raw as usize, va, (first, first + own * PAGE), super::placements::Backing::Pages(dev_key), kind, desc) {
         super::late_release::hold_unmap(r);
     }
+    *ppv = owned.into_raw();
     Some(hr)
 }
 
@@ -2352,6 +2415,76 @@ mod tests {
         assert!(late <= early, "arenas grow over time: {early} then {late} bytes");
     }
 
+    #[test]
+    fn lazy_placement_waits_for_its_first_mapping_or_returns_an_error() {
+        use crate::gpu::recomp::runner::skip_test;
+        use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0;
+        use windows::Win32::Graphics::Dxgi::Common::*;
+        use windows::Win32::Graphics::Dxgi::*;
+
+        let _guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
+        unsafe {
+            let Ok(dev) = crate::gpu::agility::create_device(None, D3D_FEATURE_LEVEL_11_0) else { return skip_test("no GPU") };
+            super::super::real::adopt(dev.as_raw(), super::super::real::Kind::Device);
+            let key = dev.as_raw() as usize;
+            let desc = D3D12_RESOURCE_DESC {
+                Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: 1024, Height: 1024,
+                DepthOrArraySize: 1, MipLevels: 11, Format: DXGI_FORMAT_R8G8B8A8_UNORM,
+                SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, ..Default::default()
+            };
+            let riid = &ID3D12Resource::IID as *const windows::core::GUID as *const windows_sys::core::GUID;
+            let place = |va, out: &mut *mut c_void| place_on_pages(&dev, dev.as_raw(), va, &desc,
+                D3D12_RESOURCE_STATE_COMMON.0 as u32, std::ptr::null(), Some(6 << 20), true, true, riid, out);
+            let mut first = std::ptr::null_mut();
+            let first_hr = place(0x40_0000_0000, &mut first);
+            if !first_hr.is_some_and(|hr| hr >= 0) { return skip_test("no reserved placement") }
+            let first = ID3D12Resource::from_raw(first);
+            if !has_lazy_levels(first.as_raw() as usize) { return skip_test("no lazy levels") }
+            let (queue, targets, settled) = {
+                let pages = PAGES.lock().unwrap();
+                let p = pages[&key].as_ref().unwrap();
+                (p.queue.clone(), p.targets.len(), p.new_settled)
+            };
+            for signal_failure in [false, true] {
+                let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap();
+                queue.Wait(&gate, 1).unwrap();
+                struct OpenOnDrop(ID3D12Fence);
+                impl Drop for OpenOnDrop {
+                    fn drop(&mut self) { unsafe { let _ = self.0.Signal(1); } }
+                }
+                let guard = OpenOnDrop(gate);
+                PAGES.lock().unwrap().get_mut(&key).unwrap().as_mut().unwrap().fail_mapping_signals = if signal_failure { 2 } else { 0 };
+                let mut raw = std::ptr::null_mut();
+                let hr = place(0x40_1000_0000, &mut raw);
+                let returned = (!raw.is_null()).then(|| ID3D12Resource::from_raw(raw));
+                let expected = if signal_failure { windows::Win32::Foundation::E_FAIL } else { DXGI_ERROR_WAIT_TIMEOUT };
+                assert_eq!(hr, Some(expected.0));
+                assert!(returned.is_none(), "an unsettled resource reached the caller");
+                let mut retry = std::ptr::null_mut();
+                assert_eq!(place(0x40_2000_0000, &mut retry), Some(DXGI_ERROR_WAS_STILL_DRAWING.0));
+                assert!(retry.is_null());
+                {
+                    let pages = PAGES.lock().unwrap();
+                    let p = pages[&key].as_ref().unwrap();
+                    assert_eq!((p.targets.len(), p.new_settled), (targets, settled));
+                    assert_eq!(p.failed_mappings.len(), 1, "queue is blocked and owns the unpublished resource");
+                    assert!(!is_placed_texture(p.failed_mappings[0].as_raw() as usize));
+                }
+                drop(guard);
+                let start = std::time::Instant::now();
+                loop {
+                    if PAGES.lock().unwrap()[&key].as_ref().unwrap().failed_mappings.is_empty() { break; }
+                    assert!(start.elapsed() < std::time::Duration::from_secs(5), "completed mapping still held");
+                    std::thread::yield_now();
+                }
+            }
+            let mut recovered = std::ptr::null_mut();
+            assert_eq!(place(0x40_1000_0000, &mut recovered), Some(0));
+            let recovered = ID3D12Resource::from_raw(recovered);
+            assert!(has_lazy_levels(recovered.as_raw() as usize));
+        }
+    }
+
     /// On the GPU: D32S8 targets 256 MiB apart take their own size of video memory, not an arena
     /// of 256 MiB each; depth and stencil survive a clear, CopyResource and a read of both planes;
     /// arenas no target uses go. Needs a hardware adapter (skips on WARP).

AI use: Codex (GPT-6.2 Astra) wrote the candidate and regression and ran the focused GPU tests; Codex (GPT-6.2 Sol) reviewed the path and ran the paired full workspace suites.

@KDenKC

KDenKC commented Nov 28, 2026

Copy link
Copy Markdown
Contributor

@throny the whole suite of your head on an RTX 3090, against its base on the same machine: no failure the base doesn't have.

Tested: fc2e9e94 and its base nvidia-dev 54225f58.

  • RTX 3090 24 GB, NVIDIA 621.24, i7-10700T x8 (a VM with the GPU passed through), Windows 11 26H2 (26300.9974), Rust 1.99.1 (stable-x86_64-pc-windows-msvc), debug, no XCL_* set.
  • cargo test --workspace --no-fail-fast -- --test-threads=4 --skip uma_driver::tests::a_refused_gpu_upload_segment_becomes_custom --skip uma_driver::tests::mixed_window_keeps_its_bytes_and_the_gpu_sees_every_segment --skip uma_driver::tests::failed_restore_stops_before_importing_an_unbacked_window (those three end the lib test binary on 621.24, at the base too)
base 54225f58 head fc2e9e94
all binaries 1,900 passed, 7 failed, 48 ignored 1,900 passed, 7 failed, 48 ignored
title_textures::tests::a_placed_texture_gets_the_pages_of_a_level_with_its_texels (with your new asserts) ok ok
  • The 7 failures are the same tests on both, and they come from this VM, not this PR:
    • placed_title_textures_share_vram_and_preserve_pixels fails on 0x8007000E in the full run and passes alone;
    • three stream_recheck_* fail only on the lock it leaves poisoned;
    • two vram::tests fail on 0x8007000E;
    • e2e test_title_runs_and_game_folder_is_untouched.
  • SKIPPED: 30, the same on both (22 no wave64).

Still to come (we'll edit this comment): the in-title part on the RTX 5090: your environment, 4 launches each for the base, this PR and #3124, counting device removals.

Not tested: a title run with XCL_TEXTURE_LEVEL_PAGES=1 (world entry, device removals); a release build; AMD / Intel.

AI use: an agent swarm: Claude Fable 5.2, Claude Opus 5.5, GPT-6.2-Sol and Gemini 4 Neon.

@Aniseto

Aniseto commented Nov 28, 2026

Copy link
Copy Markdown

Ran the lazy-level tile-mapping GPU test at fc2e9e94 on an NVIDIA Blackwell desktop part:

Environment: Windows 11 Pro build 26200 x64, NVIDIA GeForce RTX 5070 Ti (Blackwell, wave32 only, 16 GB) driver 32.0.16.2124, Intel Core i5-12400F, 64 GB RAM, rustc 1.100.0 (0ef1bc386 2026-11-09), MSVC 14.44.35207, DXC 1.9.2609.5, debug build.

XCL_ADAPTER=NVIDIA cargo test -p xcl --lib a_placed_texture_gets_the_pages_of_a_level_with_its_texels -- --test-threads=1
1 passed; 0 failed; 0 ignored; 0 measured; 1805 filtered out      (exit 0)

The GPU-backed test passes here: a placed texture with lazy levels has its tiles mapped by a call and the mapping fence is done when placement returns. This is a synthetic device test, not a retail-title launch; the PR's 0-of-10 vs 4-of-10 device-loss figures came from a title on an RTX 4080 and are not reproduced here. The thread has runs on RTX 3060, RTX 3090 and AMD; this adds a Blackwell datapoint.

Not tested: a retail title, the device-loss A/B, a paired smoke run, the full workspace suite, AMD and Intel GPUs, native wave64 hosts, Wine, release profile, game data.

AI-assisted (OpenCode), model: DeepSeek V4.1 Flash Free - checked out the PR's head commit in a detached worktree, built it, ran the tests, wrote this report; the worktree was not modified; no game data was used.

@andrewDoing

Copy link
Copy Markdown
Contributor

On RTX 5070 12 GB, driver 616.92, all 384 normal lazy placements had a completed mapping fence when checked immediately after placement returned. The production wait counter averaged 199, 205, and 212 µs per placement across three fresh processes. None reached the 250 ms cap.

I used head fc2e9e94541bf365795d0f674fd7e4cf1700e06e with a test-only extension to a_placed_texture_gets_the_pages_of_a_level_with_its_texels. Each process created 128 distinct 1024×1024 RGBA8 textures with 11 mip levels through CreatePlacedResourceX, serially on one device. It kept all 128 resources alive. After each return, the test checked that the NULL-mapping count advanced by one and that the mapping fence had reached its last signalled value. The device's physical texture-page allocation counter stayed unchanged before texel upload. The existing fixture then passed its mip-content GPU readback checks in each process. The adapter name and NVIDIA vendor ID were checked on the DXGI adapter used to create the device. Three focused tests passed, zero skipped.

The 128 waits totalled 25,456 / 26,252 / 27,197 µs in the PR's existing wait counter. These are debug-build host wait times on an otherwise ungated queue. They do not establish a safe shorter timeout, measure total placement time, or estimate world-entry device-loss frequency. No retail title or fault injection was used.

AI use: OpenAI Codex (GPT-6) inspected the two related PRs, added the test-only instrumentation, ran the fixture and prepared this report.

@Prime1997
Prime1997 changed the base branch from nvidia-dev to main November 28, 2026 20:13
Prime1997 added a commit to Prime1997/xcl that referenced this pull request Nov 28, 2026
Adapt throny PR xcl-dev#3116 explicit NULL mapping before publication. Signal errors, device removal and a five-second wait deadline fail placement while uncertain resources remain held. CPU and native fixture changes are present but unrun; this commit has not been built. Assisted-by: Codex (GPT-6)
@throny

throny commented Nov 28, 2026

Copy link
Copy Markdown
Collaborator Author

Closing this in favour of #3124. nvidia-dev was merged into main today (#3203), this PR now targets main and conflicts with it, and #3124 carries the same NULL mapping with a stricter failure path (it fails the placement instead of handing out a texture whose mapping did not complete), merges cleanly, and did equally well in the title on this card: 10 of 10 world entries without a device removal, the same frame rate (numbers). Two fixes for one hang help nobody; thanks @Prime1997 for taking it further and @KDenKC for the runs on the 3090.

AI use: Claude Code (Claude Fable 5.2) wrote this.

@throny throny closed this Nov 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants