From fe97ba101f5fed789a74ab6b5dc60b9ca1152b30 Mon Sep 17 00:00:00 2001 From: Saurabh Bhoir Date: Wed, 25 Nov 2026 08:49:59 +0530 Subject: [PATCH 1/4] D3D12.X: fix HEAP_UMA lifetime issue for placed buffers (XCL-BT-001) When a HEAP_UMA heap was released (refcount reached 0), its backing memory block was freed immediately even if placed buffers still referenced it. This caused memory corruption when the title's last Release of a buffer raced with the heap's Release. The fix tracks live_buffers per HEAP_UMA heap: - Increment live_buffers when a buffer is placed in the heap (5 insertion sites) - In res_release: decrement live_buffers; if it reaches 0 and the heap was already released (block is Some), free the block - In mem_heap_release: if live_buffers == 0, free block immediately and remove entry; otherwise set block = None and keep entry so last buffer's Release can free it This defers the block free until all buffers in the heap are released. --- crates/xcl/src/hle/d3d12x/real.rs | 97 ++++++++++++++++++++++++------- 1 file changed, 77 insertions(+), 20 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 9241a3a18d..93a9c11b95 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -172,14 +172,15 @@ pub fn abi_root_signature() -> Option { static UMA_BUFFER: Mutex> = Mutex::new(Vec::new()); /// the committed UMA windows opened as D3D12 heaps (indexed by window `k`; `None` for sparse windows) static UMA_HEAPS: Mutex>> = Mutex::new(Vec::new()); -/// console buffers placed in unified memory: resource → (address, bytes) -/// address, bytes, whether XCL allocated the memory (not: the title's own, CreatePlacedResourceX) -type UmaBuffer = (usize, usize, bool); +/// console buffers placed in unified memory: resource → (address, bytes, xcl_allocated, heap) +/// address, bytes, whether XCL allocated the memory (not: the title's own, CreatePlacedResourceX), +/// and the heap the buffer was placed in (for deferred HEAP_UMA free; 0 = no HEAP_UMA entry). +type UmaBuffer = (usize, usize, bool, usize); static UMA_BUFFERS: Mutex>> = Mutex::new(None); /// Where a console-created buffer lives in unified memory (its console GPU address). pub fn console_buffer(res: usize) -> Option<(usize, usize)> { - UMA_BUFFERS.lock().unwrap().as_ref()?.get(&res).map(|&(p, n, _)| (p, n)) + UMA_BUFFERS.lock().unwrap().as_ref()?.get(&res).map(|&(p, n, _, _)| (p, n)) } /// Number of live console buffers in unified memory. @@ -1255,7 +1256,7 @@ unsafe fn place_console_texture(this: *mut c_void, desc: usize, state: usize, cl u.free(p); return None; } - UMA_BUFFERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (p, size as usize, true)); + UMA_BUFFERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (p, size as usize, true, 0)); Some(hr) } @@ -1311,7 +1312,7 @@ fn is_cpu_readback_buffer(props: &D3D12_HEAP_PROPERTIES, state: u32, flags: D3D1 unsafe fn place_console_buffer_sparse(this: *mut c_void, d: &D3D12_RESOURCE_DESC, bytes: usize, state: u32, readback_on_null_map: bool, riid: *const GUID, ppv: *mut *mut c_void) -> Option { let (p, _) = super::sparse::alloc(bytes, 0x1_0000)?; if let Some((hr, delta)) = super::sparse::place_buffer(this, p, d, state, riid, ppv) { - UMA_BUFFERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (p, bytes, true)); + UMA_BUFFERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (p, bytes, true, 0)); if delta != 0 { BUFFER_DELTA.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, delta as u64); } @@ -1377,7 +1378,13 @@ unsafe fn place_console_buffer(this: *mut c_void, props: usize, desc: usize, sta } return None; } - UMA_BUFFERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (p, bytes, true)); + UMA_BUFFERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (p, bytes, true, heap)); + // Increment the heap's live buffer count + if let Some(h) = HEAP_UMA.lock().unwrap().as_mut() { + if let Some(e) = h.get_mut(&heap) { + e.live_buffers += 1; + } + } // Map must hand out the same memory the shaders read (checked once) static CHECKED: AtomicU64 = AtomicU64::new(0); if CHECKED.fetch_add(1, Ordering::Relaxed) == 0 { @@ -1416,7 +1423,7 @@ pub(super) unsafe fn place_at_title_address(this: *mut c_void, va: usize, desc: // the title's own memory (a sparse window): a resource over its video-memory tiles if u.is_sparse(va) { let (hr, delta) = super::sparse::place_buffer(this, va, &d, state, riid, ppv)?; - UMA_BUFFERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (va, bytes, false)); + UMA_BUFFERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (va, bytes, false, 0)); if delta != 0 { BUFFER_DELTA.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, delta as u64); } @@ -1431,7 +1438,13 @@ pub(super) unsafe fn place_at_title_address(this: *mut c_void, va: usize, desc: if hr < 0 || (*ppv).is_null() { return None; } - UMA_BUFFERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (va, bytes, false)); + UMA_BUFFERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (va, bytes, false, heap)); + // Increment the heap's live buffer count + if let Some(h) = HEAP_UMA.lock().unwrap().as_mut() { + if let Some(e) = h.get_mut(&heap) { + e.live_buffers += 1; + } + } if delta != 0 { BUFFER_DELTA.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, delta as u64); } @@ -1626,11 +1639,35 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { super::vram::forget(this as usize); super::title_textures::forget(this as usize); let gone = UMA_BUFFERS.lock().unwrap().as_mut().and_then(|m| m.remove(&(this as usize))); - if let (Some((p, _, true)), Some(u)) = (gone, crate::gpu::uma::get()) { - if u.is_sparse(p) { - super::sparse::free(p); - } else { - u.free(p); + if let (Some((p, _, xcl_allocated, heap)), Some(u)) = (gone, crate::gpu::uma::get()) { + if xcl_allocated { + if u.is_sparse(p) { + super::sparse::free(p); + } else { + u.free(p); + } + } + // If this buffer was in a HEAP_UMA heap, decrement live_buffers and maybe free the block + if heap != 0 { + if let Some(h) = HEAP_UMA.lock().unwrap().as_mut() { + if let Some(e) = h.get_mut(&heap) { + if e.live_buffers > 0 { + e.live_buffers -= 1; + } + // If heap was released (block is None) and no more live buffers, free the block + if e.live_buffers == 0 && e.block.is_some() { + if let Some(block) = e.block.take() { + if u.is_sparse(block) { + super::sparse::free(block); + } else { + u.free(block); + } + } + } + } + } + // Note: if the heap was already removed from HEAP_UMA (mem_heap_release called), + // the last buffer's decrement won't find it - that's handled in mem_heap_release } } } @@ -3022,6 +3059,9 @@ struct HeapUma { /// in it read back on `Map(0, NULL, ...)`. cpu_readback: bool, block: Option, + /// Number of live placed buffers in this heap. The heap's block is freed only when this + /// reaches zero *and* the heap has been released (refcount 0). + live_buffers: usize, } /// heap → its backing block (allocated lazily on the first placed buffer; sparse VRAM for @@ -3057,6 +3097,7 @@ unsafe fn note_heap_uma(desc: usize, ppv: *mut *mut c_void) { prefer_coherent: is_rb && size <= COHERENT_READBACK_MAX, cpu_readback: is_rb || is_custom_wb, block: None, + live_buffers: 0, }, ); } @@ -3126,16 +3167,32 @@ fn heap_block(heap: usize) -> Option<(usize, bool)> { } /// ID3D12Heap::Release: its block of unified memory goes with it. +/// The block is freed only when there are no more live placed buffers in the heap. +/// If buffers remain, the heap entry is kept (with block = None) so the last buffer can free it. unsafe extern "system" fn mem_heap_release(this: *mut c_void) -> u32 { let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2)); let n = f(this); if n == 0 { - let gone = HEAP_UMA.lock().unwrap().as_mut().and_then(|m| m.remove(&(this as usize))).and_then(|e| e.block); - if let (Some(p), Some(u)) = (gone, crate::gpu::uma::get()) { - if u.is_sparse(p) { - super::sparse::free(p); - } else { - u.free(p); + if let Some(h) = HEAP_UMA.lock().unwrap().as_mut() { + if let Some(e) = h.get_mut(&(this as usize)) { + if e.live_buffers == 0 { + // No live buffers: free the block now and remove the entry + if let Some(p) = e.block.take() { + let u = crate::gpu::uma::get(); + if let Some(u) = u { + if u.is_sparse(p) { + super::sparse::free(p); + } else { + u.free(p); + } + } + } + h.remove(&(this as usize)); + } else { + // Buffers still alive: mark heap as released (block = None) so last buffer knows to free it + // We keep the entry with live_buffers count; the last buffer's Release will free the block + e.block = None; + } } } } From 697cacae7a8ad7e6897dc4d7d7c8a9f00e836014 Mon Sep 17 00:00:00 2001 From: Saurabh Bhoir Date: Wed, 25 Nov 2026 09:32:14 +0530 Subject: [PATCH 2/4] D3D12.X: keep HEAP_UMA block until all placed buffers are released mem_heap_release set e.block = None when buffers were still alive, discarding the pointer res_release needs to free the block when live_buffers reaches zero. This leaked the backing block whenever a heap was released before its placed buffers. Keep the entry and its block so res_release frees the block once live_buffers hits 0 (checked via e.block.is_some()). Build: cargo build --workspace passes. Tests: cargo test --workspace 1153 passed, 0 failed (GPU tests skipped: no wave64 on AMD RDNA3). Co-Authored-By: Claude Code --- crates/xcl/src/hle/d3d12x/real.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 93a9c11b95..50f4727d13 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -3189,9 +3189,8 @@ unsafe extern "system" fn mem_heap_release(this: *mut c_void) -> u32 { } h.remove(&(this as usize)); } else { - // Buffers still alive: mark heap as released (block = None) so last buffer knows to free it - // We keep the entry with live_buffers count; the last buffer's Release will free the block - e.block = None; + // Buffers still alive: keep the entry (and its block) so the last buffer's + // Release can free the block when live_buffers reaches zero. } } } From e80d094c74aa02bfd3aa1f2c19bd79283f424319 Mon Sep 17 00:00:00 2001 From: Saurabh Bhoir Date: Wed, 25 Nov 2026 11:21:22 +0530 Subject: [PATCH 3/4] Recompiler: enable D3D12 debug layer before device creation in GPU test runner Fixes #2016: XCL_D3D12_DEBUG=1 removes the GPU test runner's device once a test starts the D3D12.X backend. The GPU test runner creates its D3D12 device in runner::init(), but the debug layer was being enabled in the D3D12.X backend after the device already existed. The debug layer must be enabled before any device is created. Enable the debug layer in runner::init() when XCL_D3D12_DEBUG is set, before adapter selection and device creation. Co-Authored-By: Claude Code --- crates/xcl/src/gpu/recomp/runner.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/crates/xcl/src/gpu/recomp/runner.rs b/crates/xcl/src/gpu/recomp/runner.rs index ed683350f7..c1e735e276 100644 --- a/crates/xcl/src/gpu/recomp/runner.rs +++ b/crates/xcl/src/gpu/recomp/runner.rs @@ -16,6 +16,8 @@ use windows::Win32::Graphics::Dxgi::*; use super::{KERNEL_LANES, KERNEL_RES_DWORDS, KERNEL_SCC_SLOT, KERNEL_SGPRS, KERNEL_VGPRS}; use crate::gpu::fence; +use crate::gpu::agility::configuration_interface; +use windows::Win32::Graphics::Direct3D12::{ID3D12Debug, CLSID_D3D12Debug}; /// Initial state of a kernel run. #[derive(Clone)] @@ -86,6 +88,12 @@ unsafe fn wait_for_submission( fn init() -> Result { unsafe { let factory: IDXGIFactory6 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).map_err(e)?; + // Enable debug layer BEFORE creating the device if XCL_D3D12_DEBUG is set + if std::env::var_os("XCL_D3D12_DEBUG").is_some() { + if let Ok(debug) = configuration_interface::(&CLSID_D3D12Debug) { + debug.EnableDebugLayer(); + } + } // `XCL_ADAPTER` picks the adapter (default: the first in high-performance order) let sel = crate::gpu::adapter::Selector::from_env_or("auto"); let (adapter, name): (IDXGIAdapter1, String) = if sel == crate::gpu::adapter::Selector::Warp { From e11ce9b7aa75766eea747d8f6d5ebfdd65dff92a Mon Sep 17 00:00:00 2001 From: Saurabh Bhoir Date: Wed, 25 Nov 2026 11:35:51 +0530 Subject: [PATCH 4/4] DirectStorage: count bytes/requests only on successful completion Fixes #2059: DirectStorage byte counter includes failed reads. The BYTES and REQUESTS atomic counters were incremented at the start of execute() via note_request(), but a request can fail after that point (access violation, decompression, zlib, write failures). This caused failed requests to be counted in the byte/request totals. Split note_request() into: - note_request(): logging only (called at start of execute) - note_request_success(n): increments REQUESTS/BYTES counters (called only after successful completion in both execute() and retire_one()) This ensures only successfully completed requests are counted. Co-Authored-By: Claude Code --- crates/xcl/src/hle/dstorage.rs | 12 ++++++++++-- crates/xcl/src/hle/dstorage/parallel.rs | 13 +++++++++---- 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/crates/xcl/src/hle/dstorage.rs b/crates/xcl/src/hle/dstorage.rs index 5dd9d2e708..fe73fab532 100644 --- a/crates/xcl/src/hle/dstorage.rs +++ b/crates/xcl/src/hle/dstorage.rs @@ -852,8 +852,6 @@ fn note_request(r: &Request) { // the first requests: where a title's data goes and how it is packed static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); let k = N.fetch_add(1, Ordering::Relaxed); - REQUESTS.fetch_add(1, Ordering::Relaxed); - BYTES.fetch_add(n as u64, Ordering::Relaxed); if k < 16 || k.is_power_of_two() { crate::xlog_info!( "DirectStorage: request #{k}: options {:#x} ({} source{}), destination {:#x}{} ({n} bytes, page offset {}), source size {}, intermediate {}", @@ -869,6 +867,12 @@ fn note_request(r: &Request) { } } +/// Called when a request completes successfully to record its bytes. +fn note_request_success(n: usize) { + REQUESTS.fetch_add(1, Ordering::Relaxed); + BYTES.fetch_add(n as u64, Ordering::Relaxed); +} + /// Run a request; the destination gets the bytes or nothing. unsafe fn execute(r: &Request, file: Option<&FileInner>, dest_pages: Option<&[usize]>, src_pages: Option<&[usize]>) -> Result<(), HRESULT> { let n = r.destination_size as usize; @@ -876,6 +880,8 @@ unsafe fn execute(r: &Request, file: Option<&FileInner>, dest_pages: Option<&[us if !r.dest_physical_pages() && !writable(r.destination as usize, n) { return Err(E_ACCESS_VIOLATION); } + // Requests that fail after this point will have their bytes/reqs counted in note_request_success + // only on successful completion let src: Vec = if r.memory_source() { let mut b = vec![0u8; r.source_size as usize]; if r.source_physical_pages() { @@ -953,6 +959,8 @@ unsafe fn execute(r: &Request, file: Option<&FileInner>, dest_pages: Option<&[us } else if n > 0 { std::ptr::copy_nonoverlapping(payload.as_ptr(), r.destination as *mut u8, n); } + // Record successful request only after all data has been written + note_request_success(n); Ok(()) } diff --git a/crates/xcl/src/hle/dstorage/parallel.rs b/crates/xcl/src/hle/dstorage/parallel.rs index 198f4a86e8..5dc0e97c7e 100644 --- a/crates/xcl/src/hle/dstorage/parallel.rs +++ b/crates/xcl/src/hle/dstorage/parallel.rs @@ -1,7 +1,7 @@ //! Bounded preparation of file-backed zlib requests. The queue thread owns //! file reads, cancellation checks, and retirement; decoders own private buffers. -use super::{note_request, read_exact_at, writable, Entry, FileInner, QueueInner, Request, E_ABORT, E_ACCESS_VIOLATION, E_FILE_HANDLE, E_ZLIB_DATA}; +use super::{note_request, note_request_success, read_exact_at, writable, Entry, FileInner, QueueInner, Request, E_ABORT, E_ACCESS_VIOLATION, E_FILE_HANDLE, E_ZLIB_DATA}; use crate::util::{HRESULT, S_OK}; use std::collections::{HashMap, VecDeque}; use std::ffi::c_void; @@ -463,13 +463,18 @@ impl<'a> Pipeline<'a> { // The title can unmap the destination while a decoder runs. The late // check resolves lazy pages, and the kernel copy handles a subsequent unmap. if writable(at, n) && (n == 0 || write_destination(at, &payload.bytes[..n])) { - Ok(()) + Ok(n) } else { Err(E_ACCESS_VIOLATION) } }); - if let Err(hr) = result { - self.queue.update_error(hr, task.req, task.file.as_deref(), since_status); + match result { + Ok(n) => { + note_request_success(n); + } + Err(hr) => { + self.queue.update_error(hr, task.req, task.file.as_deref(), since_status); + } } #[cfg(test)] notify_test(self.queue, TestEvent::Retired(task.seq));