Skip to content

D3D12.X: read the title's sparse windows directly instead of copying them - #2090

Open
brandostrong wants to merge 4 commits into
xcl-dev:mainfrom
brandostrong:gpu-direct-main
Open

brandostrong wants to merge 4 commits into
xcl-dev:mainfrom
brandostrong:gpu-direct-main

Conversation

@brandostrong

Copy link
Copy Markdown
Contributor

The title's GPU-read memory lives in XCL's sparse unified-memory windows, which today are tiled
video-memory resources with a CPU mirror: before each submit XCL sweeps the mapped range with
GetWriteWatch and uploads what changed. For a title that commits most of unified memory that sweep
is the dominant cost at world load – measured 24 667 ms of look for 1 254 ms of upload at
3 578 820 dirty pages
, growing 1 046 → 2 892 → 6 880 → 24 667 ms as the title commits more
(#582, at world-load scale).

This makes each sparse window one whole-committed allocation the GPU reads directly: sparse.rs
imports it (OpenExistingHeapFromAddress) and places one buffer over it, so a buffer the title
places there is that memory – identity GPU address, no tiles, no upload, no readback, no State.
The window stride stays 4 GiB, so window index math and the shader window VAs are untouched; the
1 MiB left at a window's end is not address space, so each window gets its own free range and its own
watch region. Opt-in: XCL_SPARSE_DIRECT=1.

Part of #1773 (title memory mirrored into VRAM) and #582. #1034 and #1058 shrink the same look from
the other side; #1326 / #258 want the copy path for a different platform. Gets the title past world
load into the mission on the roadmap #1833.

What is in it

  • crates/xcl/src/gpu/uma.rs: XCL_SPARSE_DIRECT=1 reserves and commits each sparse window in one
    call at MAX_SIZE; window() and watch_regions() follow the layout through a sparse_len
    field, and a layout the host cannot commit falls back to the tiled reservation. Test for the layout.
  • crates/xcl/src/hle/d3d12x/sparse.rs: init imports each window and places one buffer over it,
    place_buffer places on that heap at the same address, and committed / decommitted / free
    skip the tile and State work. If a window will not import, the windows are tiled as before.
  • crates/xcl/src/gpu/recomp/tests.rs: a GPU test for what the driver accepts there – a placed
    buffer on an imported heap must carry ALLOW_CROSS_ADAPTER, its offset must be 64 KiB-aligned,
    overlapping placements are accepted, and its GPU address is the heap base plus the offset.
  • crates/xcl/src/hle/d3d12x/sparse.rs: note_watch reports the look's cost – the line that showed
    it came from before_execute, which this layout never reaches.
  • README.md: the new switch.

Tested

  • RTX 4090 (driver 32.0.16.1664), i9-13900K, Windows 11 26200, rustc 1.100.0, debug
  • cargo build --workspace, then cargo test --workspace -- --test-threads=4: 1156 passed,
    0 failed, 46 ignored
    ; 24 SKIPPED lines – all wave64-only GPU tests (this adapter reports
    32-lane waves) and the f16 VOP3-modifier refusals
  • the two new tests ran and passed on this adapter
  • the switch on, retail title, 180 s, warm caches: the write-watch look goes from 24 667 ms
    cumulative to ~1 ms a look (4 461 ms over 4 096 looks), the sparse video-memory pools from
    7 445 MB to 0, GPU queue.Wait timeouts from 34–69 a run to 8, no device removal,
    UMA import check: ok

Regression run

xcl-smoke v1
commit: cbc296ab65a2661a61e3e2da109134bcd5319f60
gpu: NVIDIA GeForce RTX 4090
title: 3c290c16
seconds: 180
exit: 0x0
frames shown: 1901 (PresentX 1901)
presents per 2 s (last 3): 0 0 0
device removals: 0
crashes: 0
peak commit: 33336 MB
xcl-smoke v1
commit: 5e71371dffbdc8b9f58aa8b58493803e522ed070
gpu: NVIDIA GeForce RTX 4090
title: 3c290c16
seconds: 180
exit: 0x0
frames shown: 1959 (PresentX 1959)
presents per 2 s (last 3): 0 0 0
device removals: 0
crashes: 0
peak commit: 32610 MB

Both runs: the same title, the same 180 s, a fresh copy of the same warm profile for each, and the
same driving – pad A at 30 s and pad X at 70 s injected into the XCL window, process killed when the
run ends. XCL_SPARSE_DIRECT is off in both (the default), so these blocks show that the default
path is unchanged; the switch-on numbers are the ones under Tested, from separate runs.

Not tested

  • AMD and Intel adapters, and wave64-only GPUs
  • the switch on at the maintainer's run: it charges 3 × 4095 MB at start, so a host without that
    commit headroom falls back to the tiled layout (that fallback is unit-tested, not run on a title)
  • textures the title places in sparse windows are still detiled PC copies, so they keep the watch and
    the mirror: this removes the buffer mirror and the look over mapped tiles, not the texture copy
  • 8- and 16-window layouts with the switch on

AI use

  • Claude Code, Claude Opus 5.5: wrote the code, the tests and this description. The suite counts and
    both xcl-smoke blocks are from runs made here, on the hardware named.

🤖 Generated with Claude Code

brandostrong and others added 4 commits November 24, 2026 19:07
XCL_SPARSE_DIRECT=1 reserves and commits each sparse window in one call at
MAX_SIZE bytes, the shape `OpenExistingHeapFromAddress` accepts, so
`sparse.rs` can import it and the GPU can read the title's pages at their own
addresses. The 4 GiB window stride stays, so window index math and the shader
window VAs are untouched; the MiB at a window's end is not address space, so
each window gets its own free range and its own watch region. The watch stays:
a texture placed in a sparse window is still a detiled copy, and only the
watch says its pages were rewritten.

Co-Authored-By: Claude Code <noreply@anthropic.com>
With the direct layout `sparse.rs::init` imports each window
(`OpenExistingHeapFromAddress`) and places one buffer over it, so a buffer the
title places there is that memory: no tiles, no upload, no readback, no
`State`, and the GPU virtual address is the window's plus the offset.

Measured on a retail title (RTX 4090, `XCL_PSO_WAIT_MS=50`): the write-watch
look over the mapped tiles is the dominant cost at world load – 24 667 ms of
look for 1 254 ms of upload at 3 578 820 dirty pages, growing 1 046 → 2 892 →
6 880 → 24 667 ms as the title commits more (issue xcl-dev#582, at world-load scale).
With no tiles mapped the look has only the texture sources left to walk.

What the driver needs, pinned by the new GPU test: a buffer placed on an
imported heap must carry `ALLOW_CROSS_ADAPTER` like the coherent window's do,
its offset must be 64 KiB-aligned, and overlapping placements are accepted (the
title aliases). A whole-committed write-watched 4095 MB allocation does import.
If a window will not import, `init` tiles the windows as before.

Co-Authored-By: Claude Code <noreply@anthropic.com>
The cost of the look was only ever printed by `before_execute`, which the
direct layout never reaches, so the number that shows what the change buys
disappeared with it. `note_watch` runs on every look in both layouts.

Co-Authored-By: Claude Code <noreply@anthropic.com>
The switch changes what a user gets for a title that reads its own GPU memory,
so it belongs with the other XCL_* knobs.

Co-Authored-By: Claude Code <noreply@anthropic.com>
@brandostrong

Copy link
Copy Markdown
Contributor Author

PR #2090 removes the buffer half of this for a title that commits most of its unified memory.

Measured on the same title, 180 s runs, RTX 4090, warm caches:

  • tiled (main): the sparse windows' own video-memory pools reach 7 445 MB on top of the title's
    pages, and the write-watch look over the mapped tiles costs 24 667 ms cumulative for 1 254 ms of
    upload at 3 578 820 dirty pages.
  • with XCL_SPARSE_DIRECT=1 (D3D12.X: read the title's sparse windows directly instead of copying them #2090): those pools are 0 MB and the look is 4 461 ms over
    4 096 looks
    (~1 ms each) — the windows are imported heaps, a buffer the title places in one is
    that memory at its own address, so there is nothing to scan, upload or read back.

What still mirrors after that: textures the title places in sparse windows (a detiled PC copy — that
is why the windows stay write-watched), and anything XCL copies into its own video memory.

Claude Code, Claude Opus 5.5 — the numbers are from runs made here.

@WebIdentity1

WebIdentity1 commented Nov 25, 2026 •

Copy link
Copy Markdown

A second confirmed issue at 5e71371dffbdc8b9f58aa8b58493803e522ed070: title-facing kernelx::VirtualFree attempts native MEM_DECOMMIT even with direct imported windows active. On this machine Windows rejects it with error 87. Both title decommit and release return 0; the logical reservation stays allocated and its old bytes remain. The observed result is failed frees, not decommitted backing or a GPU fault.

The attached candidate applies the direct path's existing zero-for-reuse policy to this entry point. A small sparse::decommit_direct helper handles page-rounded zeroing only when DIRECT_ON is active; otherwise VirtualFree follows its existing tiled path. Existing release validation, reservation removal and mirror bookkeeping remain in place. This candidate is independent of the earlier heap.as_raw() ownership fix; the pair was not tested together.

Tested

  • Native Windows 10 Home 19045, Ryzen 7 7800X3D, RTX 3090 driver 591.74 / 32.0.15.9174, Rust/Cargo 1.98.1 MSVC, debug. Actual selected NVIDIA GeForce RTX 3090 adapter printed.
  • Same test-only fixture on the author head and the candidate. Three actual imported windows remain alive while calling the real title API. No mock COM objects or driver.
  • Full 64 KiB decommit, one-byte decommit at address+17, and whole-reservation release: baseline 0 passed / 1 failed / 0 ignored, exit 101; all three calls return 0/error 87, host pages remain committed, reservations retained, data unchanged.
  • Candidate: 1 passed / 0 failed / 0 ignored, exit 0. All three calls return 1; backing stays MEM_COMMIT. Decommit retains the reservation; release removes it. Full decommit/release zero the bytes. The one-byte request zeroes exactly the touched 4 KiB page and preserves the adjacent 60 KiB sentinel data. This follows the VirtualFree page-rounding contract.
  • Existing virtual_free_ex_and_sparse_validation, in a separate process with direct mode off: 1/0/0 on both snapshots, exit 0. Thus the four focused harness results total baseline 1/1/0 → candidate 2/0/0, with zero SKIPPED notices.
  • All 322 source hashes match before/after and archived snapshots; the candidate matches the local worktree. Both recompiled.
$env:XCL_ADAPTER='3090'
$env:XCL_SPARSE_DIRECT='1'
$env:XCL_LATE_RELEASE='0'
$env:XCL_UMA_MB='16'
$env:XCL_COHERENT_MB='16'
$env:XCL_UMA_WINDOWS='4'
cargo test --locked -p xcl --lib -- title_virtual_free_preserves_direct_heap_pages --test-threads=1 --nocapture
$env:XCL_SPARSE_DIRECT='0'
cargo test --locked -p xcl --lib -- virtual_free_ex_and_sparse_validation --test-threads=1 --nocapture

Isolated processes, approximately 12 GiB commit for each direct run. Successful calls' last-error values were not interpreted as errors; only return 0 makes that value meaningful. The fixture checks CPU memory and logical allocation state, then releases its imported resources. An earlier full-page-only diagnostic produced the same failure and was preserved separately.

Not tested: GPU dispatch/coherence or device-removal behavior, title physical-page remapping APIs (give_back_homes / release_at), arbitrary protection changes, AMD/Intel, full workspace suite, retail smoke, performance or peak memory. This fixes the tested VirtualFree entry point, not a claim that every direct-window lifetime path has been qualified. The opt-in fixture explicitly skips unless direct mode is requested.

AI use: Codex (GPT-6) identified the call-path gap, wrote the candidate and reproducer, ran native verification and prepared this report.

VirtualFree candidate and identical opt-in regression
diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs
index 4bfef5e..f63151e 100644
--- a/crates/xcl/src/hle/d3d12x/sparse.rs
+++ b/crates/xcl/src/hle/d3d12x/sparse.rs
@@ -420,6 +420,17 @@ fn direct() -> bool {
     DIRECT_ON.load(Ordering::Relaxed)
 }
 
+/// Direct windows must keep their imported backing committed. Apply a title
+/// decommit by zeroing its pages instead; false leaves the tiled path to the caller.
+pub unsafe fn decommit_direct(a: usize, n: usize) -> bool {
+    if !direct() { return false; }
+    if n != 0 {
+        let (start, end) = page_span(a, n);
+        std::ptr::write_bytes(start as *mut u8, 0, end - start);
+    }
+    true
+}
+
 /// (bytes of video memory in pool heaps, of those mapped) – `XCL_ACTIVITY`
 pub fn pool_bytes() -> (usize, usize) {
     let g = lock_state();
@@ -1749,6 +1760,74 @@ fn forget_in(s: &mut State, res: usize) {
 mod tests {
     use super::*;
 
+    /// A title free must not remove the CPU pages still backing a live imported heap.
+    #[test]
+    fn title_virtual_free_preserves_direct_heap_pages() {
+        use windows::Win32::Graphics::{Direct3D::D3D_FEATURE_LEVEL_12_0, Dxgi::*};
+        use windows_sys::Win32::System::Memory::{MEMORY_BASIC_INFORMATION, MEM_COMMIT, MEM_RELEASE, MEM_DECOMMIT};
+        if !crate::gpu::uma::sparse_direct_wanted() {
+            crate::gpu::recomp::runner::skip_test("set XCL_SPARSE_DIRECT=1 for isolated title-free check");
+            return;
+        }
+        unsafe {
+            let factory: IDXGIFactory4 = CreateDXGIFactory1().unwrap();
+            let wanted = std::env::var("XCL_ADAPTER").unwrap_or_default();
+            let mut chosen = None;
+            for i in 0.. {
+                let Ok(adapter) = factory.EnumAdapters1(i) else { break };
+                let desc = adapter.GetDesc1().unwrap();
+                let end = desc.Description.iter().position(|&c| c == 0).unwrap_or(desc.Description.len());
+                let name = String::from_utf16_lossy(&desc.Description[..end]);
+                if !wanted.is_empty() && !name.contains(&wanted) { continue; }
+                let mut dev: Option<ID3D12Device> = None;
+                if D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut dev).is_ok() {
+                    chosen = Some((name, dev.unwrap()));
+                    break;
+                }
+            }
+            let Some((name, dev)) = chosen else {
+                crate::gpu::recomp::runner::skip_test("no selected D3D12 adapter");
+                return;
+            };
+            let u = crate::gpu::uma::get().expect("UMA allocation");
+            assert!(u.sparse_direct(), "host must provide direct window commit headroom");
+            let windows = direct_windows(&dev, u);
+            assert!(!windows.is_empty(), "driver must import the direct windows");
+            let keep: Vec<_> = windows.iter().map(|&(_, p, _)| ID3D12Resource::from_raw(p as *mut c_void)).collect();
+            let mut observations = Vec::new();
+            for mode in [0, 1, 2] {
+                let release = mode == 2;
+                let (addr, len) = alloc(TILE, TILE).expect("sparse allocation");
+                std::ptr::write_bytes(addr as *mut u8, 0x5a, len);
+                let kind = if release { MEM_RELEASE } else { MEM_DECOMMIT };
+                let at = if mode == 1 { addr + 17 } else { addr };
+                let size = if release { 0 } else if mode == 1 { 1 } else { len };
+                let ok = crate::hle::kernelx::VirtualFree(at as *mut c_void, size, kind);
+                let error = windows_sys::Win32::Foundation::GetLastError();
+                let mut info: MEMORY_BASIC_INFORMATION = std::mem::zeroed();
+                assert_ne!(VirtualQuery(addr as *const c_void, &mut info, std::mem::size_of_val(&info)), 0);
+                let still_reserved = u.sparse_reservation(addr).is_some();
+                let preserved = info.State == MEM_COMMIT;
+                // Only inspect bytes while committed; restore failed-control pages before cleanup.
+                let zero = preserved && std::slice::from_raw_parts(addr as *const u8, len).iter().enumerate().all(|(i, &v)| v == if mode == 1 && i >= PAGE { 0x5a } else { 0 });
+                observations.push((mode, release, ok, error, info.State, still_reserved, zero));
+                if !preserved { assert!(!VirtualAlloc(addr as *const c_void, len, MEM_COMMIT, PAGE_READWRITE).is_null()); }
+                if still_reserved { assert!(free(addr)); }
+            }
+            println!("DIRECT_FREE adapter={name} observations={observations:?}");
+            drop(keep);
+            DIRECT.lock().unwrap().clear();
+            DIRECT_ON.store(false, Ordering::Relaxed);
+            for (mode, release, ok, _, state, reserved, zero) in observations {
+                assert_eq!(ok, 1, "title free success");
+                assert_eq!(state, MEM_COMMIT, "live imported heap backing must remain committed, release={release}");
+                assert_eq!(reserved, !release, "logical reservation lifetime");
+                assert!(zero, "page-rounded zeroing must preserve adjacent pages, mode={mode}");
+            }
+        }
+    }
+
+
     /// `queue()` answers while the state's lock is held: a resource's last `Release` asks for
     /// it (`late_release::drain_known`) from inside a D3D12 call that the lock's holder can be
     /// waiting for (a list's `Reset` against an upload's allocator `Reset`, with `XCL_DRED=1`).
diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs
index afa86c3..cdbbe17 100644
--- a/crates/xcl/src/hle/kernelx.rs
+++ b/crates/xcl/src/hle/kernelx.rs
@@ -436,7 +436,7 @@ pub unsafe extern "system" fn VirtualFree(addr: *mut c_void, size: usize, t: u32
                 }
             }
         };
-        if n > 0 {
+        if n > 0 && !crate::hle::d3d12x::sparse::decommit_direct(a, n) {
             // sparse first: under its lock, so no copy of CPU writes to video memory reads the
             // pages while they go (the submit thread's copy faulted on them)
             crate::hle::d3d12x::sparse::decommitted(a, n);
Earlier independently verified heap-reference fix and test

Confirmed a heap-reference leak in the direct place_buffer path at 5e71371dffbdc8b9f58aa8b58493803e522ed070. DIRECT supplies a cloned ID3D12Heap, but heap.into_raw() transfers ownership into dev_create_placed_resource, whose creator wrapper only borrows the heap argument. Neither a successful placement nor a driver-rejected placement releases that transferred reference.

The minimal fix in crates/xcl/src/hle/d3d12x/sparse.rs is to pass heap.as_raw() instead. The local clone then drops after the borrowing call.

Tested

  • Native Windows 10 Home 19045, Ryzen 7 7800X3D, RTX 3090 driver 591.74 / 32.0.15.9174, Rust/Cargo 1.98.1 MSVC, debug. The fixture selects and prints the actual NVIDIA GeForce RTX 3090 adapter.
  • Same test on the author head and with only the one-line ownership correction. It imports the three direct windows, calls the real sparse::place_buffer/creation wrapper, creates and releases four valid buffers, then makes four driver-rejected requests with an invalid buffer format. No mock driver or COM objects.
  • Baseline: 0 passed / 1 failed / 0 ignored, zero skips, exit 101. Initial heap reference count 3; counts after each call: 4,5,6,7,8,9,10,11.
  • Candidate: 1 passed / 0 failed / 0 ignored, zero skips, exit 0. Initial count 3; 3 after every call.
  • Both snapshots recompiled. All 322 source hashes matched before/after; candidate also matches the local worktree. Only sparse.rs differs between snapshots.
$env:XCL_ADAPTER='3090'
$env:XCL_SPARSE_DIRECT='1'
$env:XCL_LATE_RELEASE='0'
$env:XCL_UMA_MB='16'
$env:XCL_COHERENT_MB='16'
$env:XCL_UMA_WINDOWS='4'
cargo test --locked -p xcl --lib -- direct_placements_release_the_temporary_heap_reference --test-threads=1 --nocapture

Run in an isolated process; the three direct windows require approximately 12 GiB of commit. Deferred resource release is disabled solely for this ownership fixture because no GPU work is submitted. The test balances its diagnostic IUnknown::AddRef/Release calls and releases each valid placed resource before reading the heap count.

Not tested: GPU dispatch/output, peak memory or retained-byte savings, performance, retail smoke, AMD/Intel, full workspace suite. The observed reference leak is not a measurement of per-placement memory growth. The attached opt-in fixture returns an explicit skip without XCL_SPARSE_DIRECT=1 and requires XCL_LATE_RELEASE=0; it is not a new default-suite GPU-coverage claim.

AI use: Codex (GPT-6) identified the ownership issue, wrote the one-line candidate and regression, ran native verification and prepared this report.

One-line fix and identical opt-in regression
diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs
index 4bfef5e..61e8696 100644
--- a/crates/xcl/src/hle/d3d12x/sparse.rs
+++ b/crates/xcl/src/hle/d3d12x/sparse.rs
@@ -1664,7 +1664,7 @@ pub unsafe fn place_buffer(this: *mut c_void, va: usize, desc: &D3D12_RESOURCE_D
         if state & (D3D12_RESOURCE_STATE_UNORDERED_ACCESS.0 as u32 | D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE.0 as u32) != 0 {
             d.Flags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
         }
-        let hr = super::real::dev_create_placed_resource(this, heap.into_raw() as usize, start - base, &d as *const _ as usize, state as usize, 0, riid, ppv);
+        let hr = super::real::dev_create_placed_resource(this, heap.as_raw() as usize, start - base, &d as *const _ as usize, state as usize, 0, riid, ppv);
         return (hr >= 0 && !ppv.is_null() && !(*ppv).is_null()).then(|| (hr, delta));
     }
     let mut g = lock_state();
@@ -1749,6 +1749,83 @@ fn forget_in(s: &mut State, res: usize) {
 mod tests {
     use super::*;
 
+    /// The direct path borrows the imported heap while creating each buffer;
+    /// neither a successful nor a rejected placement transfers our heap owner.
+    #[test]
+    fn direct_placements_release_the_temporary_heap_reference() {
+        use windows::Win32::Graphics::{Direct3D::D3D_FEATURE_LEVEL_12_0, Dxgi::*};
+        if !crate::gpu::uma::sparse_direct_wanted() {
+            crate::gpu::recomp::runner::skip_test("set XCL_SPARSE_DIRECT=1 for isolated direct-placement ownership check");
+            return;
+        }
+        assert!(!super::super::late_release::enabled(), "run with XCL_LATE_RELEASE=0; no GPU work is submitted");
+        unsafe {
+            let factory: IDXGIFactory4 = CreateDXGIFactory1().unwrap();
+            let wanted = std::env::var("XCL_ADAPTER").unwrap_or_default();
+            let mut chosen = None;
+            for i in 0.. {
+                let Ok(adapter) = factory.EnumAdapters1(i) else { break };
+                let desc = adapter.GetDesc1().unwrap();
+                let end = desc.Description.iter().position(|&c| c == 0).unwrap_or(desc.Description.len());
+                let name = String::from_utf16_lossy(&desc.Description[..end]);
+                if !wanted.is_empty() && !name.contains(&wanted) { continue; }
+                let mut dev: Option<ID3D12Device> = None;
+                if D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut dev).is_ok() {
+                    chosen = Some((name, dev.unwrap()));
+                    break;
+                }
+            }
+            let Some((name, dev)) = chosen else {
+                crate::gpu::recomp::runner::skip_test("no selected D3D12 adapter");
+                return;
+            };
+            let u = crate::gpu::uma::get().expect("UMA allocation");
+            assert!(u.sparse_direct(), "host must provide direct window commit headroom");
+            let windows = direct_windows(&dev, u);
+            assert!(!windows.is_empty(), "driver must import the direct windows");
+            let keep: Vec<_> = windows.iter().map(|&(_, p, _)| ID3D12Resource::from_raw(p as *mut c_void)).collect();
+            super::super::real::adopt(dev.as_raw(), super::super::real::Kind::Device);
+            let (addr, len) = alloc(TILE, TILE).expect("sparse block");
+            let heap = DIRECT.lock().unwrap().iter().find(|&&(b, _)| b == u.window(u.window_of(addr).unwrap()).0).unwrap().1.clone();
+            let unknown = heap.cast::<windows::core::IUnknown>().unwrap();
+            let refs = || {
+                let vt = Interface::vtable(&unknown);
+                (vt.AddRef)(unknown.as_raw());
+                (vt.Release)(unknown.as_raw())
+            };
+            let before = refs();
+            let mut observed = Vec::new();
+            for reject in [false, true] {
+                for _ in 0..4 {
+                    let mut desc = buffer_desc(TILE as u64);
+                    if reject { desc.Format = windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32_UINT; }
+                    let mut raw = std::ptr::null_mut();
+                    let iid = &ID3D12Resource::IID as *const _ as *const windows_sys::core::GUID;
+                    let result = place_buffer(dev.as_raw(), addr, &desc, D3D12_RESOURCE_STATE_COMMON.0 as u32, iid, &mut raw);
+                    if reject {
+                        assert!(result.is_none() && raw.is_null(), "invalid buffer format must be rejected");
+                    } else {
+                        assert!(result.is_some() && !raw.is_null(), "valid placement");
+                        let resource = ID3D12Resource::from_raw(raw);
+                        assert_eq!(resource.GetDesc().Width, TILE as u64);
+                        drop(resource);
+                    }
+                    observed.push((reject, refs()));
+                }
+            }
+            println!("DIRECT_HEAP adapter={name} initial_refs={before} after_each={observed:?}");
+            assert!(free(addr));
+            assert_eq!(len, TILE);
+            drop(unknown);
+            drop(heap);
+            drop(keep);
+            DIRECT.lock().unwrap().clear();
+            DIRECT_ON.store(false, Ordering::Relaxed);
+            assert!(observed.iter().all(|&(_, n)| n == before), "temporary heap references leaked: {observed:?}");
+        }
+    }
+
+
     /// `queue()` answers while the state's lock is held: a resource's last `Release` asks for
     /// it (`late_release::drain_known`) from inside a D3D12 call that the lock's holder can be
     /// waiting for (a list's `Reset` against an upload's allocator `Reset`, with `XCL_DRED=1`).

@brandostrong

Copy link
Copy Markdown
Contributor Author

Matched head-to-head on the same title: same 180 s, a fresh copy of the same warm profile, the same
driving (pad A at 30 s, pad X at 70 s), RTX 4090, warm DXIL cache.

main cbc296a this PR, switch off this PR, XCL_SPARSE_DIRECT=1
frames shown 1901 1959 1568
write-watch look 7 096 ms cumulative at t = 41 s 7 070 ms none
sparse video-memory pools 7 445 MB 7 445 MB 0
driver compiles 47 79 103
peak commit 33 336 MB 32 610 MB 43 196 MB
presents per 2 s 60 up to t ≈ 70 s, 0 from t ≈ 100 s the same 60 up to t ≈ 54 s, 0 from t ≈ 84 s

The look and the buffer mirror really are gone and the default path is unchanged. The frame count with
the switch on is lower in this window: with nothing to copy the title reaches its compute-heavy part
sooner and blocks there (103 compiles, one 421 KB compute PSO at 14 887 ms). The copy was one wall of
several; this removes it and shows the next one, which is #1442 / #1809 / #2085 territory. Peak commit
with the switch on is 129 % of main's, which is why the switch is opt-in here.

Claude Code, Claude Opus 5.5 — all three runs were made here.

@milesah3ad

Copy link
Copy Markdown

A likely reason for the frame drop in @brandostrong's head-to-head above (1,959 → 1,568 frames and presents stopping ~16 s earlier with XCL_SPARSE_DIRECT=1, although the look is gone): with the switch on, the title's buffers are GPU-accessed in system memory over PCIe instead of from the tiled video-memory copies. That is the same placement as the coherent window, and its GPU costs have been measured on #505:

  • Dependent reads (a load whose address comes from a previous load, as in ray marches and table walks): 256 per lane in a 4 KiB block took 0.61–0.70 ms in a heap over process memory against 0.02 ms in VRAM (RTX 5090 on Windows and Linux, Ariorh1337, tylerstraub). That is about one PCIe round trip each, roughly 30×.
  • Stores whose lanes leave gaps (Store2 / Store4 / per-lane +0/4/8/12): 0.10 GB/s in such a heap, against ~1,000–2,000 GB/s in VRAM (RTX 5080, my report). Contiguous stores and plain reads run at PCIe speed, 10–50 GB/s depending on the link.
  • kanade333 and Ariorh1337 saw the reverse in title runs: moving the title's GPU heaps out of process memory made the heavy compute passes 14–350× shorter.

So XCL_SPARSE_DIRECT=1 probably trades the CPU look for GPU time on any pass that reads or writes those buffers with such patterns. One XCL_GPU_PROFILE=1 pair (switch off / on, same driving) would show it: the passes whose longest call grows. If it's that, a split may get both wins: direct for buffers the title writes on the CPU and the GPU only reads linearly, and the tiled VRAM copy for buffers the GPU writes or walks. Measuring which is which needs the title, which I don't have.

AI use: Claude Code (Claude Opus 5.5) wrote this from the linked measurements.

@Filip722

Filip722 commented Nov 25, 2026 •

Copy link
Copy Markdown

I reproduced a resource leak during fallback at 5e71371. When a first direct buffer succeeds and a later placement fails, the first buffer keeps an extra COM reference. With a 64 KiB imported heap and a deliberately oversized second placement, the isolated buffer's reference count was 3 after fallback, up from 2. This occurs in window initialization, separately from the heap reference reported in place_buffer.

fd99b68 keeps ownership until every window succeeds. The same Windows regression returned to the original count with the fix (1 passed, no skip). The failing comparison used the same small test and publication helper with the PR's original raw-handle ownership.

A separate 64 MiB probe on this PR head verified aligned overlapping placement addresses and a fenced GPU copy through a placed buffer. All 64 CPU-initialized words reached a second offset in the imported CPU backing, with surrounding words intact. The existing tiled sparse descriptor/compute test also passed. Tested on Bazzite 44, RTX 5060 Laptop GPU (8 GB), NVIDIA 615.78.08, Proton Experimental 11.0-20261112, vkd3d-proton 3.1.0 build 4522cc1a8b1347f+. Full-size direct windows and gameplay remain unverified on this laptop.

On a private Lockhart integration I also compared tiled memory with importing only the last sparse window. In the tiled run, 43,344 of the last sample's 47,888 physical-destination tile bindings went to window 2. The title's 3,977 MiB reservation crossed from window 1 into window 2. With the mixed layout it fit entirely at the start of window 2, whose import succeeded. The tiled run stopped at 3,138 MiB free VRAM. The mixed run had 6,648 MiB free VRAM at its last slow sample and stopped at 6,138 MiB available host RAM on this 16 GB machine. Both stopped before the first GPU submission. The runs ended at different stages, so these figures are stopping conditions, not a measured memory saving.

Separately, two shader dispatches copied 64 words across the tiled/imported boundary in both directions with the surrounding guards intact. The same check passed on a forced tiled fallback. This prototype uses an 8 MiB import for the synthetic tests and a nearly 4 GiB import for the title comparison.

AI use — OpenAI Codex (GPT-6.2-Sol) wrote the patch, ran the tests and prepared this report.

@iGoldenNinja

Copy link
Copy Markdown

Independent RTX 5080 check at 5e71371, Windows 11 Pro 26200, driver 617.14, Ryzen 9 5900X, 32 GB RAM, MSVC release, DXC/DXIL validator 1.9.2609.5.

  • The direct-layout and full-size imported-window placement tests passed. D3D12 accepted aligned overlapping placements at the expected GPU offsets and rejected the unaligned placement.
  • gpu_uma_import_check_at_init and gpu_sparse_vram_descriptors_buffers_and_xmem both passed with XCL_SPARSE_DIRECT=0 and with =1 in separate processes, no skips. The enabled path logged all three direct windows on the real RTX 5080 backend. The end-to-end fixture verified readback before and after updating the input buffer and its descriptor.

This covers initial heap import, placement and the tested GPU data path. The separate lifetime and title performance questions remain open. Method and results. Testing and reporting assisted by OpenAI Codex.

@JoaoPauluu

Copy link
Copy Markdown

A regression run under Wine on Linux on the retail title: no device removal, no crash, frames level with main (1417 here; 1371 and 1356 on the two main runs). The sparse windows are in use here (3 sparse window(s) for the title's own memory, 16 submits, 280 MB of CPU writes uploaded, 21 ms spent, 4328 tiles mapped), and none of the PR's three new sparse window warnings appear. So on vkd3d-proton the direct read path set up without falling back to tiled.

Tested

Regression run

main (first run):

xcl-smoke v1
commit: f5c5bdf0e91035f8f1404f46f4f2f7aedc259e7f
gpu: NVIDIA GeForce RTX 3060
title: GTA6.Xbox.v1.0.2.1
seconds: 60
exit: 0x0
frames shown: 1371 (PresentX 1371)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 0 MB

this PR:

xcl-smoke v1
commit: 5e71371dffbdc8b9f58aa8b58493803e522ed070
gpu: NVIDIA GeForce RTX 3060
title: GTA6.Xbox.v1.0.2.1
seconds: 60
exit: 0x0
frames shown: 1417 (PresentX 1418)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 0 MB

The second main run: 1356 frames, exit: 0x0, no device removal, no crash. Under Wine, peak commit reads 0 MB, so these blocks do not check memory.

Not tested

  • the test suite on this head, a longer run, memory use (peak commit reads 0 MB under Wine), native Windows.

AI use

  • Claude Code (Claude Opus 5.5) built both commits, ran the runs and wrote this report. The account owner asked for test reports to be posted and has not reviewed this one.

@DavidM1911

Copy link
Copy Markdown
Contributor

Verification on RTX 3060 Ti (Windows 11), branch merged with current main:

Thanks!

@Royalflamejlh

Copy link
Copy Markdown
Contributor

Linux (Wine + vkd3d-proton) + NVIDIA test of 5e71371 with the switch on: all three sparse windows were imported (3 sparse window(s) hold the title's own pages: no tiles, no upload) in 2 of 2 runs, with no fault and no device removal. On this 12 GB card it did not change how far the title got in 100 s. It held 1.6 GB less on the card at 30 s and the same 8.9 GB at the end; non-local video memory was 12.3 GB higher from the first reading at 4 s, the size of the three windows (3 × 4,095 MB), and 9.6 GB higher at the end.

The Linux run above quoted 3 sparse window(s) for the title's own memory: this tree logs that line with the switch off (… (tiled buffers on video memory)), so that run was on the tiled path.

Setup: Fedora 44, Wine 11.21 Staging, vkd3d-proton v3.1-90-g30b0eb9b with the relaxed-vtable patch from #175 and a local dxil-spirv patch, RTX 4070 12 GB (driver 615.71.09), 62 GB RAM. 5e71371 merged on main f5c5bdf with #684, release, cross-compiled to x86_64-pc-windows-gnu, XCL_PSO_PRELOAD=0. Retail title 1.0.2.1, the first-run screens completed once and no story progress, A at 16.3 to 16.6 s. The same tree in both columns, 2 runs each, in the order on, off, off, on. Video memory is DXGI's local / non-local, from DXVK's dxgi.

Tested

100 s switch off XCL_SPARSE_DIRECT=1
video memory at 30 s, local / non-local 6,471 / 4,129 MB in both 4,865 / 16,416 MB in both
video memory at the end, local / non-local 8,925 / 9,132 and 8,934 / 9,128 MB 8,896 / 18,784 and 8,900 / 18,749 MB
write-watch look, running total at look 2,048 (30.6 to 31.4 s, the last one logged) 1,115 and 1,240 ms 591 and 671 ms
first #101 call 73.9, 56.8 s 73.6, 70.3 s
last 2 s with a present 76.2, 74.3 s 76.0, 72.2 s
frames 1279, 1262 1307, 1236
sparse pools (the memory line's own), at 30 s / at the end 960 / 2,048 MB in both 0 / 0
faults / device removals / NVIDIA kernel messages 0 / 0 / 0 0 / 0 / 0
  • The card levelled off at 8.9 GB from 46 to 54 s in all 4 (a guess: what the desktop leaves of the 12 GB).
  • The look still ran with the switch on, at about half the cost up to 31 s (title_textures.rs:711 calls note_watch in both modes); its cost during the load, 31 to 76 s, was not logged.
  • Start-up: the sparse window(s) line came at 3.1 and 2.6 s with the switch on, 1.3 and 1.2 s with it off.

Not tested: past 100 s; a card with room left (16 GB or more), where the freed video memory could show; how much of the non-local memory was resident RAM (Wine reports no commit charge); the decommit and fallback paths raised above; Windows; AMD and Intel.

AI use: Claude Code (Claude Fable 5.2) read the diff, built the tree, ran the title and wrote this comment.

Posted without review by a person: the account owner was away and reads replies later.

IvyNotFound added a commit to IvyNotFound/xcl that referenced this pull request Nov 25, 2026
# Conflicts:
#	crates/xcl/src/gpu/uma.rs
#	crates/xcl/src/hle/d3d12x/sparse.rs
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.

8 participants