Skip to content

D3D12.X: a held heap keeps its unified memory until it goes (#1394) - #1457

Draft
ySKELLETONX wants to merge 2 commits into
xcl-dev:mainfrom
ySKELLETONX:d3d12x-heap-late-release
Draft

ySKELLETONX wants to merge 2 commits into
xcl-dev:mainfrom
ySKELLETONX:d3d12x-heap-late-release

Conversation

@ySKELLETONX

Copy link
Copy Markdown

Stacked on #1070; only the top commit (65ca891) belongs here.

mem_heap_release gave a heap's HEAP_UMA block back at the title's last Release, also while a queue could still read the buffers placed in it (they live in the block, not in the PC heap). A coherent block went back on the free list, where the next allocation could take it; a sparse one was decommitted. A heap with a block is now held like a resource (late_release), and its block goes to late_release::hold with it (#1070) to be given back once the queues are past the work in flight. A heap without a block goes at once, as before. Fixes #1394.

What is in it

  • crates/xcl/src/hle/d3d12x/real.rs: mem_heap_release holds the last Release of a heap that has a block (the res_release pattern) and passes the block to late_release::hold. Test held_release_tests::a_held_heap_keeps_its_unified_memory_until_it_goes (a queue held on a fence: the block stays allocated until the fence is signalled).

Tested

  • AMD Radeon RX 7600 XT (RDNA3, driver 32.0.32015.2008), Ryzen 7 5700X3D, Windows 11 Pro 10.0.26300, rustc 1.100.0 (stable-x86_64-pc-windows-msvc), debug build, DXC from Windows SDK 10.0.26100
  • scripts/test.ps1 (cargo test --workspace -- --test-threads=4) on this branch's tree (65ca891): 745 passed, 0 failed, 41 ignored; no SKIPPED lines
  • the new test ran on the D3D12 device (not skipped) and passes; with the hold switched off in mem_heap_release (the code before this change) it fails: the block of a heap went back while a queue still had work

Regression run
None yet: no retail title here. This stays a draft until scripts/smoke.ps1 runs on main and on this head are in.

Not tested

  • A retail title (no smoke runs); whether a title releases a heap with buffers while a queue has work is not measured.
  • NVIDIA, Intel, WARP; XCL_LATE_RELEASE=0 (the heap then goes at once, as before).

AI use

  • Claude Code (Claude Opus 5.5): traced the issue, wrote the change, the test and this description, and ran the tests above.

DTsordas and others added 2 commits November 24, 2026 15:23
Late release (e7da8a1) holds a resource whose last Release comes while a
queue may still use it, but res_release still gave back what XCL placed
under it at the title's Release: the unified-memory block went back on
the free list (the next resource could get it while the GPU still used
it), and a sparse block was decommitted and its tiles unpinned.

The bookkeeping still goes at the title's Release. A held resource's
block and its sparse tile pins go to late_release. Once the queues are
past it, its tiles are unpinned and a sparse block is freed before its
final Release (its address is no other resource's yet), and a block in a
coherent window after it. A release that is not held frees at once, as
before.

The drain does not wait for the sparse state's lock for this
(sparse::try_forget_held): it runs inside XCL's own submits and inside
D3D12 calls that make a last Release, where the lock's holder can be
waiting for that thread. A resource it cannot let go then goes at the
next drain.

Fixes xcl-dev#1040

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…1394)

mem_heap_release gave a heap's HEAP_UMA block back at the title's last
Release, also while a queue could still read the buffers placed in it
(they live in the block, not in the PC heap). A coherent block went
back on the free list, where the next allocation could take it; a
sparse one was decommitted.

A heap with a block is now held like a resource (late_release), and its
block goes to late_release::hold with it (xcl-dev#1070), to be given back once
the queues are past the work in flight. A heap without a block goes at
once, as before.

The test holds a queue on a fence, releases a heap with a block and
checks the block stays allocated until the fence is signalled; it fails
without the change.
@WebIdentity1

WebIdentity1 commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Independent native Windows validation of 65ca8911c50d657c3856d541341a4afc01d7b1cb, stacked on #1070 d0ebe34473f3668b1ed9a58bbd2294cbbbed90c4. Updated with an actual sparse-buffer GPU copy.

Sparse lifetime and bytes
Local test-only probe: seed the title-heap registration with no block, then call production heap_block and dev_create_placed_resource_x. The64KiB block is confirmed sparse; the placed resource's recorded console range matches it. Upload16,384 patterned words through sparse::before_execute, queue a GPU CopyBufferRegion behind an unsignalled fence, then release both the placed buffer and title heap. Verify the allocation and committed CPU pages remain while the copy is pending. Signal, read back every word, and check eventual sparse-reservation release plus OS page decommit.

Run alone in a fresh process for each adapter (XCL_ADAPTER=3090 / AMD):
cargo test --locked -p xcl --lib sparse_heap_release_preserves_queued_copy_bytes -- --test-threads=1 --show-output --nocapture

Final runs on RTX3090 and AMD integrated: 1 passed /0 failed /0 ignored each, no skips/timeouts. Each prints:

sparse=true held_before_signal=true committed_before_signal=true copy_pending=true
checked_words=16384 mismatches=0 reservation_released=true decommitted=true

The completion fence reached1 and GetDeviceRemovedReason succeeded. A separate3090 oracle control flips one uploaded word without changing expected output:0/1/0, exactly1 mismatch, both cleanup checks still true. Restored source, reran both GPUs successfully, verified all222 final source hashes against Windows.

Earlier coherent control
The upstream fixture uses create_device(None, ...); the local patch explicitly selects/prints the adapter. It signals before assertions so the failing control unblocks the queue. Filter a_held_heap_keeps_its_unified_memory_until_it_goes with the same command:3090 andAMD each1/0/0, no skips/timeouts; coherent block held before signal and freed afterward. Restoring only mem_heap_release from exact parent makes the same3090 fixture fail0/1/0 because the block was already freed while fenced. Runtime source restored afterward. This old-function control was coherent-only; the sparse negative control checks the byte oracle, not the old release function.

Full workspace — unmodified revisions
All221 source hashes checked for each archived revision. Interactive Session1:
cargo build --locked --workspace: exit0 on both.
cargo test --locked --workspace --no-fail-fast -- --test-threads=4 --show-output:

  • Exact stacked parent d0ebe34: 743 passed /1 failed /41 ignored.
  • PR head 65ca891: 744 passed /1 failed /41 ignored.
    Same existing gpu_clamp_and_omod_per_instruction failure (test exit101), no timeout. Four explicit skips each: gpu_geometry_wave32_prefix_count_over_a_mask, gpu_wave32_program_in_wave64_hardware (native wave64), test_title_draws_with_a_root_signature_under_the_debug_layer, uploads_start_from_each_subresources_state (debug layers absent).

Environment / not tested
Windows10 Home19045, Ryzen7 7800X3D/32GB, RTX3090 driver591.74, AMD integrated32.0.21030.2001, Rust1.98.1 MSVC, SDK DXC1.8.2502.11, Agility1.620.2, debug. Focused probes in SSH Session0. Recompiler suite selects3090; upstream default-adapter fixtures may useAMD. Sample inputs absent and system XGameRuntime comparison unavailable.

Full-suite results are the unmodified stacked-parent comparison, not current-main integration or the scratch-probe tree. The sparse probe initializes global state and must run alone; it has not been qualified as a parallel suite test. It seeds heap registration directly, not a full title startup. No shader dispatch, retail/gameplay, disabled-late-release path or required xcl-smoke pair. No competing runtime implementation/PR.

AI use
Codex (GPT-6) inspected source, prepared diagnostics/controls, executed native runs and wrote the report.

Complete test-only probe patch against65ca891 — run the named filters separately
diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs
index b34ce76..95b4acc 100644
--- a/crates/xcl/src/hle/d3d12x/real.rs
+++ b/crates/xcl/src/hle/d3d12x/real.rs
@@ -5861,9 +5861,13 @@ mod held_release_tests {
             if !super::super::late_release::enabled() {
                 return;
             }
-            let Ok(dev) = crate::gpu::agility::create_device(None, D3D_FEATURE_LEVEL_11_0) else {
+            let factory: IDXGIFactory6 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).unwrap();
+            let sel = crate::gpu::adapter::Selector::from_env_or("auto");
+            let Some((adapter, desc)) = crate::gpu::adapter::candidates(&factory, &sel).into_iter().next() else {
                 return crate::gpu::recomp::runner::skip_test("no GPU");
             };
+            println!("adapter={}", crate::gpu::adapter::name(&desc));
+            let dev = crate::gpu::agility::create_device(&adapter, D3D_FEATURE_LEVEL_11_0).unwrap();
             let Some(u) = crate::gpu::uma::get() else {
                 return crate::gpu::recomp::runner::skip_test("no GPU");
             };
@@ -5892,15 +5896,23 @@ mod held_release_tests {
 
             // the title's last Release, while the queue still has work
             let release: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*(*(raw as *const *const usize)).add(2));
-            assert_eq!(release(raw), 0);
-            assert!(u.is_allocated(p), "the block of a heap went back while a queue still had work");
-
+            let remaining = release(raw);
+            let held_before_signal = u.is_allocated(p);
+            println!("release={remaining} held_before_signal={held_before_signal} sparse={}", u.is_sparse(p));
+            // Unblock the queue before asserting, including in the old-behavior control.
             gate.Signal(1).unwrap();
+            assert_eq!(remaining, 0);
+            assert!(held_before_signal, "the block of a heap went back while a queue still had work");
             let start = std::time::Instant::now();
             while u.is_allocated(p) && start.elapsed() < std::time::Duration::from_secs(10) {
                 std::thread::sleep(std::time::Duration::from_millis(5));
             }
+            println!("freed_after_signal={} elapsed_ms={}", !u.is_allocated(p), start.elapsed().as_millis());
             assert!(!u.is_allocated(p), "the block goes back once the held heap goes");
         }
     }
 }
+
+#[cfg(test)]
+#[path = "heap_sparse_probe.rs"]
+mod heap_sparse_probe;
diff --git a/crates/xcl/src/hle/d3d12x/heap_sparse_probe.rs b/crates/xcl/src/hle/d3d12x/heap_sparse_probe.rs
new file mode 100644
index 0000000..589bb5d
--- /dev/null
+++ b/crates/xcl/src/hle/d3d12x/heap_sparse_probe.rs
@@ -0,0 +1,110 @@
+//! Local synthetic PR1457 validation; run alone in its own process.
+use super::*;
+use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, MEM_RESERVE};
+
+unsafe fn page_state(p: usize) -> u32 {
+    let mut info: MEMORY_BASIC_INFORMATION = std::mem::zeroed();
+    assert_ne!(VirtualQuery(p as *const c_void, &mut info, std::mem::size_of_val(&info)), 0);
+    info.State
+}
+
+#[test]
+fn sparse_heap_release_preserves_queued_copy_bytes() {
+    unsafe {
+        assert!(super::super::late_release::enabled(), "requires late release");
+        let factory: IDXGIFactory6 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).unwrap();
+        let sel = crate::gpu::adapter::Selector::from_env_or("auto");
+        let Some((adapter, desc)) = crate::gpu::adapter::candidates(&factory, &sel).into_iter().next() else {
+            return crate::gpu::recomp::runner::skip_test("no GPU");
+        };
+        println!("adapter={}", crate::gpu::adapter::name(&desc));
+        let dev = crate::gpu::agility::create_device(&adapter, D3D_FEATURE_LEVEL_12_0).unwrap();
+        let u = crate::gpu::uma::get().expect("UMA");
+        let windows = super::super::sparse::init(&dev);
+        assert!(!windows.is_empty(), "native sparse windows initialized");
+        // init returns owned window references; the sparse state retains its own copies.
+        for (_, raw, _) in windows { drop(ID3D12Resource::from_raw(raw as *mut c_void)); }
+        let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap();
+        let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap();
+        let done: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap();
+        let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap();
+        let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap();
+        const BYTES: usize = 65536;
+        let d = D3D12_RESOURCE_DESC {
+            Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: BYTES as u64,
+            Height: 1, DepthOrArraySize: 1, MipLevels: 1,
+            SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
+            Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, ..Default::default()
+        };
+        let mut readback: Option<ID3D12Resource> = None;
+        dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() },
+            D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut readback).unwrap();
+        let readback = readback.unwrap();
+        let mut heap: Option<ID3D12Heap> = None;
+        dev.CreateHeap(&D3D12_HEAP_DESC {
+            SizeInBytes: BYTES as u64, Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() },
+            Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS, ..Default::default()
+        }, &mut heap).unwrap();
+        let heap = heap.unwrap();
+        adopt(dev.as_raw(), Kind::Device);
+        adopt(heap.as_raw(), Kind::Heap);
+        // Seed only the title-heap registration; allocation and buffer placement use production paths.
+        HEAP_UMA.lock().unwrap().get_or_insert_with(HashMap::new).insert(heap.as_raw() as usize,
+            HeapUma { size: BYTES, align: BYTES, prefer_coherent: false, cpu_readback: false, block: None });
+        let (p, _) = heap_block(heap.as_raw() as usize).expect("production heap block");
+        assert!(u.is_sparse(p));
+        let mut console = [0u8; 0x38];
+        console[..4].copy_from_slice(&1u32.to_le_bytes());
+        console[16..24].copy_from_slice(&(BYTES as u64).to_le_bytes());
+        console[24..28].copy_from_slice(&1u32.to_le_bytes());
+        console[28..30].copy_from_slice(&1u16.to_le_bytes());
+        console[30..32].copy_from_slice(&1u16.to_le_bytes());
+        console[36..40].copy_from_slice(&1u32.to_le_bytes());
+        console[44..48].copy_from_slice(&1u32.to_le_bytes());
+        let mut raw = std::ptr::null_mut();
+        let iid = ID3D12Resource::IID;
+        let hr = dev_create_placed_resource_x(dev.as_raw(), heap.as_raw() as usize, 0, console.as_ptr() as usize,
+            D3D12_RESOURCE_STATE_COPY_SOURCE.0 as usize, 0, &iid as *const _ as *const GUID, &mut raw);
+        assert!(hr >= 0 && !raw.is_null(), "placed sparse buffer: {hr:#x}");
+        let source = ID3D12Resource::from_raw(raw);
+        assert_eq!(console_buffer(raw as usize), Some((p, BYTES)));
+        let expected: Vec<u32> = (0..BYTES / 4).map(|i| 0x7135abcd ^ (i as u32).wrapping_mul(0x10203)).collect();
+        std::ptr::copy_nonoverlapping(expected.as_ptr(), p as *mut u32, expected.len());
+        let dirty: Vec<usize> = (p..p + BYTES).step_by(4096).collect();
+        super::super::sparse::before_execute(&queue, &dirty, 4096);
+        list.CopyBufferRegion(&readback, 0, &source, 0, BYTES as u64);
+        list.Close().unwrap();
+        queue.Wait(&gate, 1).unwrap();
+        queue.ExecuteCommandLists(&[Some(list.cast::<ID3D12CommandList>().unwrap())]);
+        queue.Signal(&done, 1).unwrap();
+        super::super::present::note_execute(queue.as_raw(), &[]);
+        drop(source);
+        drop(heap);
+        let held = u.sparse_reservation(p).is_some();
+        let committed = page_state(p) == MEM_COMMIT;
+        let pending = done.GetCompletedValue() == 0;
+        println!("sparse=true held_before_signal={held} committed_before_signal={committed} copy_pending={pending}");
+        gate.Signal(1).unwrap();
+        let start = std::time::Instant::now();
+        while done.GetCompletedValue() == 0 && start.elapsed().as_secs() < 10 {
+            std::thread::sleep(std::time::Duration::from_millis(1));
+        }
+        assert_eq!(done.GetCompletedValue(), 1, "GPU copy completed without device removal");
+        dev.GetDeviceRemovedReason().unwrap();
+        let mut mapped = std::ptr::null_mut();
+        readback.Map(0, Some(&D3D12_RANGE { Begin: 0, End: BYTES }), Some(&mut mapped)).unwrap();
+        let got = std::slice::from_raw_parts(mapped as *const u32, expected.len());
+        let wrong = got.iter().zip(&expected).filter(|(a, b)| a != b).count();
+        readback.Unmap(0, Some(&D3D12_RANGE { Begin: 0, End: 0 }));
+        let start = std::time::Instant::now();
+        while u.sparse_reservation(p).is_some() && start.elapsed().as_secs() < 10 {
+            std::thread::sleep(std::time::Duration::from_millis(5));
+        }
+        let released = u.sparse_reservation(p).is_none();
+        let decommitted = page_state(p) == MEM_RESERVE;
+        println!("checked_words={} mismatches={wrong} reservation_released={released} decommitted={decommitted}", expected.len());
+        assert!(held && committed && pending, "backing memory must remain while the copy waits");
+        assert_eq!(wrong, 0, "GPU read the original bytes after the title released both objects");
+        assert!(released && decommitted, "backing memory goes after the queue passes");
+    }
+}

