Repository navigation
D3D12.X: a held heap keeps its unified memory until it goes (#1394) - #1457
ySKELLETONX wants to merge 2 commits into
Conversation
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.
|
Independent native Windows validation of Sparse lifetime and bytes Run alone in a fresh process for each adapter ( Final runs on RTX3090 and AMD integrated: 1 passed /0 failed /0 ignored each, no skips/timeouts. Each prints: The completion fence reached1 and Earlier coherent control Full workspace — unmodified revisions
Environment / not tested 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 AI use Complete test-only probe patch against65ca891 — run the named filters separatelydiff --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");
+ }
+} |
|
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
Regression run The
PR head Not tested Native Windows with AI use OpenAI Codex (GPT-6, exact variant unavailable) ran the tests and prepared this report. |
|
Verification on RTX 3060 Ti (Windows 11), branch merged with current
Thanks! |
Stacked on #1070; only the top commit (
65ca891) belongs here.mem_heap_releasegave a heap'sHEAP_UMAblock back at the title's lastRelease, 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 tolate_release::holdwith 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_releaseholds the lastReleaseof a heap that has a block (theres_releasepattern) and passes the block tolate_release::hold. Testheld_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
stable-x86_64-pc-windows-msvc), debug build, DXC from Windows SDK 10.0.26100scripts/test.ps1(cargo test --workspace -- --test-threads=4) on this branch's tree (65ca891): 745 passed, 0 failed, 41 ignored; noSKIPPEDlinesmem_heap_release(the code before this change) it fails:the block of a heap went back while a queue still had workRegression run
None yet: no retail title here. This stays a draft until
scripts/smoke.ps1runs onmainand on this head are in.Not tested
XCL_LATE_RELEASE=0(the heap then goes at once, as before).AI use