Skip to content

D3D12.X: sparse tiles outside the GPU heaps can live in system memory - #2987

Open
treybertram06 wants to merge 1 commit into
xcl-dev:nvidia-devfrom
treybertram06:nv-sparse-sysmem
Open

treybertram06 wants to merge 1 commit into
xcl-dev:nvidia-devfrom
treybertram06:nv-sparse-sysmem

Conversation

@treybertram06

@treybertram06 treybertram06 commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Target: nvidia-dev. Part of #2688. Related: gefydev's planned budget-triggered L0 sparse pools (#2688), and #1702 (texture pages in system memory).

With XCL_COHERENT_HEAPS=sparse the title's GPU heaps live in the sparse windows instead of the coherent window. These heaps are committed memory with a PAGE_GRAPHICS_* protection, about 4.5 GB in a retail title. Shaders read and write them every frame. In the coherent window (system RAM, read over PCIe), one retail compute program took 1,364 ms per frame on an RTX 3080; with the heaps in video memory it falls under 33 ms (XCL_GPU_TIMES). An RTX 4080 report on #2688 found the same factor. But with the heaps in video memory, the sparse windows hold about 7.5 GB of tiles. On a 10 GB card the device runs out of budget: 19 GB in use against 8.9 GB, removed at 659 s.

XCL_SPARSE_SYSMEM=1 (off by default) keeps the GPU heaps' tiles in video memory and puts every other sparse-window tile in system memory:

  • kernelx registers a GPU heap's range as hot (sparse::alloc_as) before its commit maps its tiles;
  • other tiles take pool tiles in system-memory pool heaps (custom heaps, MEMORY_POOL_L0, write-back), which the GPU reads over PCIe.

gefydev's plan moves new pools past the budget. This one decides by what a range holds, so the heaps the shaders depend on are never the ones moved.

