Repository navigation
D3D12.X: read the title's sparse windows directly instead of copying them - #2090
brandostrong wants to merge 4 commits into
Conversation
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>
|
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:
What still mirrors after that: textures the title places in sparse windows (a detiled PC copy — that Claude Code, Claude Opus 5.5 — the numbers are from runs made here. |
|
A second confirmed issue at The attached candidate applies the direct path's existing zero-for-reuse policy to this entry point. A small Tested
$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 --nocaptureIsolated 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 ( 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 regressiondiff --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 testConfirmed a heap-reference leak in the direct The minimal fix in Tested
$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 --nocaptureRun 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 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 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 regressiondiff --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`). |
|
Matched head-to-head on the same title: same 180 s, a fresh copy of the same warm profile, the same
The look and the buffer mirror really are gone and the default path is unchanged. The frame count with Claude Code, Claude Opus 5.5 — all three runs were made here. |
|
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
So AI use: Claude Code (Claude Opus 5.5) wrote this from the linked measurements. |
|
I reproduced a resource leak during fallback at 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 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. |
|
Independent RTX 5080 check at
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. |
|
A regression run under Wine on Linux on the retail title: no device removal, no crash, frames level with Tested
Regression run main (first run): this PR: The second Not tested
AI use
|
|
Verification on RTX 3060 Ti (Windows 11), branch merged with current
Thanks! |
|
Linux (Wine + vkd3d-proton) + NVIDIA test of The Linux run above quoted 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. Tested
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. |
# Conflicts: # crates/xcl/src/gpu/uma.rs # crates/xcl/src/hle/d3d12x/sparse.rs
|
RTX 3070 Ti 8 GB, driver 621.14, Windows 11 26100, release. Local tree:
AI use: Claude Code ran the runs and wrote this. |
|
AMD run (listed as untested), plus an RTX 3060: the new GPU test passes on both. Head
Not tested: the switch on in a title (so not the 3 × 4095 MB commit charge on this machine), Intel. |
|
Setup: RTX 3090 Ti 24 GB (driver 621.01), i9-13900K, 31.7 GB RAM, Windows 11 Pro 26300, Rust 1.100.0, release. On #2090's own head ( Merged locally into #2057 (
Not tested: #2090 on its own head with a full cache; AMD; more than one run of g9. AI use: Claude Code (Claude Opus 5.5) merged the trees, ran everything above and wrote this report. |
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
GetWriteWatchand uploads what changed. For a title that commits most of unified memory that sweepis 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.rsimports it (
OpenExistingHeapFromAddress) and places one buffer over it, so a buffer the titleplaces 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=1reserves and commits each sparse window in onecall at
MAX_SIZE;window()andwatch_regions()follow the layout through asparse_lenfield, and a layout the host cannot commit falls back to the tiled reservation. Test for the layout.
crates/xcl/src/hle/d3d12x/sparse.rs:initimports each window and places one buffer over it,place_bufferplaces on that heap at the same address, andcommitted/decommitted/freeskip the tile and
Statework. 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 placedbuffer 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_watchreports the look's cost – the line that showedit came from
before_execute, which this layout never reaches.README.md: the new switch.Tested
cargo build --workspace, thencargo test --workspace -- --test-threads=4: 1156 passed,0 failed, 46 ignored; 24
SKIPPEDlines – all wave64-only GPU tests (this adapter reports32-lane waves) and the f16 VOP3-modifier refusals
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.Waittimeouts from 34–69 a run to 8, no device removal,UMA import check: okRegression run
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_DIRECTis off in both (the default), so these blocks show that the defaultpath is unchanged; the switch-on numbers are the ones under Tested, from separate runs.
Not tested
commit headroom falls back to the tiled layout (that fallback is unit-tested, not run on a title)
the mirror: this removes the buffer mirror and the look over mapped tiles, not the texture copy
AI use
both
xcl-smokeblocks are from runs made here, on the hardware named.🤖 Generated with Claude Code