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

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.
  • New test the_title_gpu_heaps_are_hot_and_nothing_around_them.

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 6c5904f9: 1822 passed, 11 failed, 48 ignored.
  • cargo test -p xcl --lib the_title_gpu_heaps_are_hot: 1 passed.
  • Retail title, this PR's head, release build, 610 s, 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: 6c5904f9426ffdfd4772399c92bfa84ddf29f6e2
gpu: NVIDIA GeForce RTX 3080
title: 4ba6c38e
seconds: 60
exit: 0x0
frames shown: 1535 (PresentX 1535)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 17388 MB

Not tested

AI use

  • Claude Code with Claude Opus 5.5. It measured the placement, wrote the code, the test and this description, and ran the tests and title runs. The author reviewed the diff.

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 <noreply@anthropic.com>
@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

Correction to the candidate diff below: Further review found that an adapter may reject an L0 heap and validly use a video-memory tile for a cold reservation. The current candidate would retire that parked fallback tile on recommit, so please do not apply the diff as-is. The proposed tests also need a feature guard that works under strict GPU modes and a race-free release assertion. The reported RTX 3080 Ti red/green observations remain valid for the stated focused runs. I am revising the candidate and will update this comment after verification.

Follow-up on PR head 6c5904f9. I checked the system-memory pool path on an RTX 3080 Ti and found two address-lifetime cases that change where a tile is placed.

  • A new eager-path GPU test with XCL_SPARSE_SYSMEM=1 confirmed that a cold tile used an L0 heap and that all 65,536 uploaded bytes were read back through its reserved GPU window: 1 passed, 0 failed, 0 ignored, no skip.
  • A hot sparse allocation remains in HOT after sparse::free or kernelx::VirtualFree(MEM_RELEASE). Because UMA may return that address to a cold reservation, the stale entry can send its tiles to video memory. The release regression failed on the unchanged head (0/1/0) and passed with the candidate (1/0/0). The candidate removes the marker before the address returns to UMA, including the allocation-failure rollback.
  • A cold L0 tile parked at an address is reused unchanged if that address becomes hot; the reverse transition can also keep a video tile for a cold owner. The transition regression failed on the unchanged head (0/1/0) and passed with the candidate (1/0/0) in both directions. The candidate unmaps and quarantines only the mismatched parked tile, then selects the new owner's pool class. Pinned tiles retain their existing alias.

The HOT lookup is on the per-tile path. The candidate uses the nonoverlapping UMA reservation starts in a BTreeMap, giving logarithmic lookup and removal instead of scanning an ever-growing vector. The earlier lazy first-write finding still needs its own allocator-path fix.

Environment and commands: Windows 11 build 26300; RTX 3080 Ti, driver 621.35; Ryzen 7 9800X3D; rustc 1.99.1 MSVC. With XCL_SPARSE_SYSMEM=1 and XCL_REQUIRE_GPU=1, I ran cargo test --offline --locked -j 4 -p xcl --lib <test name> -- --nocapture --test-threads=1 separately for the four new tests. All four passed on the candidate (1/0/0 each, no skips). The two existing tests the_title_gpu_heaps_are_hot_and_nothing_around_them and a_lazy_tile_gets_memory_at_its_first_bytes_and_keeps_them also passed (1/0/0 each). The full workspace suite, paired title smoke, failed-commit rollback, and a live pinned-resource class change were not tested on this local candidate.

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..ff43f40f 100644
--- a/crates/xcl/src/hle/d3d12x/sparse.rs
+++ b/crates/xcl/src/hle/d3d12x/sparse.rs
@@ -388,12 +388,21 @@ 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);
+    }
 }
 
 fn sysmem_tiles() -> bool {
@@ -408,7 +417,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.
@@ -1658,6 +1667,11 @@ 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() {
+                if self.parked.get(&t).is_some_and(|tile| (tile.0 & SYS != 0) != (sysmem_tiles() && !is_hot(t))) {
+                    // A new owner can require the other pool class at the same address.
+                    // Unmap only this parked tile; the other parked mappings stay cached.
+                    self.retire_parked_at(t);
+                }
                 // 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)));
@@ -2528,6 +2542,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 +2576,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()
 }
 
@@ -3206,6 +3224,22 @@ impl State {
         self.quarantine_tiles(tiles);
         true
     }
+
+    /// Retire one parked mapping whose address now needs a different memory pool.
+    unsafe fn retire_parked_at(&mut self, t: usize) {
+        let Some(tile) = self.parked.remove(&t) else { return };
+        if self.pinned.contains_key(&tile) {
+            self.kept.insert(t, tile);
+            return;
+        }
+        if let Some(wi) = self.window_index(t) {
+            let (base, resource) = (self.windows[wi].0, self.windows[wi].1.clone());
+            TILE_WORK[2].fetch_add(1, Ordering::Relaxed);
+            self.unmap_tiles(&resource, base, &[t]);
+            self.signal();
+        }
+        self.quarantine_tiles(vec![tile]);
+    }
 }
 
 /// Window tiles asked for by `map_mirror`: each is queued once, until it is forgotten
@@ -5506,6 +5540,43 @@ 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 {
+            let (p, _) = alloc_as(TILE, TILE, true).expect("hot sparse allocation");
+            assert!(is_hot(p));
+            assert!(free(p));
+            assert!(!is_hot(p), "a released address must not retain its old hot class");
+            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 {
+            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!(!is_hot(p), "kernelx MEM_RELEASE must clear the old hot class");
+        }
+    }
+
     #[test]
     fn aligned_tile_addresses_spread_across_hash_buckets() {
         use std::hash::BuildHasher;
@@ -6075,6 +6146,49 @@ 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);
+        if !sysmem_tiles() {
+            return crate::gpu::recomp::runner::skip_test("XCL_SPARSE_SYSMEM=1 required");
+        }
+        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.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");
+        }
+    }
+
+    #[test]
+    fn a_parked_cold_tile_is_replaced_when_the_address_becomes_hot() {
+        if !sysmem_tiles() {
+            return crate::gpu::recomp::runner::skip_test("XCL_SPARSE_SYSMEM=1 required");
+        }
+        unsafe {
+            let (base, mut s) = test_state_with_reserved(1);
+            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");
+        }
+    }
+
     /// 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) traced the paths, wrote the candidate and ran the tests; Codex (GPT-6.2 Astra) reviewed the low-level placement and lifetime paths.

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.

6 participants