@vitor127wt

Copy link
Copy Markdown

I ran the retail smoke comparison requested in #1243 on Proton. Both runs used the same Xbox title for 60 seconds, with fresh Proton prefixes and XCL caches.

Tested

  • Ryzen 7 9700X, 32 GB DDR5 and NVIDIA GeForce RTX 5070 Ti with driver 620.73.04 on CachyOS (kernel 7.3.5-2-cachyos).
  • Proton Experimental 11.0 (experimental-11.0-20261112-x86_64), vkd3d-proton ec207194 with the XCL patch from Linux: docs/linux.md, scripts/linux and Wine start-up checks for vkd3d-proton and DXVK (#154, #241) #257, DXC 1.9.2609.5 and VKD3D_CONFIG=ignore_shared_fence.
  • Windows MSVC release builds from clean checkouts using cargo xwin build --offline --locked --target x86_64-pc-windows-msvc --release -p xcl --bin xcl. Ran scripts/linux/smoke.sh "$PROTON" "$PREFIX" "$GAME" 60 from Linux: docs/linux.md, scripts/linux and Wine start-up checks for vkd3d-proton and DXVK (#154, #241) #257 with XCL_EXE pointing to the matching build.
  • Built the release test executable with cargo xwin test --offline --locked --target x86_64-pc-windows-msvc --release -p xcl --lib --no-run. Ran wine <xcl-test.exe> a_held_heap_keeps_its_unified_memory_until_it_goes --test-threads=1 --nocapture with Proton's Wine on the RTX 5070 Ti. 1 passed, 0 failed, 0 ignored, 0 skipped.

Regression run

The title field omits a local folder suffix. All measurements are as emitted by the script.

main

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

PR head

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

Not tested

Native Windows with scripts/smoke.ps1 and the full workspace suite. Wine reported peak commit: 0 MB in both runs, so these blocks provide no usable peak memory comparison.

AI use

OpenAI Codex (GPT-6, exact variant unavailable) ran the tests and prepared this report.

@DavidM1911

Copy link
Copy Markdown
Contributor

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

  • cargo test -p xcl --lib: all passed, 0 failed, ~21 ignored. (Intermittent single-test flake / 0xc0000005 abort under parallel scheduling; clean on single-threaded rerun — same flake seen on unmodified main.)

Thanks!

IvyNotFound added a commit to IvyNotFound/xcl that referenced this pull request Nov 25, 2026
@throny throny added the goal:world-load Bears on the retail title getting past world loading label Nov 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

goal:world-load Bears on the retail title getting past world loading

Projects

None yet

Development

Successfully merging this pull request may close these issues.

D3D12.X: mem_heap_release frees HEAP_UMA backing immediately while placed resources may still be in flight

6 participants