From d0ebe34473f3668b1ed9a58bbd2294cbbbed90c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9?= <153442863+DTsordas@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:10:24 +0200 Subject: [PATCH] D3D12.X: a held resource keeps its memory until its Release goes 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 #1040 Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/uma.rs | 12 +++ crates/xcl/src/hle/d3d12x/late_release.rs | 109 +++++++++++++++++++--- crates/xcl/src/hle/d3d12x/real.rs | 73 ++++++++++++++- crates/xcl/src/hle/d3d12x/sparse.rs | 60 +++++++++--- 4 files changed, 227 insertions(+), 27 deletions(-) diff --git a/crates/xcl/src/gpu/uma.rs b/crates/xcl/src/gpu/uma.rs index 82eac9e534..5fec87ed74 100644 --- a/crates/xcl/src/gpu/uma.rs +++ b/crates/xcl/src/gpu/uma.rs @@ -603,6 +603,18 @@ impl Uma { true } + /// Whether `p` is a block handed out and not freed since (tests). + #[cfg(test)] + pub fn is_allocated(&self, p: usize) -> bool { + { + let g = self.pool.lock().unwrap(); + if p >= g.0 && p < g.1 { + return !g.2.contains(&p); + } + } + p.checked_sub(self.base).is_some_and(|off| self.inner.lock().unwrap().used.contains_key(&off)) + } + /// Bytes handed out. pub fn used(&self) -> usize { self.inner.lock().unwrap().used.values().sum() diff --git a/crates/xcl/src/hle/d3d12x/late_release.rs b/crates/xcl/src/hle/d3d12x/late_release.rs index 18ddc684e7..fcb43b1d7e 100644 --- a/crates/xcl/src/hle/d3d12x/late_release.rs +++ b/crates/xcl/src/hle/d3d12x/late_release.rs @@ -21,8 +21,12 @@ const SEAL_EVERY: Duration = Duration::from_millis(10); /// how often the thread here looks for batches that can go const TICK: Duration = Duration::from_millis(4); +/// A held resource and the unified-memory or sparse-VRAM block XCL placed under it (given back +/// when it goes: until then the queues may still use it). +type Dead = (usize, Option); + struct Batch { - dead: Vec, + dead: Vec, /// (fence, value) a queue: all reached = nothing submitted before the batch closed is left marks: Vec<(ID3D12Fence, u64)>, } @@ -31,7 +35,7 @@ struct Batch { struct Held { /// queue → its fence here and the last value signalled on it fences: HashMap, - open: Vec, + open: Vec, sealed: VecDeque, last_seal: Option, } @@ -46,7 +50,7 @@ impl Held { /// Close the open batch (at most every `SEAL_EVERY`, or `seal_now`) with a fence value on each of `queues`, /// and take out the batches every queue is past: the resources to release now. - unsafe fn drain(&mut self, queues: &[ID3D12CommandQueue], seal_now: bool) -> Vec { + unsafe fn drain(&mut self, queues: &[ID3D12CommandQueue], seal_now: bool) -> Vec { if !self.open.is_empty() && (seal_now || self.last_seal.is_none_or(|t| t.elapsed() >= SEAL_EVERY)) { let mut marks = Vec::with_capacity(queues.len()); let mut ok = true; @@ -82,6 +86,11 @@ impl Held { } gone } + + /// `dead`, which every queue is past already, go at the next drain. + fn again(&mut self, dead: Vec) { + self.sealed.push_front(Batch { dead, marks: Vec::new() }); + } } static HELD: Mutex> = Mutex::new(None); @@ -96,11 +105,12 @@ pub fn enabled() -> bool { const IDLE_WAIT: Duration = Duration::from_micros(300); /// `res` (an adopted resource) holds one reference that is now this module's. With no work in -/// flight it goes before this returns (the queues pass a fence value at once): a title that -/// frees the memory under a resource right after its last `Release` finds it unpinned, as -/// before. Otherwise the thread here lets it go. -pub unsafe fn hold(res: usize) { - HELD.lock().unwrap().get_or_insert_with(Held::default).open.push(res); +/// flight it goes before this returns (the queues pass a fence value at once; unless the sparse +/// state is busy): a title that frees the memory under a resource right after its last +/// `Release` finds it unpinned, as before. Otherwise the thread here lets it go. `memory`: the +/// block XCL placed under it, given back (and its sparse tiles unpinned) only when it goes. +pub unsafe fn hold(res: usize, memory: Option) { + HELD.lock().unwrap().get_or_insert_with(Held::default).open.push((res, memory)); let start = Instant::now(); drain_known(true); while start.elapsed() < IDLE_WAIT && HELD.lock().unwrap().as_ref().is_some_and(|h| !h.is_empty()) { @@ -142,10 +152,36 @@ pub unsafe fn drain_known(seal_now: bool) { None => return, }; // (outside the lock: a release may end other objects, whose releases come back here) - for res in gone { + let later = let_go(gone); + if !later.is_empty() { + if let Some(h) = HELD.lock().unwrap().as_mut() { + h.again(later); + } + } +} + +/// Release `gone`, which the queues are past, with their tiles and memory – except those the +/// sparse state is busy for: returned, to go at a later drain. +unsafe fn let_go(gone: Vec) -> Vec { + let mut later = Vec::new(); + for (res, memory) in gone { + // its tiles and a sparse block under it go first, while it is still alive (its address + // is no other resource's yet), and without waiting for the sparse state: a drain runs + // where the state's holder can be waiting for this thread + if !super::sparse::try_forget_held(res, memory) { + later.push((res, memory)); + continue; + } let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(super::real::orig_fn(res as *mut c_void, 2)); f(res as *mut c_void); + // a block in a coherent window after it + if let (Some(p), Some(u)) = (memory, crate::gpu::uma::get()) { + if !u.is_sparse(p) { + u.free(p); + } + } } + later } #[cfg(test)] @@ -180,7 +216,7 @@ mod tests { let raw = res.unwrap().into_raw() as usize; let mut held = Held::default(); - held.open.push(raw); + held.open.push((raw, None)); let queues = [queue.clone()]; assert!(held.drain(&queues, false).is_empty(), "the queue has not passed the batch's fence value"); std::thread::sleep(Duration::from_millis(100)); @@ -194,7 +230,7 @@ mod tests { std::thread::sleep(Duration::from_millis(5)); gone = held.drain(&queues, false); } - assert_eq!(gone, vec![raw], "released once the queue is past the batch"); + assert_eq!(gone, vec![(raw, None)], "released once the queue is past the batch"); assert!(held.is_empty()); drop(ID3D12Resource::from_raw(raw as *mut c_void)); } @@ -204,8 +240,55 @@ mod tests { #[test] fn without_queues_a_batch_goes_at_once() { let mut held = Held::default(); - held.open.push(0x1000); - assert_eq!(unsafe { held.drain(&[], false) }, vec![0x1000]); + held.open.push((0x1000, Some(0x2000))); + assert_eq!(unsafe { held.drain(&[], false) }, vec![(0x1000, Some(0x2000))]); assert!(held.is_empty()); } + + /// Letting held resources go does not wait for the sparse state's lock: a drain runs inside + /// XCL's own submit while that thread holds the lock (an upload going out on a queue whose + /// submits are hooked), and inside D3D12 calls the lock's holder can wait for. The resource + /// is kept for a later drain instead. + #[test] + fn letting_go_does_not_wait_for_the_sparse_state() { + let locked = super::super::sparse::lock_for_test(); + let (tx, rx) = std::sync::mpsc::channel(); + let drain = std::thread::spawn(move || { + let _ = tx.send(unsafe { let_go(vec![(0x1000, None)]) }); + }); + let answered = rx.recv_timeout(Duration::from_secs(5)); + drop(locked); + drain.join().unwrap(); + assert_eq!(answered.ok(), Some(vec![(0x1000, None)]), "the drain waited for the sparse state's lock"); + } + + /// A resource put back (the sparse state was busy) goes at the next drain, ahead of a batch a + /// queue has not got past. + #[test] + fn a_resource_put_back_goes_at_the_next_drain() { + unsafe { + let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); + let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.Wait(&gate, 1).unwrap(); + let queues = [queue.clone()]; + + let mut held = Held::default(); + held.open.push((0x1000, None)); + assert!(held.drain(&queues, true).is_empty(), "the queue has not passed the batch's fence value"); + held.again(vec![(0x2000, None)]); + assert_eq!(held.drain(&queues, false), vec![(0x2000, None)], "put back: goes at the next drain"); + assert!(!held.is_empty(), "the batch the queue has not passed stays"); + + gate.Signal(1).unwrap(); + let start = Instant::now(); + while !held.is_empty() && start.elapsed() < Duration::from_secs(10) { + std::thread::sleep(Duration::from_millis(5)); + held.drain(&queues, false); + } + assert!(held.is_empty()); + } + } } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 5b01e85692..77d13cc560 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -1563,6 +1563,7 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { } else { f(this) }; + let mut memory = None; if n == 0 { if let Some(s) = UNMAPPABLE.lock().unwrap().as_mut() { s.remove(&(this as usize)); @@ -1576,12 +1577,18 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { if let Some(m) = TITLE_ADDRESS.lock().unwrap().as_mut() { m.remove(&(this as usize)); } - super::sparse::forget_buffer(this as usize); + // a held resource's tiles stay pinned until it goes (`late_release`) + if !held { + super::sparse::forget_buffer(this as usize); + } 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) { + if held { + // its memory goes with it: a queue may still be using it + memory = Some(p); + } else if u.is_sparse(p) { super::sparse::free(p); } else { u.free(p); @@ -1589,7 +1596,7 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { } } if held { - super::late_release::hold(this as usize); + super::late_release::hold(this as usize, memory); } n } @@ -5765,3 +5772,63 @@ mod console_format_query_tests { } } } + +#[cfg(test)] +mod held_release_tests { + use super::*; + use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + + /// A resource whose last `Release` is held (a queue still has work) keeps the unified memory + /// XCL placed under it until the hold ends: given back at the title's `Release`, the block + /// could go to the next allocation while the GPU still used it. + #[test] + fn a_held_resource_keeps_its_unified_memory_until_it_goes() { + unsafe { + if !super::super::late_release::enabled() { + return; + } + let Ok(dev) = crate::gpu::agility::create_device(None, D3D_FEATURE_LEVEL_11_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + let Some(u) = crate::gpu::uma::get() else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + // a queue with work in flight (it waits for a fence nobody has signalled yet) that + // the title has submitted to: late release waits for the queues it knows + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); + let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.Wait(&gate, 1).unwrap(); + super::super::present::note_execute(queue.as_raw(), &[]); + + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 4096, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut res: Option = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut res).unwrap(); + let raw = res.unwrap().into_raw(); + adopt(raw, Kind::Resource); + // the block XCL placed under it, recorded as `place_console_buffer` does + let p = u.alloc(0x1_0000, crate::gpu::uma::GRAIN).expect("unified memory") as usize; + UMA_BUFFERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(raw as usize, (p, 0x1_0000, true)); + + // 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 under a held resource went back while a queue still had work"); + + gate.Signal(1).unwrap(); + 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)); + } + assert!(!u.is_allocated(p), "the block goes back once the held resource goes"); + } + } +} diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 91b8a2e0d4..44720a8a51 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -1201,6 +1201,11 @@ pub unsafe fn alloc_in(window: usize, size: usize, align: usize) -> Option<(usiz /// Release a sparse allocation from `alloc` / `alloc_in` (false: not a sparse allocation). pub unsafe fn free(p: usize) -> bool { + free_with(p, |a, n| decommitted(a, n)) +} + +/// `free`, telling the state about the decommit through `decommit`. +unsafe fn free_with(p: usize, decommit: impl FnOnce(usize, usize)) -> bool { let Some(u) = crate::gpu::uma::get() else { return false }; if !u.is_sparse(p) { return false; @@ -1208,7 +1213,7 @@ pub unsafe fn free(p: usize) -> bool { // decommitted before the address goes back: once released, another thread may get it, // commit it and write there let Some((start, len)) = u.sparse_reservation(p).filter(|&(start, _)| start == p) else { return false }; - decommitted(start, len); + decommit(start, len); VirtualFree(p as *mut c_void, len, MEM_DECOMMIT); u.sparse_release(p).is_some() } @@ -1318,7 +1323,11 @@ pub unsafe fn decommitted(a: usize, n: usize) { if n == 0 { return; } - let mut g = STATE.lock().unwrap(); + decommitted_in(&mut STATE.lock().unwrap(), a, n); +} + +/// `decommitted` with the state's lock held (`g`). +unsafe fn decommitted_in(g: &mut Option, a: usize, n: usize) { let Some(s) = g.as_mut() else { let (start, end) = page_span(a, n); early_remove(&mut EARLY.lock().unwrap(), start, end); @@ -1576,15 +1585,44 @@ pub unsafe fn place_buffer(this: *mut c_void, va: usize, desc: &D3D12_RESOURCE_D /// A placed buffer is gone: its tiles are not pinned by it any more. pub fn forget_buffer(res: usize) { - let mut g = STATE.lock().unwrap(); - let Some(s) = g.as_mut() else { return }; - let Some(tiles) = s.buffers.remove(&res) else { return }; - for tile in tiles { - if let Some(c) = s.pinned.get_mut(&tile) { - *c -= 1; - if *c == 0 { - s.pinned.remove(&tile); - s.release_if_unused(tile); + if let Some(s) = STATE.lock().unwrap().as_mut() { + s.forget_buffer(res); + } +} + +/// `forget_buffer(res)`, and `free(block)` when `block` is a sparse block, for a resource whose +/// last `Release` `late_release` held – only if the state's lock is free right now (false: +/// nothing was done, ask again later). The late-release drain runs where the lock's holder can +/// be waiting for this thread: inside a D3D12 call that made a resource's last `Release`, or +/// inside XCL's own submit while the state is locked. +pub unsafe fn try_forget_held(res: usize, block: Option) -> bool { + let Ok(mut g) = STATE.try_lock() else { return false }; + if let Some(s) = g.as_mut() { + s.forget_buffer(res); + } + if let Some(p) = block { + free_with(p, |a, n| decommitted_in(&mut g, a, n)); + } + true +} + +/// The state's lock, held by a test (as XCL's own uploads hold it). +#[cfg(test)] +pub(super) fn lock_for_test() -> impl Sized { + STATE.lock().unwrap_or_else(|e| e.into_inner()) +} + +impl State { + /// `forget_buffer` with the state locked + fn forget_buffer(&mut self, res: usize) { + let Some(tiles) = self.buffers.remove(&res) else { return }; + for tile in tiles { + if let Some(c) = self.pinned.get_mut(&tile) { + *c -= 1; + if *c == 0 { + self.pinned.remove(&tile); + self.release_if_unused(tile); + } } } }