What is in it

  • D3D12.X: sparse tiles outside the GPU heaps can live in system memory (hle/d3d12x/sparse.rs, hle/kernelx.rs):
    • note_hot / is_hot / alloc_as mark the hot ranges;
    • system-memory pools (SysPools, pool index tagged with SYS) with their own free and cooling lists;
    • pool_heap resolves either kind;
    • a lazy tile's first write takes its tile by the same choice (take_tile_for);
    • a system-memory tile parked at an address that is a GPU heap at its next commit gives way to a video-memory tile, the old one quarantined behind the fences;
    • a released reservation forgets its hot range (forget_hot, from sparse::free and kernelx's MEM_RELEASE).
  • Tests: the_title_gpu_heaps_are_hot_and_nothing_around_them, a_lazy_tile_outside_the_gpu_heaps_gets_system_memory, a_parked_system_memory_tile_gives_way_to_a_gpu_heap. The last two fail without their fixes. Under cfg(test) the switch follows a thread-local a test sets, not the environment.

Tested

  • RTX 3080 10 GB (driver 621.40), Ryzen 9 5900X, 64 GB RAM, Windows 11 26300, NVIDIA profile with the 2 GiB shader heap for xcl.exe (xcl run: xcl nvprofile puts xcl.exe in an NVIDIA profile with a bigger shader heap (#2403) #2590). Debug tests, release title runs.
  • cargo test --workspace --no-fail-fast -- --test-threads=4, with XCL_DXC_DIR set to DXC 1.9, at this PR's head f8e75bca: 1824 passed, 11 failed, 48 ignored.
  • cargo test -p xcl --lib -- hle::d3d12x::sparse --test-threads=4: 69 passed, 0 failed, 1 ignored, no skips.
  • Retail title, release build, 610 s, at 6c5904f9 (before the review fixes), XCL_COHERENT_HEAPS=sparse XCL_SPARSE_SYSMEM=1 XCL_TEXTURE_LEVEL_PAGES=1 XCL_PREPARE_WORKERS=6, scripted presses. Over the 400 s after the menus: 0.72 presents/s, video memory 15.1 GB local / 5.0 GB non-local (budget 9.2 GB), commit 41.5 GB, no device removal.
    • The same title with level pages only (heaps in the coherent window): 0.28–0.42 presents/s.
    • Heaps in video memory without this switch: 0.98 presents/s, but 19 GB of video memory and a device removal at 659 s.
    • Rates come from single runs over different stretches of the title (cutscene loading varies), so treat them as rough.
  • XCL_GPU_TIMES with the heaps in the coherent window: the top program cs 10eaefe801508781 took 1,364 ms per frame. With them in video memory, the top program is under 70 ms.

Regression run
Base, a commit of main: b49be183, the last main commit before #2555's launch preparation gate, which takes hours with this title on this card. The switch is off in both runs.

xcl-smoke v1
commit: b49be1836844fe0b0cdb3211dce3cb7fb4e21ac7
gpu: NVIDIA GeForce RTX 3080
title: 4ba6c38e
seconds: 60
exit: 0x0
frames shown: 1415 (PresentX 1415)
presents per 2 s (last 3): 61 60 60
device removals: 0
crashes: 0
peak commit: 15557 MB

This PR's head:

xcl-smoke v1
commit: f8e75bca1ea903b1cf0e9d4f9387b73f359e5051
gpu: NVIDIA GeForce RTX 3080
title: 4ba6c38e
seconds: 60
exit: 0x0
frames shown: 1607 (PresentX 1607)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 18867 MB

Not tested

AI use

  • Claude Code with Claude Opus 5.5. It measured the placement, wrote the code, the tests (and the fixes for review findings) and this description, and ran the tests and title runs. The author reviewed the diff.

@thehollowedone

Copy link
Copy Markdown
Contributor

Independent RTX 3080 Ti check of 6c5904f9: with XCL_SPARSE_SYSMEM=1, the eager path places a cold control tile in the system-memory pool, but a lazy cold tile receives a default video-memory pool tile at its first CPU write. The lazy materialization path calls take_tile() directly, bypassing the cold/hot choice in ensure_mapped. This undercuts the VRAM saving when XCL_SPARSE_LAZY=1 is used.

I extended the existing synthetic lazy first-write test to first verify L0 support with an eager control tile and then assert the lazy tile's pool class. On Windows 11 build 26300, RTX 3080 Ti (621.35), Ryzen 7 9800X3D, Rust 1.99.1 MSVC, I set XCL_SPARSE_SYSMEM=1 and XCL_REQUIRE_GPU=1 and ran cargo test --offline --locked -j 4 -p xcl --lib a_lazy_tile_gets_memory_at_its_first_bytes_and_keeps_them -- --nocapture --test-threads=1. It failed on the PR head (0 passed, 1 failed, 0 ignored, no GPU skip; lazy pool class was video). Sharing the selection in take_tile_for(t) made the same test pass (1 passed, 0 failed, 0 ignored, no GPU skip), including its existing 64-KiB GPU readback. This is a local candidate, not a committed change or a full title validation.

Candidate fix and focused regression diff
diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs
index 979b4d04..4f161733 100644
--- a/crates/xcl/src/hle/d3d12x/sparse.rs
+++ b/crates/xcl/src/hle/d3d12x/sparse.rs
@@ -1301,6 +1301,11 @@ impl State {
         Some(((h, 0), false))
     }
 
+    /// Choose backing by the title reservation that owns this tile.
+    unsafe fn take_tile_for(&mut self, t: usize) -> Option<((u32, u32), bool)> {
+        if sysmem_tiles() && !is_hot(t) { self.take_sys_tile() } else { self.take_tile() }
+    }
+
     /// The heap of pool index `h` (video memory, or a system-memory pool with `SYS`).
     fn pool_heap(&self, h: u32) -> ID3D12Heap {
         if h & SYS != 0 {
@@ -1607,7 +1612,7 @@ impl State {
             if self.mapped.get(&t).is_some_and(|e| e.pool == LAZY) {
                 let at_hand = !self.free.is_empty() || cooled(&self.cooling, std::time::Instant::now()) || !self.retired.is_empty();
                 let wait = left > 0 || (!force && self.short_of_memory() && !at_hand);
-                match if wait { None } else { self.take_tile() } {
+                match if wait { None } else { self.take_tile_for(t) } {
                     Some((tile, used)) => {
                         if let Some(e) = self.mapped.get_mut(&t) {
                             e.pool = tile;
@@ -1665,7 +1670,7 @@ impl State {
                     self.to_zero.insert((t, TILE));
                     unparked = true;
                 } else {
-                    let got = if sysmem_tiles() && !is_hot(t) { self.take_sys_tile() } else { self.take_tile() };
+                    let got = self.take_tile_for(t);
                     let Some((tile, reused)) = got else { break };
                     self.mapped.insert(t, TileEntry::with_holes(tile, initial_holes(t)));
                     early_add(&mut self.runs, t, t + TILE);
@@ -6083,7 +6088,10 @@ mod tests {
     fn a_lazy_tile_gets_memory_at_its_first_bytes_and_keeps_them() {
         let lazy = Lazy::on(true);
         unsafe {
-            let Some((base, mut s, queue)) = lazy_state(2) else { return crate::gpu::recomp::runner::skip_test("no GPU with tiled resources tier 2") };
+            let Some((base, mut s, queue)) = lazy_state(3) else { return crate::gpu::recomp::runner::skip_test("no GPU with tiled resources tier 2") };
+            let cold_control = base + 2 * TILE;
+            s.ensure_mapped(cold_control, TILE, |_| 0);
+            assert_ne!(s.mapped[&cold_control].pool.0 & SYS, 0, "eager cold tile uses system memory on this adapter");
             s.commit_range(base, 2 * TILE);
             assert_eq!(s.mapped[&base].pool, LAZY, "committed: listed with no video memory");
             assert_eq!(s.mapped[&(base + TILE)].pool, LAZY);
@@ -6092,6 +6100,7 @@ mod tests {
             let dirty = write_tile(base, 7);
             s.before_execute_on(&queue, &dirty, PAGE);
             assert_ne!(s.mapped[&base].pool, LAZY, "its first bytes gave it a pool tile");
+            assert_ne!(s.mapped[&base].pool.0 & SYS, 0, "lazy cold tile also uses system memory");
             assert_eq!(s.mapped[&(base + TILE)].pool, LAZY, "the tile never written has none");
             let cpu = std::slice::from_raw_parts(base as *const u8, TILE).to_vec();
             assert!(window_bytes(&mut s, base, TILE) == cpu, "the bytes reached the GPU");

The broader policy still needs the lazy path's at_hand/low-memory decision to consider ready system-pool tiles, plus reservation-lifetime handling when an address changes between hot and cold. Those cases were not exercised by this focused test. No game files were used. AI use: Codex (GPT-6.2 Sol) ran the red/green GPU test and wrote the local candidate; Codex (GPT-6.2 Astra) reviewed the sparse allocation paths.

@3L1A5-1

3L1A5-1 commented Nov 27, 2026

Copy link
Copy Markdown

8 GB VRAM / 16 GB RAM data point with XCL_SPARSE_SYSMEM=1 alone (no hot heaps, which an 8 GB card can't hold): local video memory is cut from ~4.1 GB to ~1.1 GB over budget, and it stays under budget until title ~180 s. The cost is system memory, roughly one-for-one, and on 16 GB the run still ends on host memory. One run with the switch. The comparison is against single runs of the same stack without it, and the local over-budget peak was stable at +3.7 to +4.5 GB across 8 runs of this base with and without the other PRs.

Tested

Results

without (same stack) XCL_SPARSE_SYSMEM=1
Local VRAM vs ~7.24 GB budget, title 60 / 120 / 180 / 240 s −1.1 / +0.3 / +2.4 / +2.8 GB −3.4 / −2.7 / −0.0 / +0.4 GB
Local VRAM peak 11.3 GB (+4.1 GB) 8.3 GB (+1.1 GB)
Video-memory sparse pools, peak 3.97 GB 1.22 GB
System-memory pool heaps – 2,048 MB by title 26 s (64 MB heaps)
Non-local video memory, peak 2.7–3.4 GB 6.75 GB
Process commit peak / free RAM min 29.3 GB / 42 MB 29.5 GB / 131 MB
fps, title 100 s → end 2.1 2.4 (0.4–0.8 in the world phase in both)
End Close E_OUTOFMEMORY at title 439.9 s Close E_OUTOFMEMORY at title 399.3 s, no device-removed line
  • 0 no system-memory pool heap warnings. The end time difference is within the 340–440 s spread I see between single runs of this stack, so I'm not reading a gain or loss from it.
  • So on this class of machine the switch moves the overcommit from VRAM into system memory. That helps a lot on the VRAM side, but with 16 GB RAM the host side becomes the limit at about the same point. GPU reads over PCIe didn't cost visible fps here, but the world phase was already below 1 fps.

Not tested: repeats, XCL_COHERENT_HEAPS=sparse (no room in 8 GB), 32 GB RAM, AMD.

AI use: build, run and log analysis by Claude Code agents (Claude Sonnet 5.5), report written and checked against the run logs by Claude Code (Claude Opus 5.5).

@SzczepanGrela

Copy link
Copy Markdown

RX 9070 / Wine: an eager sparse-window system-memory readback works in a focused native GPU fixture at 6c5904f9426ffdfd4772399c92bfa84ddf29f6e2. Both copies and a wave64 compute shader preserve the expected contents through the mixed pool mapping.

Tested

RX 9070 16 GB, RADV GFX1201 / Mesa 26.3.1, Ryzen 7 7700, CachyOS 7.3.0-5, GE-Proton11-12 / Wine 11.0 Staging, vkd3d-proton 8293130ebe370b1+ with local asserts-disabled build, DXC/DXIL 1.9.2602.17, Rust 1.97.1 Windows-GNU release. Explicit adapter, network off, private enabled caches. Owned tests were appended to source copies; production functions and original assertions were unchanged.

Compared the exact head with its actual parent a5e2d851a503fc0e04609f773ea53f2d2c4e3269; the target nvidia-dev had advanced to e0821b12.

cargo test --offline --locked --release --target x86_64-pc-windows-gnu -p xcl --lib --no-run, then the resulting PE under Wine:

  • Head's original hle::d3d12x::sparse::tests::the_title_gpu_heaps_are_hot_and_nothing_around_them --exact --nocapture --test-threads=1 and =4: 1 passed, 0 failed each.
  • Owned hle::d3d12x::sparse::workflow_sysmem_native::workflow_cold_system_tiles_and_hot_video_tiles_read_back --exact --nocapture --test-threads=1: three fresh full processes per source/switch combination, plus one pilot each. XCL_SPARSE_SYSMEM=0 and =1 were tested in separate processes. Each harness passed; zero ignored or skipped tests.

The fixture maps eagerly through ensure_mapped, with XCL_SPARSE_LAZY unset. It uses a 16-tile reserved buffer, with 6 tiles marked hot and 10 cold. It calls production new_state, ensure_mapped, flush_pending and upload_dirty, registering hot ranges directly through note_hot on head.

Source / switch Hot tiles Cold tiles
Parent, either switch DEFAULT pool DEFAULT pool
Head, switch off DEFAULT pool DEFAULT pool
Head, switch on DEFAULT pool CUSTOM, WRITE_BACK, MEMORY_POOL_L0

These are actual pool tags and native ID3D12Heap::GetDesc results. All cold tiles in the enabled head used the system-pool path; no fallback to DEFAULT was counted as coverage.

Every window word was checked after CPU upload, after partial native GPU writes with untouched regions retained, and after an owned wave64 shader loaded, transformed and stored every word through the same window. A separate width buffer verified lane count 64 and its 15 untouched guards.

Independent Python verification checked all 10,223,872 readback words, including 39 MiB of window payload, across 64 native readbacks and 16 wave64 dispatches. Data, guards and shader containers match across sources, switches and fresh repeats. No device removal occurred.

Not tested

Lazy first-write materialization, including the bypass already reported here, the full kernelx VirtualAlloc / alloc_as caller, hot-range free/reuse lifecycle, title workload, smoke, full suite, native Windows, physical residency, budget reduction or performance. Heap properties and GPU data correctness do not establish those measurements. Main 83b00818 was not integrated or built: the three-way file application conflicts in sparse.rs and kernelx.rs; no manual repairs were made.

AI use

OpenAI Codex (GPT-6; exact serving variant not exposed) reviewed the public change, wrote and ran the fixture and independent verifier, and drafted this report. Publication authorized by the account owner.

@thehollowedone

Copy link
Copy Markdown
Contributor

New, separate finding on #2987 head 6c5904f9, following my earlier lazy-placement report: a cold tile can be decommitted into parked, then immediately recommitted at the same address after that address becomes a title GPU heap. ensure_mapped takes the parked tuple before checking is_hot, so the new hot heap inherits system-memory backing. This is distinct from the lazy first-write path.

I added a synthetic one-tile GPU regression that commits cold, flushes the mapping, verifies the SYS pool bit, decommits, calls note_hot for the same address, and recommits. On Windows 11 build 26300, RTX 3080 Ti (621.35), Ryzen 7 9800X3D, Rust 1.99.1 MSVC, with XCL_SPARSE_SYSMEM=1 and XCL_REQUIRE_GPU=1, cargo test --offline --locked -j 4 -p xcl --lib a_parked_cold_tile_does_not_back_a_new_hot_heap -- --nocapture --test-threads=1 failed on the PR head (0 passed, 1 failed, 0 ignored, no GPU skip; pool index retained the SYS bit). The candidate below passed the same test (1 passed, 0 failed, 0 ignored, no GPU skip).

The candidate acquires a video-memory replacement before touching the parked mapping, then unmaps and quarantines the old tile behind the existing queue fences. It leaves pinned tiles on their existing backing so placed-buffer aliases remain intact. It is a focused local candidate, not a full proof of safe retirement under every queue schedule; the author should review and extend the pinned/blocked-queue tests before merging.

Candidate correction and regression diff
diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs
index 979b4d04..cae3e6a3 100644
--- a/crates/xcl/src/hle/d3d12x/sparse.rs
+++ b/crates/xcl/src/hle/d3d12x/sparse.rs
@@ -1658,8 +1658,26 @@ impl State {
         let mut t = first;
         while t < end {
             if !self.mapped.contains_key(&t) && !self.mirror_src.contains_key(&t) && self.window_index(t).is_some() {
-                // still mapped there: no new mapping, what it held is cleared
-                if let Some(tile) = self.parked.remove(&t).or_else(|| self.kept.remove(&t)) {
+                // A new GPU heap at this address cannot inherit a parked system-memory tile.
+                // Acquire its replacement first; keep the old mapping if video memory is unavailable.
+                if let Some(old) = self.parked.get(&t).copied().filter(|tile| is_hot(t) && tile.0 & SYS != 0 && !self.pinned.contains_key(tile)) {
+                    let Some((tile, reused)) = self.take_tile() else { break };
+                    let wi = self.window_index(t).expect("mapped window");
+                    let (b, r) = (self.windows[wi].0, self.windows[wi].1.clone());
+                    self.unmap_tiles(&r, b, &[t]);
+                    TILE_WORK[2].fetch_add(1, Ordering::Relaxed);
+                    self.signal();
+                    self.quarantine_tiles(vec![old]);
+                    self.parked.remove(&t);
+                    self.mapped.insert(t, TileEntry::with_holes(tile, initial_holes(t)));
+                    early_add(&mut self.runs, t, t + TILE);
+                    if reused {
+                        self.to_zero.insert((t, TILE));
+                    }
+                    self.pending.push(t);
+                    new = true;
+                } else if let Some(tile) = self.parked.remove(&t).or_else(|| self.kept.remove(&t)) {
+                    // still mapped there: no new mapping, what it held is cleared
                     self.mapped.insert(t, TileEntry::with_holes(tile, initial_holes(t)));
                     early_add(&mut self.runs, t, t + TILE);
                     self.to_zero.insert((t, TILE));
@@ -5506,6 +5524,38 @@ mod tests {
         assert_eq!(system.0 & !SYS, video.0);
     }
 
+    #[test]
+    fn a_parked_cold_tile_does_not_back_a_new_hot_heap() {
+        use windows_sys::Win32::System::Memory::MEM_RELEASE;
+
+        if !sysmem_tiles() {
+            return crate::gpu::recomp::runner::skip_test("XCL_SPARSE_SYSMEM=1 required");
+        }
+        let _lazy = Lazy::on(false);
+        unsafe {
+            let (base, mut s) = test_state_with_reserved(1);
+            s.commit_range(base, TILE);
+            s.flush_pending();
+            let cold = s.mapped[&base].pool;
+            if cold.0 & SYS == 0 {
+                s.wait_for(s.value);
+                drop(s);
+                assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0);
+                return crate::gpu::recomp::runner::skip_test("system-memory pool unavailable");
+            }
+            s.decommit_range(base, TILE);
+            assert_eq!(s.parked.get(&base), Some(&cold));
+            note_hot(base, TILE);
+            s.commit_range(base, TILE);
+            assert_eq!(s.mapped[&base].pool.0 & SYS, 0, "a hot heap must use video memory");
+            s.flush_pending();
+            s.wait_for(s.value);
+            drop(s);
+            HOT.lock().unwrap().retain(|&(a, n)| a != base || n != TILE);
+            assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0);
+        }
+    }
+
     #[test]
     fn aligned_tile_addresses_spread_across_hash_buckets() {
         use std::hash::BuildHasher;

Separate test-coverage note: with XCL_SPARSE_SYSMEM=1, the broader parked filter still has two existing failures because those tests expect released tiles in the video-memory s.cooling queue. The candidate does not change them. With the feature unset, that filter completed 6 passed, 0 failed, with the new SYS-only case reporting a skip; those six passes are not six SYS-mode coverage cases.

No game files or title executable were used. AI use: Codex (GPT-6.2 Sol) wrote and ran the red/green test and candidate; Codex (GPT-6.2 Astra) checked the mapping and fence sequence.

@Decodere

Copy link
Copy Markdown
Contributor

Independent desktop NVIDIA verification of PR #2987 at head 6c5904f9426ffdfd4772399c92bfa84ddf29f6e2 (1 commit; exact parent & merge-base: a5e2d851a503fc0e04609f773ea53f2d2c4e3269 on nvidia-dev).

Environment

  • 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 (6C / 12T), 32 GB RAM (31.9 GiB usable), Windows 11 Home 26200 (Developer Mode off)
  • Toolchain: rustc 1.100.0 (0ef1bc386 2026-11-09) MSVC, DXC 1.9.2609.5, --release

Targeted release tests & build (6c5904f9)

Command Result
cargo test --release -p xcl --lib -- hle::d3d12x::sparse::tests::the_title_gpu_heaps_are_hot_and_nothing_around_them --exact --nocapture (3 consecutive runs) 1 passed; 0 failed; 0 ignored; 1727 filtered out × 3 (0.00s × 3, 0 skipped)
cargo test --release -p xcl --lib -- hle::d3d12x::sparse:: --test-threads=1 --nocapture (3 consecutive runs) 67 passed; 0 failed; 1 ignored; 1660 filtered out × 3 (5.20s, 4.74s, 4.98s, 0 skipped; 1 #[ignore]: early_commit_timing)
cargo test --release -p xcl --lib -- hle::kernelx:: --test-threads=1 --nocapture (3 consecutive runs) 61 passed; 0 failed; 1 ignored; 1666 filtered out × 3 (1.25s, 1.25s, 1.26s, 0 skipped; 1 #[ignore]: scatter_timing)
cargo build --release -p xcl Clean build (2m 16s, exit 0, 0 new warnings in sparse.rs / kernelx.rs; pre-existing rbq_value warning unchanged from a5e2d851)

Paired quiet 60 s retail smokes (title: 29640639, XCL_PREPARE=0 XCL_NETWORK=0)

Exact parent & merge-base (a5e2d851a503fc0e04609f773ea53f2d2c4e3269, XCL_PREPARE=0 XCL_NETWORK=0):

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

PR #2987 default (6c5904f9426ffdfd4772399c92bfa84ddf29f6e2, XCL_SPARSE_SYSMEM unset, XCL_PREPARE=0 XCL_NETWORK=0):

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

PR #2987 opt-in (6c5904f9426ffdfd4772399c92bfa84ddf29f6e2, XCL_SPARSE_SYSMEM=1, XCL_PREPARE=0 XCL_NETWORK=0):

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

Runtime memory & sparse-pool telemetry (xcl.log steady-state ~48–58 s)

Run Local VRAM Non-local Sparse VRAM pools (mapped) Peak commit Avg submit cost
Parent a5e2d851 (default) 6115 MB 4741 MB 896 MB (838 MB mapped) 14755 MB 0.17–0.18 ms
PR #2987 default (XCL_SPARSE_SYSMEM unset) 6116 MB 4782 MB 896 MB (838 MB mapped) 14740 MB 0.18–0.19 ms
PR #2987 opt-in (XCL_SPARSE_SYSMEM=1) 5218 MB (-898 MB / -14.7%) 5597 MB (+815 MB) 0 MB (0 MB mapped) 14637 MB 0.15–0.16 ms

Under XCL_SPARSE_SYSMEM=1, the runtime log confirmed activation (sparse windows: XCL_SPARSE_SYSMEM=1 - tiles outside the title's GPU heaps in system memory) and system-memory pool heap growth (64 -> 128 -> 256 -> 512 MB logged at power-of-two checkpoints), keeping VRAM sparse pools at 0 MB and reducing RTX 4060 local VRAM usage by 898 MB with 0 device removals and 0 crashes.

Limits of coverage

  • Verified the note_hot/is_hot range boundary predicate (the_title_gpu_heaps_are_hot_and_nothing_around_them 3/3), hle::d3d12x::sparse:: (67/0/1 × 3), hle::kernelx:: (61/0/1 × 3), default-off non-regression, and live XCL_SPARSE_SYSMEM=1 L0 pool routing (-898 MB local VRAM) on RTX 4060 (8 GB).
  • The opt-in 60 s smoke ran with XCL_SPARSE_SYSMEM=1 alone (without XCL_COHERENT_HEAPS=sparse); did not run a combined XCL_COHERENT_HEAPS=sparse + XCL_SPARSE_SYSMEM=1 multi-minute post-menu world-load stress test.
  • Paired 60 s retail smokes ran with XCL_PREPARE=0 (XCL_NETWORK=0), bypassing startup prepare_for_launch, and the 2 #[ignore] timing tests (early_commit_timing, scatter_timing) were not executed.

AI disclosure: test execution and report drafting assisted by Google Antigravity (Gemini 4 Neon).

@thehollowedone

Copy link
Copy Markdown
Contributor

The Windows no-GPU CI run for head 6c5904f9 exits with D3D12 device removal 0x887a0020 on Microsoft Basic Render Driver. Its last allocation is a 3 GiB GPU-view alias. In this test module, a_gpu_view_tile_is_filled_from_its_cpu_view_and_follows_its_writes is the path that requests exactly 3 GiB when software(&test_device()) returns false; its software path requests 53 tiles. The abort suppresses the test name, so this is a source/log correlation, not a definitive harness attribution.

software() currently returns false when factory creation, adapter lookup, or GetDesc1 fails. For this test's allocation decision, an unknown adapter should use the bounded software case. The candidate below does that while preserving the large case when a known hardware adapter reports no software flag. Microsoft documents the Basic Render Driver's software flag.

On Windows 11 build 26300, RTX 3080 Ti / driver 621.35, the new unknown_adapter_uses_the_small_gpu_view_case regression failed 0/1/0 before the policy change and passed 1/0/0 afterward. With XCL_TEST_WARP=1, cargo test --offline --locked -p xcl --lib a_gpu_view_tile_is_filled_from_its_cpu_view_and_follows_its_writes -- --nocapture --test-threads=1 passed 1/0/0, no skip, and logged a 0x350000-byte GPU view. That WARP test also passed on the unchanged PR head here; I could not reproduce the runner's failed adapter classification locally. The full suite and CI on this candidate are untested. Rerunning the same CI job after the author integrates the small guard would decide whether it resolves this crash.

Candidate test-only diff
diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs
index 979b4d04..0605a02f 100644
--- a/crates/xcl/src/hle/d3d12x/sparse.rs
+++ b/crates/xcl/src/hle/d3d12x/sparse.rs
@@ -4943,12 +4943,25 @@ mod tests {
         dev.expect("D3D12 device")
     }
 
+    fn software_flags(flags: Option<u32>) -> bool {
+        use windows::Win32::Graphics::Dxgi::DXGI_ADAPTER_FLAG_SOFTWARE;
+        flags.map_or(true, |f| f & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0)
+    }
+
+    #[test]
+    fn unknown_adapter_uses_the_small_gpu_view_case() {
+        use windows::Win32::Graphics::Dxgi::DXGI_ADAPTER_FLAG_SOFTWARE;
+        assert!(software_flags(None));
+        assert!(software_flags(Some(DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32)));
+        assert!(!software_flags(Some(0)));
+    }
+
     /// Whether `dev` is a software device (WARP).
     unsafe fn software(dev: &ID3D12Device) -> bool {
         use windows::Win32::Graphics::Dxgi::*;
-        let Ok(factory) = CreateDXGIFactory1::<IDXGIFactory4>() else { return false };
+        let Ok(factory) = CreateDXGIFactory1::<IDXGIFactory4>() else { return true };
         let adapter: windows::core::Result<IDXGIAdapter1> = factory.EnumAdapterByLuid(dev.GetAdapterLuid());
-        adapter.and_then(|a| a.GetDesc1()).is_ok_and(|d| d.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0)
+        software_flags(adapter.and_then(|a| a.GetDesc1()).ok().map(|d| d.Flags))
     }
 
     /// The small ones of an upload's runs go up in dispatches: each lands where it belongs (far

AI use: Codex (GPT-6.2 Sol) traced the CI and source, wrote the candidate, and ran the focused tests.

@LocranKing

Copy link
Copy Markdown

Tested PR #2987 (6c5904f9) on Windows 11 with a Series S (lockhart) profile, including a paired A/B 240 s open-world comparison with XCL_SPARSE_SYSMEM=1 vs unset and the unit test.

Environment

  • GPU: NVIDIA GeForce RTX 3060 Ti (8024 MiB VRAM, ~7.25 GB process DXGI local budget, Resizable BAR / GPU_UPLOAD supported, driver 32.0.16.2140)
  • CPU / RAM: AMD Ryzen 5 5500 (6C/12T), 32 GB DDR4, Windows 11 Build 26300
  • Shader cache & runtime: Frozen nvidia-dev DXIL cache (XCL_DIRECT_DXIL=1, XCL_HEAP_WINDOWS=1, XCL_TEXTURE_LEVEL_PAGES=1, XCL_PREPARE_GRAPHICS=0, XCL_DRED=1), XCL_COHERENT_HEAPS=sparse for both PR runs

Unit test

cargo test --locked -p xcl --lib -- the_title_gpu_heaps_are_hot --nocapture on 6c5904f9:

  • hle::d3d12x::sparse::tests::the_title_gpu_heaps_are_hot_and_nothing_around_them — ok (1 passed, 0 failed)

Paired A/B 240 s World Runs (XCL_COHERENT_HEAPS=sparse, RTX 3060 Ti 8 GB)

Run Commit / Env Exit Crashes / Removals Frames (PresentX) Heavy world start (>=700 draws/2s) Peak Commit Peak Local VRAM Peak Non-Local Peak Target Pages Peak Sparse Pools
Base (180 s, default heaps) a5e2d851 0x0 0 / 0 1861 151.36 s 25770 MB 8974 MB 4677 MB 3880 MB 2560 MB (2393 MB mapped)
Base (240 s, default heaps) a5e2d851 0xc0000005 (188.46 s) 2 / 0 — 126.29 s 25909 MB 9351 MB 4768 MB 3864 MB 2624 MB (2423 MB mapped)
#2987 unset (240 s) 6c5904f9, XCL_COHERENT_HEAPS=sparse 0x0 0 / 0 1999 (0 1 3 last 3/2s) 138.55 s 31745 MB 13121 MB 2019 MB 4380 MB 5568 MB (5344 MB mapped)
#2987 + XCL_SPARSE_SYSMEM=1 (240 s) 6c5904f9, XCL_COHERENT_HEAPS=sparse, XCL_SPARSE_SYSMEM=1 0x0 0 / 0 1896 (1 2 2 last 3/2s) 120.65 s 31726 MB 10560 MB 4915 MB 4518 MB 2944 MB (2892 MB mapped)

Summary

  • Both 240 s runs under XCL_COHERENT_HEAPS=sparse reached the world cleanly and exited 0x0 with 0 device removals and 0 crashes on this 8 GB card.
  • Enabling XCL_SPARSE_SYSMEM=1 logged sparse windows: XCL_SPARSE_SYSMEM=1 - tiles outside the title's GPU heaps in system memory and reduced peak local VRAM by 2,561 MB (13,121 MB -> 10,560 MB), shifting ~2.6 GB of sparse pool allocations (5,568 MB -> 2,944 MB local; non-local 2,019 MB -> 4,915 MB) into system memory while keeping the hot GPU heaps in local VRAM.

@thehollowedone

thehollowedone commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Follow-up on PR head 6c5904f9. I revised my earlier candidate after reviewing a failed system-memory heap allocation. This diff supersedes the one previously in this comment.

  • A released hot reservation can leave its placement marker behind. A later cold allocation at that address then selects video memory. The local fix removes the marker before returning the address to UMA, including the allocation-failure path. My earlier release regression failed on the unchanged head and passed with the fix.
  • A parked tile can belong to a different memory class from the next owner. The local fix acquires replacement backing before disturbing the parked mapping. If an L0 allocation fails, the existing video-memory fallback remains usable; a successful replacement remaps the address, then quarantines displaced tiles behind one fence batch. Pinned placed-buffer aliases keep their backing. My earlier class-transition regression failed on the unchanged head and passed with the fix.
  • The hot-reservation lookup is on the per-tile path. Nonoverlapping UMA reservation starts now use a BTreeMap for logarithmic lookup and removal instead of a growing linear scan.

Tested: Windows 11 build 26300, RTX 3080 Ti / 621.35, Ryzen 7 9800X3D, rustc 1.99.1 MSVC. The revised synthetic tests force the feature on their own thread and include GPU readback, L0 capability checks, failed-allocation preservation, batched replacement, pinned backing, and release cleanup. cargo test -p xcl --lib hle::d3d12x::sparse::tests -- --test-threads=4: 74 passed, 0 failed, 1 ignored. With an isolated Cargo target, cargo test --workspace -- --test-threads=4: 1,705 passed, 2 failed, 28 ignored; 25 GPU skip notices (21 no wave64, 3 unsupported per-lane instruction cases, 1 opt-in heap-window test). Both failures are integer overflows in texture_upload::tests::{pieces_hold_the_texels_of_their_levels,gpu_parts_of_a_texture_go_up_and_the_rest_stays}; each also failed alone at the same line on untouched PR head 6c5904f9. git diff --check passed.

Not tested: A clean-commit paired title smoke, AMD/Intel, and a live placed-buffer alias. The diff is uncommitted and is a candidate for the author to review; it is not merge-ready evidence. The separate lazy first-write finding still needs its allocator-path fix.

Revised candidate fix and focused regressions (uncommitted diff)
diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs
index 979b4d04..d29f3b30 100644
--- a/crates/xcl/src/hle/d3d12x/sparse.rs
+++ b/crates/xcl/src/hle/d3d12x/sparse.rs
@@ -388,15 +388,30 @@ struct SysPools {
 unsafe impl Send for SysPools {}
 
 static SYS_POOLS: Mutex<Option<SysPools>> = Mutex::new(None);
-/// the title's GPU heaps in the sparse windows (`XCL_COHERENT_HEAPS=sparse`): (start, bytes)
-static HOT: Mutex<Vec<(usize, usize)>> = Mutex::new(Vec::new());
+/// The title's GPU heaps in the sparse windows (`XCL_COHERENT_HEAPS=sparse`): start -> bytes.
+/// UMA reservations do not overlap; lookup is per tile, so keep it logarithmic.
+static HOT: Mutex<BTreeMap<usize, usize>> = Mutex::new(BTreeMap::new());
 
 /// `[a, a + n)` is a GPU heap of the title: its tiles keep video memory under `XCL_SPARSE_SYSMEM`.
 pub fn note_hot(a: usize, n: usize) {
-    HOT.lock().unwrap().push((a, n));
+    HOT.lock().unwrap().insert(a, n);
+}
+
+/// A released reservation no longer determines the pool class at this address.
+pub fn forget_hot(a: usize, n: usize) {
+    let mut hot = HOT.lock().unwrap();
+    if hot.get(&a) == Some(&n) {
+        hot.remove(&a);
+        #[cfg(test)]
+        tests::FORGOT_HOT_FOR_TEST.with(|c| c.set(a));
+    }
 }
 
 fn sysmem_tiles() -> bool {
+    #[cfg(test)]
+    if let Some(on) = tests::SYSMEM_TILES_FOR_TEST.with(|c| c.get()) {
+        return on;
+    }
     static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
     *ON.get_or_init(|| {
         let on = std::env::var("XCL_SPARSE_SYSMEM").is_ok_and(|v| v.trim() == "1");
@@ -408,7 +423,7 @@ fn sysmem_tiles() -> bool {
 }
 
 fn is_hot(a: usize) -> bool {
-    HOT.lock().unwrap().iter().any(|&(s, n)| a >= s && a < s + n)
+    HOT.lock().unwrap().range(..=a).next_back().is_some_and(|(&start, &len)| a - start < len)
 }
 
 /// Bytes of the system-memory pool heaps.
@@ -1265,7 +1280,11 @@ impl State {
     }
 
     /// `take_tile` from the system-memory pools (`XCL_SPARSE_SYSMEM`).
-    unsafe fn take_sys_tile(&mut self) -> Option<((u32, u32), bool)> {
+    unsafe fn take_sys_tile(&mut self, strict: bool) -> Option<((u32, u32), bool)> {
+        #[cfg(test)]
+        if tests::SYS_FALLBACK_FOR_TEST.with(|c| c.get()) {
+            return if strict { None } else { self.take_tile() };
+        }
         self.drain_quarantined();
         let mut g = SYS_POOLS.lock().unwrap();
         let p = g.get_or_insert_with(SysPools::default);
@@ -1285,9 +1304,11 @@ impl State {
         };
         let mut heap: Option<ID3D12Heap> = None;
         if let Err(e) = super::title_textures::own_work(|| self.dev.CreateHeap(&desc, &mut heap)) {
-            crate::xlog_warn!("sparse windows: no system-memory pool heap ({e}) - video memory instead");
+            if !strict {
+                crate::xlog_warn!("sparse windows: no system-memory pool heap ({e}) - video memory instead");
+            }
             drop(g);
-            return self.take_tile();
+            return if strict { None } else { self.take_tile() };
         }
         let heap = heap?;
         let _ = heap.SetName(windows::core::w!("xcl sparse system-memory pool"));
@@ -1574,10 +1595,11 @@ impl State {
         let end = a.saturating_add(n);
         let mut t = a & !(TILE - 1);
         let mut new = false;
+        let mut parked = false;
         while t < end {
             if !self.mapped.contains_key(&t) && !self.mirror_src.contains_key(&t) && self.window_index(t).is_some() {
                 if self.parked.contains_key(&t) || self.kept.contains_key(&t) {
-                    self.ensure_mapped(t, TILE, |_| 0xFFFF);
+                    parked = true;
                 } else {
                     self.mapped.insert(t, TileEntry::with_holes(LAZY, 0xFFFF));
                     early_add(&mut self.runs, t, t + TILE);
@@ -1592,6 +1614,9 @@ impl State {
         if new {
             MAPPED_GEN.fetch_add(1, Ordering::Release);
         }
+        if parked {
+            self.ensure_mapped(a, n, |_| 0xFFFF);
+        }
     }
 
     /// The `LAZY` tiles of `[a, a + n)` get their video memory now (their mapping is pending,
@@ -1655,25 +1680,43 @@ impl State {
         let end = a.saturating_add(n);
         let mut new = false;
         let mut unparked = false;
+        let mut replaced = Vec::new();
         let mut t = first;
         while t < end {
             if !self.mapped.contains_key(&t) && !self.mirror_src.contains_key(&t) && self.window_index(t).is_some() {
-                // still mapped there: no new mapping, what it held is cleared
-                if let Some(tile) = self.parked.remove(&t).or_else(|| self.kept.remove(&t)) {
-                    self.mapped.insert(t, TileEntry::with_holes(tile, initial_holes(t)));
-                    early_add(&mut self.runs, t, t + TILE);
-                    self.to_zero.insert((t, TILE));
-                    unparked = true;
-                } else {
-                    let got = if sysmem_tiles() && !is_hot(t) { self.take_sys_tile() } else { self.take_tile() };
-                    let Some((tile, reused)) = got else { break };
-                    self.mapped.insert(t, TileEntry::with_holes(tile, initial_holes(t)));
-                    early_add(&mut self.runs, t, t + TILE);
-                    if reused {
+                let want_sys = sysmem_tiles() && !is_hot(t);
+                let mut replaced_here = false;
+                if let Some(&old) = self.parked.get(&t).filter(|tile| (tile.0 & SYS != 0) != want_sys && !self.pinned.contains_key(tile)) {
+                    let replacement = if want_sys { self.take_sys_tile(true) } else { self.take_tile() };
+                    if let Some((tile, _)) = replacement {
+                        self.parked.remove(&t);
+                        self.mapped.insert(t, TileEntry::with_holes(tile, initial_holes(t)));
+                        early_add(&mut self.runs, t, t + TILE);
                         self.to_zero.insert((t, TILE));
+                        self.pending.push(t);
+                        replaced.push(old);
+                        new = true;
+                        replaced_here = true;
+                    }
+                }
+                if !replaced_here {
+                    // A failed replacement keeps its existing backing, which is cleared on reuse.
+                    if let Some(tile) = self.parked.remove(&t).or_else(|| self.kept.remove(&t)) {
+                        self.mapped.insert(t, TileEntry::with_holes(tile, initial_holes(t)));
+                        early_add(&mut self.runs, t, t + TILE);
+                        self.to_zero.insert((t, TILE));
+                        unparked = true;
+                    } else {
+                        let got = if want_sys { self.take_sys_tile(false) } else { self.take_tile() };
+                        let Some((tile, reused)) = got else { break };
+                        self.mapped.insert(t, TileEntry::with_holes(tile, initial_holes(t)));
+                        early_add(&mut self.runs, t, t + TILE);
+                        if reused {
+                            self.to_zero.insert((t, TILE));
+                        }
+                        self.pending.push(t);
+                        new = true;
                     }
-                    self.pending.push(t);
-                    new = true;
                 }
             }
             match t.checked_add(TILE) {
@@ -1684,7 +1727,10 @@ impl State {
         if new || unparked {
             MAPPED_GEN.fetch_add(1, Ordering::Release);
         }
-        if self.pending.len() >= PENDING_MAX {
+        if !replaced.is_empty() {
+            self.flush_pending();
+            self.quarantine_tiles(replaced);
+        } else if self.pending.len() >= PENDING_MAX {
             self.flush_pending();
         } else if !self.pending.is_empty() {
             pending_soon();
@@ -2528,6 +2574,9 @@ pub unsafe fn alloc_as(size: usize, align: usize, hot: bool) -> Option<(usize, u
         note_hot(addr, rounded);
     }
     if VirtualAlloc(addr as *const c_void, rounded, MEM_COMMIT, PAGE_READWRITE).is_null() {
+        if hot {
+            forget_hot(addr, rounded);
+        }
         u.sparse_release(addr);
         return None;
     }
@@ -2559,6 +2608,7 @@ pub unsafe fn free(p: usize) -> bool {
     let Some((start, len)) = u.sparse_reservation(p).filter(|&(start, _)| start == p) else { return false };
     decommitted(start, len);
     VirtualFree(p as *mut c_void, len, MEM_DECOMMIT);
+    forget_hot(start, len);
     u.sparse_release(p).is_some()
 }
 
@@ -4837,6 +4887,9 @@ mod tests {
         pub(super) static LAZY_COMMITS_FOR_TEST: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
         /// `take_tile` finds no video memory on this thread
         pub(super) static NO_TILES: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
+        pub(super) static SYSMEM_TILES_FOR_TEST: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
+        pub(super) static SYS_FALLBACK_FOR_TEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
+        pub(super) static FORGOT_HOT_FOR_TEST: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
     }
 
     /// The runs of the tiles mapped, made from all of them (but those over a CPU view: their
@@ -5506,6 +5559,45 @@ mod tests {
         assert_eq!(system.0 & !SYS, video.0);
     }
 
+    #[test]
+    fn releasing_a_hot_sparse_reservation_clears_its_placement_class() {
+        let Some(u) = crate::gpu::uma::get() else {
+            return crate::gpu::recomp::runner::skip_test("no unified memory");
+        };
+        if !u.has_sparse() {
+            return crate::gpu::recomp::runner::skip_test("no sparse window");
+        }
+        unsafe {
+            FORGOT_HOT_FOR_TEST.with(|c| c.set(0));
+            let (p, _) = alloc_as(TILE, TILE, true).expect("hot sparse allocation");
+            assert!(is_hot(p));
+            assert!(free(p));
+            assert_eq!(FORGOT_HOT_FOR_TEST.with(|c| c.get()), p, "release must remove the hot marker before publishing the address");
+            let (q, _) = alloc(TILE, TILE).expect("cold sparse allocation");
+            if q == p {
+                assert!(!is_hot(q), "a cold allocation reusing the address must use the cold class");
+            }
+            assert!(free(q));
+        }
+    }
+
+    #[test]
+    fn kernelx_release_clears_a_hot_sparse_reservation() {
+        let Some(u) = crate::gpu::uma::get() else {
+            return crate::gpu::recomp::runner::skip_test("no unified memory");
+        };
+        if !u.has_sparse() {
+            return crate::gpu::recomp::runner::skip_test("no sparse window");
+        }
+        unsafe {
+            FORGOT_HOT_FOR_TEST.with(|c| c.set(0));
+            let (p, _) = alloc_as(TILE, TILE, true).expect("hot sparse allocation");
+            assert!(is_hot(p));
+            assert_eq!(crate::hle::kernelx::VirtualFree(p as *mut c_void, 0, windows_sys::Win32::System::Memory::MEM_RELEASE), 1);
+            assert_eq!(FORGOT_HOT_FOR_TEST.with(|c| c.get()), p, "kernelx release must remove the hot marker before publishing the address");
+        }
+    }
+
     #[test]
     fn aligned_tile_addresses_spread_across_hash_buckets() {
         use std::hash::BuildHasher;
@@ -6020,14 +6112,38 @@ mod tests {
         fn no_tiles(&self, none: bool) {
             NO_TILES.with(|c| c.set(none));
         }
+        fn sysmem(&self, on: bool) {
+            SYSMEM_TILES_FOR_TEST.with(|c| c.set(Some(on)));
+        }
+        fn sys_fallback(&self, on: bool) {
+            SYS_FALLBACK_FOR_TEST.with(|c| c.set(on));
+        }
     }
     impl Drop for Lazy {
         fn drop(&mut self) {
             LAZY_COMMITS_FOR_TEST.with(|c| c.set(None));
             NO_TILES.with(|c| c.set(false));
+            SYSMEM_TILES_FOR_TEST.with(|c| c.set(None));
+            SYS_FALLBACK_FOR_TEST.with(|c| c.set(false));
         }
     }
 
+    unsafe fn custom_l0_heap_supported(dev: &ID3D12Device) -> bool {
+        let desc = D3D12_HEAP_DESC {
+            SizeInBytes: POOL_TILES as u64 * TILE as u64,
+            Properties: D3D12_HEAP_PROPERTIES {
+                Type: D3D12_HEAP_TYPE_CUSTOM,
+                CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK,
+                MemoryPoolPreference: D3D12_MEMORY_POOL_L0,
+                ..Default::default()
+            },
+            Alignment: 0,
+            Flags: D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES | D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES,
+        };
+        let mut heap: Option<ID3D12Heap> = None;
+        dev.CreateHeap(&desc, &mut heap).is_ok() && heap.is_some()
+    }
+
     /// A state of `tiles` tiles for the lazy tests, its window's CPU pages committed and the title's
     /// queue. None: no GPU whose unmapped tiles read zeros (the lazy path is left out there).
     unsafe fn lazy_state(tiles: usize) -> Option<(usize, State, ID3D12CommandQueue)> {
@@ -6075,6 +6191,150 @@ mod tests {
         (t..t + TILE).step_by(PAGE).collect()
     }
 
+    #[test]
+    fn a_cold_system_pool_tile_is_visible_through_the_gpu_window() {
+        let eager = Lazy::on(false);
+        eager.sysmem(true);
+        unsafe {
+            let Some((base, mut s, queue)) = lazy_state(1) else {
+                return crate::gpu::recomp::runner::skip_test("no GPU with tiled resources tier 2");
+            };
+            if !custom_l0_heap_supported(&s.dev) {
+                drop(s);
+                assert_ne!(VirtualFree(base as *mut c_void, 0, windows_sys::Win32::System::Memory::MEM_RELEASE), 0);
+                return crate::gpu::recomp::runner::skip_test("no custom L0 heap");
+            }
+            s.commit_range(base, TILE);
+            let pool = s.mapped[&base].pool.0;
+            assert_ne!(pool & SYS, 0, "cold tile must use the system-memory pool");
+            assert_eq!(s.pool_heap(pool).GetDesc().Properties.MemoryPoolPreference, D3D12_MEMORY_POOL_L0);
+            let dirty = write_tile(base, 23);
+            s.before_execute_on(&queue, &dirty, PAGE);
+            let cpu = std::slice::from_raw_parts(base as *const u8, TILE);
+            assert!(window_bytes(&mut s, base, TILE) == cpu, "GPU window must contain the uploaded tile bytes");
+            s.wait_for(s.value);
+            drop(s);
+            assert_ne!(VirtualFree(base as *mut c_void, 0, windows_sys::Win32::System::Memory::MEM_RELEASE), 0);
+        }
+    }
+
+    #[test]
+    fn a_parked_cold_tile_is_replaced_when_the_address_becomes_hot() {
+        let eager = Lazy::on(false);
+        eager.sysmem(true);
+        unsafe {
+            let Some((base, mut s, _queue)) = lazy_state(1) else {
+                return crate::gpu::recomp::runner::skip_test("no GPU with tiled resources tier 2");
+            };
+            if !custom_l0_heap_supported(&s.dev) {
+                drop(s);
+                assert_ne!(VirtualFree(base as *mut c_void, 0, windows_sys::Win32::System::Memory::MEM_RELEASE), 0);
+                return crate::gpu::recomp::runner::skip_test("no custom L0 heap");
+            }
+            s.ensure_mapped(base, TILE, |_| 0);
+            assert_ne!(s.mapped[&base].pool.0 & SYS, 0, "initial cold tile uses system memory");
+            s.decommit_range(base, TILE);
+            assert_ne!(s.parked[&base].0 & SYS, 0, "cold tile remains parked at its address");
+            note_hot(base, TILE);
+            s.ensure_mapped(base, TILE, |_| 0);
+            assert_eq!(s.mapped[&base].pool.0 & SYS, 0, "new hot reservation needs video memory");
+            s.decommit_range(base, TILE);
+            assert_eq!(s.parked[&base].0 & SYS, 0, "hot tile remains parked at its address");
+            forget_hot(base, TILE);
+            s.ensure_mapped(base, TILE, |_| 0);
+            assert_ne!(s.mapped[&base].pool.0 & SYS, 0, "new cold reservation needs system memory");
+            assert!(window_bytes(&mut s, base, TILE).iter().all(|&b| b == 0), "new cold mapping starts clear");
+            s.wait_for(s.value);
+            drop(s);
+            assert_ne!(VirtualFree(base as *mut c_void, 0, windows_sys::Win32::System::Memory::MEM_RELEASE), 0);
+        }
+    }
+
+    #[test]
+    fn a_parked_video_fallback_survives_when_system_memory_and_video_allocation_fail() {
+        let eager = Lazy::on(false);
+        eager.sysmem(true);
+        eager.sys_fallback(true);
+        unsafe {
+            let Some((base, mut s, _queue)) = lazy_state(1) else {
+                return crate::gpu::recomp::runner::skip_test("no GPU with tiled resources tier 2");
+            };
+            s.ensure_mapped(base, TILE, |_| 0);
+            let old = s.mapped[&base].pool;
+            assert_eq!(old.0 & SYS, 0, "cold allocation falls back to video memory");
+            s.flush_pending();
+            s.decommit_range(base, TILE);
+            eager.no_tiles(true);
+            s.ensure_mapped(base, TILE, |_| 0);
+            assert_eq!(s.mapped[&base].pool, old, "failed replacement must keep usable backing");
+            assert!(window_bytes(&mut s, base, TILE).iter().all(|&b| b == 0));
+            eager.no_tiles(false);
+            s.wait_for(s.value);
+            drop(s);
+            assert_ne!(VirtualFree(base as *mut c_void, 0, windows_sys::Win32::System::Memory::MEM_RELEASE), 0);
+        }
+    }
+
+    #[test]
+    fn parked_pool_changes_remap_together_without_disturbing_the_next_address() {
+        let eager = Lazy::on(false);
+        eager.sysmem(true);
+        unsafe {
+            let Some((base, mut s, _queue)) = lazy_state(3) else {
+                return crate::gpu::recomp::runner::skip_test("no GPU with tiled resources tier 2");
+            };
+            if !custom_l0_heap_supported(&s.dev) {
+                drop(s);
+                assert_ne!(VirtualFree(base as *mut c_void, 0, windows_sys::Win32::System::Memory::MEM_RELEASE), 0);
+                return crate::gpu::recomp::runner::skip_test("no custom L0 heap");
+            }
+            s.ensure_mapped(base, 3 * TILE, |_| 0);
+            let old: Vec<_> = (0..3).map(|i| s.mapped[&(base + i * TILE)].pool).collect();
+            s.flush_pending();
+            s.decommit_range(base, 3 * TILE);
+            note_hot(base, 2 * TILE);
+            s.ensure_mapped(base, 2 * TILE, |_| 0);
+            assert_eq!(s.parked.get(&(base + 2 * TILE)), Some(&old[2]));
+            assert!((0..2).all(|i| s.mapped[&(base + i * TILE)].pool.0 & SYS == 0));
+            assert!(s.pending.is_empty(), "replacements must be published before old tiles are retired");
+            assert_eq!(s.quarantined.back().map(|b| b.tiles.len()), Some(2), "old tiles share one fence batch");
+            forget_hot(base, 2 * TILE);
+            s.wait_for(s.value);
+            drop(s);
+            assert_ne!(VirtualFree(base as *mut c_void, 0, windows_sys::Win32::System::Memory::MEM_RELEASE), 0);
+        }
+    }
+
+    #[test]
+    fn a_pinned_parked_tile_keeps_its_pool_for_a_placed_buffer() {
+        let eager = Lazy::on(false);
+        eager.sysmem(true);
+        unsafe {
+            let Some((base, mut s, _queue)) = lazy_state(1) else {
+                return crate::gpu::recomp::runner::skip_test("no GPU with tiled resources tier 2");
+            };
+            if !custom_l0_heap_supported(&s.dev) {
+                drop(s);
+                assert_ne!(VirtualFree(base as *mut c_void, 0, windows_sys::Win32::System::Memory::MEM_RELEASE), 0);
+                return crate::gpu::recomp::runner::skip_test("no custom L0 heap");
+            }
+            s.ensure_mapped(base, TILE, |_| 0);
+            let old = s.mapped[&base].pool;
+            s.flush_pending();
+            s.pinned.insert(old, 1);
+            s.decommit_range(base, TILE);
+            note_hot(base, TILE);
+            s.ensure_mapped(base, TILE, |_| 0);
+            assert_eq!(s.mapped[&base].pool, old, "placed-buffer alias must keep its existing pool tile");
+            assert!(s.quarantined.is_empty());
+            forget_hot(base, TILE);
+            s.pinned.remove(&old);
+            s.wait_for(s.value);
+            drop(s);
+            assert_ne!(VirtualFree(base as *mut c_void, 0, windows_sys::Win32::System::Memory::MEM_RELEASE), 0);
+        }
+    }
+
     /// With `XCL_SPARSE_LAZY` a committed tile gets no video memory until the CPU's first bytes
     /// go up to it; they reach the GPU, and a later submit with nothing written leaves them there
     /// (a tile cleared one submit after its bytes went up would read zeros). A tile never written
diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs
index 913b7fd1..569da074 100644
--- a/crates/xcl/src/hle/kernelx.rs
+++ b/crates/xcl/src/hle/kernelx.rs
@@ -1199,6 +1199,7 @@ pub unsafe extern "system" fn VirtualFree(addr: *mut c_void, size: usize, t: u32
             mirrors::released(a);
             forget_title_mappings(a, n);
             let gone = mirrors::place_gone(a, n);
+            crate::hle::d3d12x::sparse::forget_hot(a, n);
             u.sparse_release(a);
             // (tiles may show pages kept here)
             if mirrors::any_mapped() {

AI use: Codex (GPT-6.2 Sol) revised the candidate and ran the tests; Codex (GPT-6.2 Astra) independently reviewed the replacement invariant.

@gefydev

gefydev commented Nov 27, 2026

Copy link
Copy Markdown
Member

4 GB data point: GTX 1650 (driver 621.24), 16 GB RAM, Ryzen 5 1600, Windows 11 26300, head 6c5904f9 unmodified, release.

  • cargo test --release -p xcl --lib the_title_gpu_heaps_are_hot: 1 passed.
  • cargo test --release -p xcl --lib hle::d3d12x::sparse -- --test-threads=1: 67 passed, 0 failed, 1 ignored. With XCL_SPARSE_SYSMEM=1 set: 64 passed, 3 failed, 1 ignored. The three assert on State::cooling; from reading State::cool, a system-pool tile cools in SysPools instead.
  • Retail title, one run, Series S profile, XCL_COHERENT_HEAPS=sparse:1024 XCL_SPARSE_SYSMEM=1 plus my usual memory and pipeline switches: device removed (0x887a0005) at 806 s, before a 3D frame. Just before: 6.85 GB local (budget 3.3 GB), 4.4 GB non-local, 2.9 GB of sparse pools in video memory, 3.0 GB of target pages.
  • From 805 s, 15 system-memory pool heap creations failed with 0x8007000E and fell back to video memory, with 10.8 GB of system commit still free.

Not tested: the same run with the switch unset.

AI use: Claude Code (Claude Sonnet 5.5) built, ran and wrote this for @gefydev.

@throny

throny commented Nov 27, 2026

Copy link
Copy Markdown
Collaborator

Test of this PR's exact diff (6c5904f9) on the newest nvidia-dev d1be8103, RTX 4080 16 GB (driver 621.40, 2 GiB shader-heap profile), i9-12900K, Windows 11 26300, 64 GB + 32 GB page file. The tree also had #684 and #2951 (so launches are quick) and a local press-timing patch; nothing else. Same build base, same save, 600 s each, XCL_COHERENT_HEAPS=sparse XCL_TEXTURE_LEVEL_PAGES=1 XCL_CS_PSO_WAIT_MS=200 XCL_TWO_PASS_MB=3072:

without the PR with the PR, XCL_SPARSE_SYSMEM=1
video memory in use at the end (budget 15.2 GB) 21.7 GB, 6.5 GB over 18.8 GB, 3.6 GB over
process commit at the end 51.7 GB 52.0 GB
presents per second in the world (from 240 s after the first frame, 350 s) 1.60 1.50
device removals, crashes 0 0

So on this card the switch moves about 2.9 GB out of video memory as intended, with no cost in commit and no stability problem in 10 minutes. It does not raise the present rate here (1.5-1.6 either way, one run each, so the difference is noise), and the process is still 3.6 GB over the budget; XCL_TEXTURE_SYSMEM from your prototype was what brought it under on my earlier runs.

Not tested: the picture (the world is black on this machine on every build, see #505), a run longer than 10 minutes, AMD, default heap placement.

Numbers are from the logs of these two runs. AI use: Claude Code (Claude Fable 5.2) ran the tests and wrote this.

@gefydev

gefydev commented Nov 27, 2026

Copy link
Copy Markdown
Member

Follow-up, not a test of this PR alone: the same head plus b6fd1f2, texture pool pages in system memory past the budget, and the upload queue created with the device (local build). Local at the failing point 4.4 GB instead of 6.85 GB, no system-memory pool failures, but a 0xc0000005 inside nvwgf2umx.dll at 845 s at world entry; still no 3D frame. Local + non-local about 11 GB. One run each.

AI use: Claude Code (Claude Sonnet 5.5) built, ran and wrote this for @gefydev.

With XCL_COHERENT_HEAPS=sparse the title's GPU heaps (committed memory with
a PAGE_GRAPHICS_* protection, ~4.5 GB in a retail title) live in the sparse
windows. Those are the data the title's shaders read and write every frame;
in the coherent window (system memory, read over PCIe) one retail compute
program took 1,364 ms a frame on an RTX 3080, under 33 ms in video memory.
With them in video memory the windows hold ~7.5 GB of tiles and the device
ran out of its budget (19 GB in use against 8.9 GB, removed at 659 s).

XCL_SPARSE_SYSMEM=1 (off by default): kernelx registers a GPU heap's range
as hot before its commit maps its tiles (sparse::alloc_as); every other
sparse-window tile takes a pool tile in system-memory pool heaps (custom
heaps, L0, write-back), which the GPU reads over PCIe. A pool tile of those
heaps has SYS in its pool index; freed ones cool in their own lists.

RTX 3080, retail title, 400 s of its world after the menus: heaps in video
memory alone 0.98 presents/s and 19 GB of video memory; with this and the
texture-level counterpart 1.70 presents/s, 12.7 GB, no device removal in
900 s. An RTX 4080 report on xcl-dev#2688 found the same with a port of it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@treybertram06

Copy link
Copy Markdown
Contributor Author

@thehollowedone thanks, all three are right. Fixed in f8e75bca (squashed into the one commit, rebased on nvidia-dev d1be8103):

  • Lazy first write (your first comment): materialize takes its tile through the same choice as ensure_mapped (take_tile_for). A system-memory tile doesn't wait when video memory is short.
  • Parked system-memory tile under a new GPU heap: when a hot address takes back a parked tile that has SYS, a video-memory tile is mapped over it at once. The old tile goes to quarantine_tiles behind the fences of that flush. A tile a placed buffer has pinned keeps its backing. If no video memory is found, it keeps the old tile, as before.
    • I didn't do the reverse case: a parked video tile that ends up under a cold allocation stays in video memory. That costs placement but not correctness, and it's what happens without the switch.
  • Released hot reservations: forget_hot(a) is called on sparse::free, on the alloc_as commit failure path, and on kernelx's MEM_RELEASE of a sparse reservation. I kept the Vec: there are a few dozen GPU heaps per run.
  • XCL_SPARSE_SYSMEM in tests (gefydev's 3 cooling failures): under cfg(test), sysmem_tiles() follows a thread-local that a test sets, never the environment. The existing tests now pass with the variable set.

New tests (each fails on 6c5904f9's logic and passes now, RTX 3080 / 621.40, no skips):

  • a_lazy_tile_outside_the_gpu_heaps_gets_system_memory
  • a_parked_system_memory_tile_gives_way_to_a_gpu_heap, which checks the old tile is quarantined and reads the new bytes back through the window
  • the_title_gpu_heaps_are_hot_and_nothing_around_them, extended with forget_hot

The no-GPU CI failure (0x887a0020) also happens on other recent nvidia-dev PRs (#3036, #3037). I left the test helper alone here, since it's outside this PR.

@gefydev the 0x8007000E from system-memory heap creation at 805 s on the 4 GB card looks like a separate limit. I don't have a 4 GB card to check it, so I've added it under Not tested.

Thanks to @3L1A5-1, @LocranKing and @throny for the runs. throny's numbers match mine: this switch moves memory out of video memory, and the frame-rate gain on a 10 GB card comes with the texture-level part, which I'll open next as a PR stacked on this one.

AI use: Claude Code (Claude Opus 5.5) wrote the fixes and tests, ran them, and wrote this reply.

@andrewDoing

Copy link
Copy Markdown

I retested the stale hot-range lifecycle from my prototype report on head f8e75bca1ea903b1cf0e9d4f9387b73f359e5051 using the exact-head source plus a test-only fixture and its test-mode switch.

Three fresh-process controls passed with zero skips: normal sparse::free, an injected 64 KiB commit failure, and the title-facing VirtualFree(MEM_RELEASE) path. In each, the next cold reservation reused the same address and is_hot was false, so the placement policy selected L0. The original prototype retained the hot classification in the normal-release and injected-failure controls.

This verifies reservation bookkeeping and policy selection. It does not allocate a GPU backing heap or measure physical residency, a retail workload, or performance.

AI use: OpenAI Codex with GPT-6.2 Astra ran the controls; Codex reviewed and prepared this report.

@DarkPanda69

Copy link
Copy Markdown

AMD run for the Not tested line.

Tested: pass, head f8e75bc applied on its base nvidia-dev d1be810, debug, Rust 1.100.0, Windows 11 Pro 26200, Ryzen 7 5800X.
cargo test -p xcl --lib -- hle::d3d12x::sparse hle::kernelx --test-threads=4 --nocapture:

  • AMD RX 9070 XT (RDNA4), driver 32.0.32029.2010: 130 passed, 0 failed, 2 ignored, 0 SKIPPED (nvidia-dev alone: 127 passed). New and ok: the_title_gpu_heaps_are_hot_and_nothing_around_them, a_lazy_tile_outside_the_gpu_heaps_gets_system_memory, a_parked_system_memory_tile_gives_way_to_a_gpu_heap.

The sparse tests make their device on the first adapter (D3D12CreateDevice(None, ..)), the RX 9070 XT here. The same tests also pass inside #3039 (report there).

Not tested: XCL_COHERENT_HEAPS=sparse in a title, a long session, Intel.

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

@thehollowedone

thehollowedone commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

merge-check
base: d1be8103644791b7a65f068954324e93d4b1b565 (nvidia-dev)
head: f8e75bca1ea903b1cf0e9d4f9387b73f359e5051
merge: clean trial merge into the current nvidia-dev tip; two intended files, +239/-10. I read the merged diff and traced the new L0 tile path through allocation, fallback, mapping, quarantine, cooling, and pool retirement.
build: cargo build --locked --workspace -> ok.
tests: cargo test --locked --workspace --no-fail-fast -- --test-threads=4 -> 1,827 passed, 8 failed, 48 ignored, 27 GPU SKIPPED notices. All three new #2987 tests passed. The eight failures are a subset of the nine seen on the untouched exact base: both texture-upload tests, the console-MS test, the async-compute PSO test, split-compute in two targets, and two-pass driver-cache in two targets. The base's mesh-cache failure did not recur here; no new suite failure appeared.
review: A refused L0 heap request repeats for every cold tile before fallback. take_sys_tile tries a new 64 MiB L0 heap after its free list is exhausted; on CreateHeap failure it falls back to a video-memory tile, then the next cold tile repeats the same request. In a test-only forced-failure fixture, mapping four cold tiles made four failed L0 attempts while the video pool supplied all four. The focused regression failed on the unchanged merged head (0/1; observed 4, expected 1). The local candidate below reuses any available L0 tile first, then delays another failed heap request for one second while falling back; it passed the regression (1/0), retried after the delay, and the final sparse test group passed (70/0, 1 ignored). The author has reported a real L0 allocation refusal on a 4 GB card. The candidate is uncommitted and has not had a full-suite or title run.
review: System-memory heap capacity remains at its process high-water mark. SYS_POOLS.heaps retains every 64 MiB L0 heap after its tiles cool; retire_free_pools and its later-submit scheduling only consider the video-memory pool. Tile reuse works, but a fully unused L0 heap cannot be returned. This is a source-derived lifetime finding, not a measurement of wasted commit in the author's title run. Keep stable, optional L0 heap slots owned by State; retire only heaps whose tiles have completed mapping/queue quarantine and cooling, while pinned aliases keep their heap alive. Include L0 cooling and retired heaps in the later-submit sweep so the last heap can leave after its last tile cools. A gated GPU regression should verify retention before fence completion, live alias readback, then release after all fences, cooling, and a later submit. The separate texture L0 pool in #3039 has an earlier verified reclaim regression, but its patch does not cover this sparse pool.
performance: the switch is off by default. With it on, repeated failed 64 MiB allocation calls and warnings add CPU time in the cold-tile path; L0 heaps that never retire keep host capacity after a streaming peak. I did not measure title frame time or process commit for this check.
verdict: not yet: bound failed L0 allocation retries and retire fully idle L0 sparse pools with the existing GPU-lifetime rules. The attached retry candidate resolves the first finding locally; the second needs its own focused regression and implementation.
hardware / tool and model: Windows 11 build 26300, Ryzen 7 9800X3D, RTX 3080 Ti (NVIDIA 621.35), rustc 1.99.1 MSVC, SDK DXC 1.8.2502.11. Codex (GPT-6.2 Sol) ran the trial merge, build, full suite, forced-failure regression and candidate sparse tests, reviewed the merged code, and wrote this check; Codex (GPT-6.2 Astra) independently traced the pool and fence lifetimes.

Not tested here: a new retail-title run, AMD, Intel, a full suite on the local candidate, or a production L0-heap retirement change.

Local retry candidate and isolated forced-failure regression
diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs
index 9a868283..80a9d2c9 100644
--- a/crates/xcl/src/hle/d3d12x/sparse.rs
+++ b/crates/xcl/src/hle/d3d12x/sparse.rs
@@ -572,6 +572,8 @@ struct State {
     retired: Vec<(ID3D12Heap, u64, std::time::Instant)>,
     /// when `retire_free_pools` last ran (`retire_due`)
     retire_tried: std::time::Instant,
+    /// Delay another L0 heap request after the driver refuses one; existing L0 tiles remain reusable.
+    sys_retry_after: Option<std::time::Instant>,
     /// tile address → pool tile + uncommitted page hole mask + per-page sent chunk hashes
     mapped: FxHashMap<usize, TileEntry>,
     /// pool tiles also used by placed buffers (not freed while they are)
@@ -1125,6 +1127,7 @@ unsafe fn new_state(dev: &ID3D12Device, windows: Vec<(usize, ID3D12Resource)>) -
         cooling: VecDeque::new(),
         retired: Vec::new(),
         retire_tried: std::time::Instant::now(),
+        sys_retry_after: None,
         mapped: FxHashMap::default(),
         pinned: FxHashMap::default(),
         parked: FxHashMap::default(),
@@ -1279,9 +1282,23 @@ impl State {
         self.drain_quarantined();
         let mut g = SYS_POOLS.lock().unwrap();
         let p = g.get_or_insert_with(SysPools::default);
-        if let Some(t) = reuse_tile(&mut p.free, &mut p.cooling, std::time::Instant::now()) {
+        let now = std::time::Instant::now();
+        if let Some(t) = reuse_tile(&mut p.free, &mut p.cooling, now) {
             return Some((t, true));
         }
+        if self.sys_retry_after.is_some_and(|at| now < at) {
+            drop(g);
+            return self.take_tile();
+        }
+        #[cfg(test)]
+        {
+            tests::SYS_HEAP_ATTEMPTS.with(|v| v.set(v.get() + 1));
+            if tests::REFUSE_SYS_HEAP.with(|v| v.get()) {
+                self.sys_retry_after = Some(now + std::time::Duration::from_secs(1));
+                drop(g);
+                return self.take_tile();
+            }
+        }
         let desc = D3D12_HEAP_DESC {
             SizeInBytes: POOL_TILES as u64 * TILE as u64,
             Properties: D3D12_HEAP_PROPERTIES {
@@ -1295,10 +1312,12 @@ impl State {
         };
         let mut heap: Option<ID3D12Heap> = None;
         if let Err(e) = super::title_textures::own_work(|| self.dev.CreateHeap(&desc, &mut heap)) {
+            self.sys_retry_after = Some(now + std::time::Duration::from_secs(1));
             crate::xlog_warn!("sparse windows: no system-memory pool heap ({e}) - video memory instead");
             drop(g);
             return self.take_tile();
         }
+        self.sys_retry_after = None;
         let heap = heap?;
         let _ = heap.SetName(windows::core::w!("xcl sparse system-memory pool"));
         p.heaps.push(heap);
@@ -4877,6 +4896,8 @@ mod tests {
         pub(super) static NO_TILES: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
         /// `sysmem_tiles` (`XCL_SPARSE_SYSMEM`) for the test on this thread (`Lazy::sysmem`)
         pub(super) static SYSMEM_FOR_TEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
+        pub(super) static REFUSE_SYS_HEAP: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
+        pub(super) static SYS_HEAP_ATTEMPTS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
     }
 
     /// The runs of the tiles mapped, made from all of them (but those over a CPU view: their
@@ -5141,6 +5162,7 @@ mod tests {
                 cooling: VecDeque::new(),
                 retired: Vec::new(),
                 retire_tried: std::time::Instant::now(),
+                sys_retry_after: None,
                 mapped: FxHashMap::default(),
                 pinned: FxHashMap::default(),
                 parked: FxHashMap::default(),
@@ -5472,6 +5494,7 @@ mod tests {
                 cooling: VecDeque::new(),
                 retired: Vec::new(),
                 retire_tried: std::time::Instant::now(),
+                sys_retry_after: None,
                 parked: FxHashMap::default(),
                 kept: FxHashMap::default(),
                 pending: Vec::new(),
@@ -5726,6 +5749,7 @@ mod tests {
                 cooling: VecDeque::new(),
                 retired: Vec::new(),
                 retire_tried: std::time::Instant::now(),
+                sys_retry_after: None,
                 mapped: FxHashMap::default(),
                 pinned: FxHashMap::default(),
                 parked: FxHashMap::default(),
@@ -5852,6 +5876,7 @@ mod tests {
                 cooling: VecDeque::new(),
                 retired: Vec::new(),
                 retire_tried: std::time::Instant::now(),
+                sys_retry_after: None,
                 mapped: FxHashMap::default(),
                 pinned: FxHashMap::default(),
                 parked: FxHashMap::default(),
@@ -6175,6 +6200,46 @@ mod tests {
         drop(lazy);
     }
 
+    #[test]
+    fn refused_system_heap_is_not_retried_for_every_cold_tile() {
+        const CHILD: &str = "XCL_TEST_SYS_HEAP_REFUSAL_CHILD";
+        if std::env::var_os(CHILD).is_none() {
+            unsafe {
+                let dev = test_device();
+                let mut o = D3D12_FEATURE_DATA_D3D12_OPTIONS::default();
+                if software(&dev)
+                    || dev.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &mut o as *mut _ as *mut c_void, std::mem::size_of_val(&o) as u32).is_err()
+                    || o.TiledResourcesTier.0 < D3D12_TILED_RESOURCES_TIER_2.0
+                {
+                    return crate::gpu::recomp::runner::skip_test("no GPU with tiled resources tier 2");
+                }
+            }
+            let output = std::process::Command::new(std::env::current_exe().unwrap())
+                .args(["--exact", "hle::d3d12x::sparse::tests::refused_system_heap_is_not_retried_for_every_cold_tile", "--nocapture"])
+                .env(CHILD, "1")
+                .output()
+                .unwrap();
+            assert!(output.status.success(), "{}\n{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr));
+            return;
+        }
+        let eager = Lazy::on(false);
+        eager.sysmem(true);
+        unsafe {
+            let Some((base, mut s, _)) = lazy_state(5) else { return crate::gpu::recomp::runner::skip_test("no GPU with tiled resources tier 2") };
+            REFUSE_SYS_HEAP.with(|v| v.set(true));
+            SYS_HEAP_ATTEMPTS.with(|v| v.set(0));
+            s.ensure_mapped(base, 4 * TILE, |_| 0);
+            REFUSE_SYS_HEAP.with(|v| v.set(false));
+            assert_eq!(s.mapped.len(), 4, "fallback maps every tile");
+            assert!(s.mapped.values().all(|e| e.pool.0 & SYS == 0), "fallback uses video memory");
+            assert_eq!(SYS_HEAP_ATTEMPTS.with(|v| v.get()), 1, "one failed L0 allocation should suppress repeats in the same burst");
+            s.sys_retry_after = Some(std::time::Instant::now() - std::time::Duration::from_millis(1));
+            s.ensure_mapped(base + 4 * TILE, TILE, |_| 0);
+            assert_eq!(SYS_HEAP_ATTEMPTS.with(|v| v.get()), 2, "the L0 request is retried after the delay");
+        }
+        drop(eager);
+    }
+
     /// A system-memory tile parked at an address that is a GPU heap of the title by its next commit
     /// gives way to a video-memory tile, mapped there before the old one goes (behind the fences),
     /// and the heap's bytes reach the GPU through the new one.

@throny

throny commented Nov 28, 2026

Copy link
Copy Markdown
Collaborator

merge-check claim
head: f8e75bc

@throny

throny commented Nov 28, 2026

Copy link
Copy Markdown
Collaborator

merge-check
base: d1be810 (nvidia-dev)
head: f8e75bc
merge: clean
build: cargo build --workspace -> ok
tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 1827 passed, 8 failed, 48 ignored (27 SKIPPED lines). The 8 failures are the base's own on this GPU, the same six names with and without the PR (#2771 and #2788 fix three of them). Base alone: 1824 passed, 8 failed, 48 ignored.
review: opt-in (XCL_SPARSE_SYSMEM=1); without it the behaviour is the base's: every new branch first checks the switch. The only default change is that GPU heaps are noted in a small table, once per heap. Open for the opt-in path, from the earlier check and still on this head: the system-memory pool heaps are never retired, and take_sys_tile retries CreateHeap for every cold tile after a refusal, without backoff; also the activity counter undercounts mapped bytes. For whoever merges: #3039 contains this PR's sparse.rs hunks (merge one, rebase the other), and #2898 changes reuse_tile's free-list type that this PR's pool passes, so the two break each other's build until one is rebased (system-memory tiles must not go into #2898's per-heap table). World-run note: this PR has been part of the local build this card used for 16 world runs yesterday (d1be810 plus a stack of open PRs, 5 to 30 minutes each, switches of this PR left at their defaults); nothing in those runs pointed at it.
performance: no default cost beyond one OnceLock read per tile (reasoned).
verdict: safe to merge (default path; the opt-in follow-ups above stay open)
hardware / tool and model: RTX 4080 16 GB (621.40), i9-12900K, Windows 11 26300, Rust 1.100.0, debug. Claude Code; merge, build and suite run by Claude Fable 5.2, diff review by Claude Opus 5.5 (every hunk read; nothing run on the GPU beyond the suite unless said).

@razormontana

Copy link
Copy Markdown
Contributor

Independent native validation of #2987 f8e75bca1ea903b1cf0e9d4f9387b73f359e5051 as included in the clean #3039 child 7cce7d3d4625ac8f90f146f1f89f25a613e32e76. The child only changes the placed-texture module. Windows 11 Pro build 22631, Core i7-10700K, RTX 3070 8 GB with NVIDIA 617.42, Rust 1.100.0 x64 MSVC.

Tested

A native cargo test --offline --locked -j 1 -p xcl --lib --no-run --message-format=json-render-diagnostics build passed. The test binary ran the_title_gpu_heaps_are_hot_and_nothing_around_them on CPU and a_lazy_tile_outside_the_gpu_heaps_gets_system_memory and a_parked_system_memory_tile_gives_way_to_a_gpu_heap on the RTX 3070, each by exact name with --exact --nocapture --test-threads=1. The sparse GPU fixtures verified system-memory backing, ordinary remapping to a hot heap, and byte-exact readback.

3 passed, 0 failed, 0 ignored, 0 explicit skips.

Not tested

A detached #2987-only build, load-time VRAM savings, or sustained retail use.

AI use

Codex GPT-6.2 ran the focused validation, checked the results, and prepared this report.

@akimfomin

Copy link
Copy Markdown

AnyPS5 #27991 tests keeping sparse read-only address uploads current across backing changes. An XCL-specific check could move one tile from local to system backing while leaving a neighboring tile on the original heap, then compare both bytes and bytes re-uploaded. It separates always re-reading everything from refreshing only the mapping that actually changed. Existing capacity and pressure results are independent of this control.

@andrewDoing

Copy link
Copy Markdown

I checked the implemented system-to-local transition on RTX 5070 / NVIDIA 616.92 at head f8e75bca1ea903b1cf0e9d4f9387b73f359e5051. This is the reverse of the local-to-system direction requested above; it is a complementary control, not a substitute for that scenario.

A test-only native fixture initialized two adjacent 64 KiB tiles, promoted and rewrote only the first from parked system backing to local VRAM, and read both back. All 65,536 bytes of the promoted tile matched the new value; the neighbor retained its original pool mapping and all 65,536 original bytes. Instrumented upload selection recorded one 65,536-byte dirty upload and no clears for that submit. A subsequent clean submit recorded zero upload bytes and both tiles remained correct. The focused test passed with no skips.

The fixture supplies the dirty-page list directly. It checks upload selection and GPU contents for this transition, not Windows dirty-page discovery, the reverse transition, or retail bandwidth/performance.

AI use: OpenAI Codex with GPT-6.2 Astra built and ran the fixture; Codex reviewed and prepared this report.

@Prime1997

Copy link
Copy Markdown
Collaborator

Conflict in Sparse.rs needs to be fixed.

-Prime

@Aniseto

Aniseto commented Nov 28, 2026

Copy link
Copy Markdown

Ran the sparse-tile placement tests at f8e75bca 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 -- hle::d3d12x::sparse --test-threads=1
69 passed; 0 failed; 1 ignored; 0 measured; 1660 filtered out      (exit 0)

All 69 tests pass with one ignored, including a_lazy_tile_outside_the_gpu_heaps_gets_system_memory and a_parked_system_memory_tile_gives_way_to_a_gpu_heap. They are CPU-side placement tests under cfg(test); no system-memory tile was actually allocated on this adapter. The thread has a report on an RTX 5070 (driver 616.92) for the reverse transition; this adds a desktop RTX 5070 Ti with driver 32.0.16.2124.

Not tested: real system-memory tile placement in a title, a paired smoke run, the full workspace suite and its 11 known failures, 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.

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.