From f71cf2147ecd3b4aa67b71c53ebcd8cfec326c2b Mon Sep 17 00:00:00 2001 From: b3IKK <278540256+b3IKK@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:13:58 +0000 Subject: [PATCH] D3D12.X: a queue the title releases is not kept alive by submit tracking present::note_execute AddRef'd every queue a title submitted work to and never dropped that reference, so the queue's own Release never reached zero, q_release never ran, and every queue (and the driver memory behind it) lived on for the rest of the process. In the loop of #1668 - create, submit, synchronise, release, 128 times - CreateCommandQueue failed with E_OUTOFMEMORY on the 64th queue, while the same loop without a submit (the path that takes no reference) passed all 128. Drop the reference when a Release brings the count down to it (n == 1), clear the present candidate that names the queue, and drop the fence late_release keeps for it. The presenter now holds its own reference to the queue it makes a swap chain for, so that pointer cannot dangle once the title lets its queues go. A tracked queue can now be freed, so its readers no longer take raw pointers out of the list: late_release's drain and drain_gpu get their references from known_queues_held(), which takes them while the list is locked. A reader's reference either lands before the queue leaves the list - its release is then the one that lets the queue go - or the reader does not see the queue at all (review of #1691). A queue must outlive the work submitted to it, though: letting the reference go the moment the title does would free a queue the GPU is still executing, which ends in a device removal (0x887A0005, one run of six with this change merged onto main). The reference now goes to late_release, which signals a value on the queue's fence and drops it once every earlier submission has passed it - as it already does for a resource's last release. Assisted-by: OpenCode (Claude Fable 5.2) The late-release thread that lets a held resource or a released queue go is started once (`ensure_thread`), from either path: a title that does both must not start two. --- crates/xcl/src/hle/d3d12x/late_release.rs | 99 ++++++++++++++++-- crates/xcl/src/hle/d3d12x/present.rs | 42 ++++++++ crates/xcl/src/hle/d3d12x/real.rs | 122 +++++++++++++++++++++- 3 files changed, 248 insertions(+), 15 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/late_release.rs b/crates/xcl/src/hle/d3d12x/late_release.rs index 18ddc684e7..6adb980bd1 100644 --- a/crates/xcl/src/hle/d3d12x/late_release.rs +++ b/crates/xcl/src/hle/d3d12x/late_release.rs @@ -27,6 +27,14 @@ struct Batch { marks: Vec<(ID3D12Fence, u64)>, } +/// A queue the title released whose reference here waits for the work it already has: a queue +/// must outlive what was submitted to it, as a resource does. +struct ReleasedQueue { + queue: usize, + fence: ID3D12Fence, + value: u64, +} + #[derive(Default)] struct Held { /// queue → its fence here and the last value signalled on it @@ -34,6 +42,8 @@ struct Held { open: Vec, sealed: VecDeque, last_seal: Option, + /// queues let go by the title, still executing (`take_released_queues`) + queues: Vec, } // (the interface pointers are only used under the lock) @@ -41,7 +51,21 @@ unsafe impl Send for Held {} impl Held { fn is_empty(&self) -> bool { - self.open.is_empty() && self.sealed.is_empty() + self.open.is_empty() && self.sealed.is_empty() && self.queues.is_empty() + } + + /// The released queues whose last signal has passed: their reference goes now. + fn take_released_queues(&mut self) -> Vec { + let mut gone = Vec::new(); + self.queues.retain(|q| { + if unsafe { q.fence.GetCompletedValue() } >= q.value { + gone.push(q.queue); + false + } else { + true + } + }); + gone } /// Close the open batch (at most every `SEAL_EVERY`, or `seal_now`) with a fence value on each of `queues`, @@ -86,6 +110,53 @@ impl Held { static HELD: Mutex> = Mutex::new(None); +/// Forget the fence kept for a queue the title released: no batch may be waited on with it again +/// (a sealed batch holds its own clone), so its memory can go with the queue's (#1668). +pub fn forget_queue(queue: usize) { + if let Some(h) = HELD.lock().unwrap().as_mut() { + h.fences.remove(&queue); + } +} + +/// `queue` is down to the one reference the submit tracking holds and the title is done with it +/// (`q_release`). The GPU may still have work submitted to the queue, and a queue has to outlive +/// it: signal a value on the queue's fence and keep the reference until every earlier +/// submission has passed it, as a resource's last release is held. Returns whether the reference +/// was taken (false: late release is off, the caller drops it now, as before). +/// The queue must not be used after this: it has left `present`'s list and `late_release`'s. +pub unsafe fn hold_queue(queue: usize) -> bool { + if !enabled() { + return false; + } + let raw = queue as *mut c_void; + let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&raw) else { return false }; + let mut h = HELD.lock().unwrap(); + let held = h.get_or_insert_with(Held::default); + if !held.fences.contains_key(&queue) { + let mut dev: Option = None; + let made = q.GetDevice(&mut dev).ok().and(dev).and_then(|d| d.CreateFence::(0, D3D12_FENCE_FLAG_NONE).ok()); + let Some(f) = made else { return false }; + held.fences.insert(queue, (f, 0)); + } + let (fence, value) = held.fences.get_mut(&queue).unwrap(); + if q.Signal(&*fence, *value + 1).is_err() { + return false; + } + *value += 1; + let (fence, value) = (fence.clone(), *value); + held.fences.remove(&queue); + held.queues.push(ReleasedQueue { queue, fence, value }); + drop(h); + ensure_thread(); + true +} + +/// `#[cfg(test)]`: the released queues whose reference is still held. +#[cfg(test)] +pub fn held_queues() -> Vec { + HELD.lock().unwrap().as_ref().map_or_else(Vec::new, |h| h.queues.iter().map(|q| q.queue).collect()) +} + /// Whether last releases are held (`XCL_LATE_RELEASE=0` turns it off). pub fn enabled() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); @@ -113,6 +184,11 @@ pub unsafe fn hold(res: usize) { // A thread of its own lets the held ones go: the title may release a resource and then // wait for its memory without another submit (an imported heap pins the pages under its // resources – unmapping them stood still while one was held "until the next submit"). + ensure_thread(); +} + +/// The one thread that lets held resources and released queues go (`hold`, `hold_queue`). +fn ensure_thread() { static THREAD: std::sync::Once = std::sync::Once::new(); THREAD.call_once(|| { let _ = std::thread::Builder::new().name("xcl-late-release".into()).spawn(|| loop { @@ -128,24 +204,25 @@ pub unsafe fn drain_known(seal_now: bool) { if HELD.lock().unwrap().as_ref().is_none_or(Held::is_empty) { return; } - let mut queues: Vec = Vec::new(); - for raw in super::present::known_queues() { - let raw = raw as *mut c_void; - if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&raw) { - queues.push(q.clone()); - } - } + let mut queues: Vec = super::present::known_queues_held(); queues.extend(super::sparse::queue()); queues.extend(super::title_textures::upload_queues()); - let gone = match HELD.lock().unwrap().as_mut() { - Some(h) => h.drain(&queues, seal_now), - None => return, + let (gone, released) = { + let mut h = HELD.lock().unwrap(); + let Some(h) = h.as_mut() else { return }; + let gone = h.drain(&queues, seal_now); + (gone, h.take_released_queues()) }; // (outside the lock: a release may end other objects, whose releases come back here) for res in gone { 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); } + for q in released { + let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(super::real::orig_fn(q as *mut c_void, 2)); + f(q as *mut c_void); + super::list_x::on_queue_release(q); + } } #[cfg(test)] diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index 2958aa0e9b..d56fbcba67 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -247,6 +247,46 @@ pub fn known_queues() -> Vec { QUEUES.lock().unwrap().clone() } +/// The queues the title submitted work to, each with a reference of the caller's taken while it +/// is listed: `q_release` frees a queue the title lets go as soon as it has left the list, so a +/// pointer from [`known_queues`] may be freed before it is used (#1668). +pub fn known_queues_held() -> Vec { + let q = QUEUES.lock().unwrap(); + q.iter() + .filter_map(|&raw| { + let raw = raw as *mut c_void; + unsafe { ID3D12CommandQueue::from_raw_borrowed(&raw) }.cloned() + }) + .collect() +} + +/// `queue` is down to the one reference `note_execute` took to keep it valid for `late_release`: +/// the title is done with it. Forget it – and any use of it here – so the caller can let that +/// reference go: otherwise every queue a title ever submitted to (and the driver memory behind +/// it) stays allocated for the life of the process (#1668). +pub fn forget_queue(queue: usize) -> bool { + let tracked = { + let mut q = QUEUES.lock().unwrap(); + let at = q.iter().position(|&x| x == queue); + if let Some(at) = at { + q.remove(at); + } + at.is_some() + }; + // (a candidate for the window's present that is this queue: drop the resource it holds) + let dropped = { + let mut c = CANDIDATE.lock().unwrap(); + match *c { + Some((q, _)) if q == queue => c.take().map(|(_, r)| r), + _ => None, + } + }; + if let Some(r) = dropped { + unsafe { release(r) }; + } + tracked +} + static EXECUTES: AtomicU64 = AtomicU64::new(0); /// (PresentX calls, ExecuteCommandLists calls) so far @@ -672,6 +712,7 @@ unsafe fn new_presenter(queue: usize) -> Option { list.Close().ok()?; let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; let event = CreateEventW(None, false, false, None).ok()?; + add_ref(queue); // (a swap chain may still be made for it: the title's own reference is not ours) Some(Presenter { queue, dev: dev.clone(), sc: None, w: 0, h: 0, fmt: DXGI_FORMAT_UNKNOWN, alloc, spare_alloc, ring: PresentRing::new(actual_slots), @@ -1112,6 +1153,7 @@ impl Drop for Presenter { let _ = fence::wait(&self.fence, self.value, &self.dev, Some(self.event), 1000); } let _ = CloseHandle(self.event); + release(self.queue); } } } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 51016f38ad..f97d3b0390 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -6771,9 +6771,23 @@ unsafe extern "system" fn cl_release(this: *mut c_void) -> u32 { unsafe extern "system" fn q_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); + let mut n = f(this); if n == 0 { super::list_x::on_queue_release(this as usize); + } else if n == 1 && super::present::forget_queue(this as usize) { + // Only the reference `present` keeps (to fence what `late_release` holds) is left: the + // title is done with this queue, so it does not stay allocated for the life of the + // process, as it did before #1668. The GPU may still have work submitted to it, though, + // and a queue must outlive that: the reference goes once the queue's fence has passed + // its last signal – `late_release` holds it, as it holds a resource's last release. + super::late_release::forget_queue(this as usize); + if super::late_release::hold_queue(this as usize) { + return 1; + } + n = f(this); + if n == 0 { + super::list_x::on_queue_release(this as usize); + } } n } @@ -7046,9 +7060,7 @@ pub fn drain_gpu() { unsafe { // a fence per queue (they finish in any order) let mut fences = Vec::new(); - for q in super::present::known_queues() { - let qr = q as *mut c_void; - let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&qr) else { continue }; + for q in super::present::known_queues_held() { let submit = || { let f: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE) .map_err(|e| fence::api_error(dev, "CreateFence", e))?; @@ -7726,6 +7738,108 @@ mod console_format_query_tests { dev } + /// #1668: a title that submits work to a queue and then releases it leaves nothing of that + /// queue behind. `note_execute` keeps a reference so `late_release` can fence what it holds; + /// when the title's own last release brings the count down to that one, the reference goes + /// too – otherwise every queue the title ever submitted to stays allocated, and a loop of + /// them made `CreateCommandQueue` fail with `E_OUTOFMEMORY` after 63 of 128 (issue #1668). + #[test] + fn a_queue_the_title_releases_is_not_kept_alive_by_the_submit_tracking() { + unsafe { + let Some(dev) = device() else { return }; + let (raw, release) = submitted_queue(&dev); + // (not the count it returns: another test's `drain_known` may hold a reference of its + // own at this moment, and then its release is the one that lets the queue go) + release(raw); + assert!(untracked_soon(raw), "a queue let go is not tracked any more"); + } + } + + /// A reader of the tracked queues (`late_release`'s drain, `drain_gpu`) takes its references + /// while the queues are listed, so the title's last release cannot free one under it: the + /// queue stays – and stays listed – until the reader lets go, and goes then. + #[test] + fn a_tracked_queue_a_reader_holds_outlives_the_titles_release() { + unsafe { + let Some(dev) = device() else { return }; + let (raw, release) = submitted_queue(&dev); + let held = crate::hle::d3d12x::present::known_queues_held(); + assert!(held.iter().any(|q| q.as_raw() == raw), "the reader holds the tracked queue"); + assert!(release(raw) >= 2, "the reader's reference and the tracking's are left"); + assert!( + crate::hle::d3d12x::present::known_queues().contains(&(raw as usize)), + "a queue a reader still uses stays tracked" + ); + drop(held); + assert!(untracked_soon(raw), "the reader's release lets the queue go"); + } + } + + /// A queue the title releases is not destroyed while the GPU still has work submitted to it: + /// its reference here is held until the queue's fence has passed the last signal, as a + /// resource's last release is (#1691, the device loss @upipibi saw in one run of six with + /// this PR merged onto `main`). The queue here waits on a fence nobody has signalled yet. + #[test] + fn a_released_queue_is_held_until_its_submitted_work_is_done() { + unsafe { + let Some(dev) = device() else { return }; + let (raw, release) = submitted_queue(&dev); + let qraw = raw as *mut c_void; + let queue = ID3D12CommandQueue::from_raw_borrowed(&qraw).expect("the queue"); + let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("CreateFence"); + queue.Wait(&gate, 1).expect("Wait"); + assert!(release(raw) >= 1, "the tracking reference is not dropped on the title's release"); + assert!( + crate::hle::d3d12x::late_release::held_queues().contains(&(raw as usize)), + "the GPU may still run what was submitted to the queue: its reference is held" + ); + // (the queue is usable while `late_release` holds it: it is alive, not gone) + assert_eq!(queue.GetDesc().Type, D3D12_COMMAND_LIST_TYPE_DIRECT, "the held queue is alive"); + // the work completes, and then the reference goes + let signaller: ID3D12CommandQueue = dev + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }) + .expect("CreateCommandQueue"); + signaller.Signal(&gate, 1).expect("Signal"); + let end = std::time::Instant::now() + std::time::Duration::from_secs(5); + while crate::hle::d3d12x::late_release::held_queues().contains(&(raw as usize)) { + assert!(std::time::Instant::now() < end, "the queue is let go once its work is done"); + std::thread::sleep(std::time::Duration::from_millis(5)); + } + } + } + + /// A queue adopted as the title's, with work submitted to it: its pointer – the title's one + /// reference – and its (hooked) `Release`. + unsafe fn submitted_queue(dev: &ID3D12Device) -> (*mut c_void, unsafe extern "system" fn(*mut c_void) -> u32) { + let queue: ID3D12CommandQueue = dev + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }) + .expect("CreateCommandQueue"); + let raw = queue.as_raw() as *mut c_void; + std::mem::forget(queue); // (the only reference left is the title's) + super::adopt(raw, Kind::CommandQueue); + crate::hle::d3d12x::present::note_execute(raw, &[]); + assert!( + crate::hle::d3d12x::present::known_queues().contains(&(raw as usize)), + "a queue work was submitted to is tracked, for late_release to fence" + ); + (raw, std::mem::transmute(*(*(raw as *const *mut usize)).add(2))) + } + + /// Whether `queue` leaves the tracked queues (within 5 s: a reader in another test may hold + /// it for a moment). + fn untracked_soon(queue: *mut c_void) -> bool { + let end = std::time::Instant::now() + std::time::Duration::from_secs(5); + loop { + if !crate::hle::d3d12x::present::known_queues().contains(&(queue as usize)) { + return true; + } + if std::time::Instant::now() >= end { + return false; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + } + /// CheckFeatureSupport of the PC device as `dev_check_feature_support` reaches it (vtable #13). fn pc_check(dev: &ID3D12Device) -> CheckFeatureSupportFn { unsafe { std::mem::transmute(*(*(dev.as_raw() as *const *const usize)).add(13)) }