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 { diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 9241a3a18d..50f4727d13 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,31 @@ 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: keep the entry (and its block) so the last buffer's + // Release can free the block when live_buffers reaches zero. + } } } } 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));