From d783592c5c72e22267cd4e607f699fea2d61000e Mon Sep 17 00:00:00 2001 From: Pipodi Date: Sun, 29 Nov 2026 09:47:55 +0100 Subject: [PATCH] D3D12.X: leave releases made inside a list Reset to the late-release thread With XCL_DRED=1 a retail title stalled: main d8bd9a38 stalled 2 of 2 runs (the earlier main fa204595 3 of 4); without DRED 0 of 3 stalled. Two threads deadlocked. The title thread takes a queue's submit lease (readback after execute) and waits in CCommandAllocator::Reset on D3D12Core's allocator lock. The recording thread, inside a native list Reset that holds that lock, has D3D12Core release DRED's breadcrumb buffer, which enters late_release::hold; its drain_known signals the queues and waits for the lease the title thread holds. A thread-local guard (InListReset) is set around the native Reset in alloc_pool::reset_list and in the cl_reset hook (XCL's own list Resets do not go through reset_list). While it is set, hold treats the release as busy and leaves it to the late-release thread. That alone is not enough: drain_known held HELD across Held::drain, whose native_queue_signal takes the lease, so another drain_known caller could wait for the lease with HELD locked, and the guarded hold would block on HELD. The drain is now split: begin_seal (under HELD) takes the open batch out and reserves fence values, the signals are made with HELD unlocked, end_seal relocks to push the batch (or put it back in order if a signal failed). Because the signals are no longer under the lock, two seals could interleave and the (non-FIFO) leases could order their signals wrongly: only one seal runs at a time, and a batch in flight counts as held (is_empty), so a pinned hold still waits for its release. A seal skipped because another is under way leaves the batch open for the next one. Measured with XCL_DRED=1 on the same title (150 s, RTX 4090): this commit 0 of 3 runs stalled, main d8bd9a38 2 of 2. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/alloc_pool.rs | 7 +- crates/xcl/src/hle/d3d12x/late_release.rs | 251 +++++++++++++++++++--- crates/xcl/src/hle/d3d12x/real.rs | 5 +- 3 files changed, 228 insertions(+), 35 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs index b115958321..bbb56bdc3f 100644 --- a/crates/xcl/src/hle/d3d12x/alloc_pool.rs +++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs @@ -958,7 +958,10 @@ pub(super) fn forget_list(list: usize) { /// only after native Reset succeeds. No pool lock is held across the driver call. pub fn reset_list(list: usize, alloc: usize, ty: i32, reset: impl FnOnce(usize) -> HRESULT) -> HRESULT { let backing = current(alloc); - let hr = reset(backing); + let hr = { + let _in_reset = super::late_release::InListReset::enter(); + reset(backing) + }; if hr < 0 || !enabled() || alloc == 0 { return hr; } @@ -2259,8 +2262,10 @@ mod tests { assert!(reset, "the reserved backing is put aside instead of Reset"); assert_eq!(reset_list(list, alloc, -1, |backing| { assert_eq!(backing, next); + assert!(crate::hle::d3d12x::late_release::in_list_reset(), "the native Reset runs with the guard set"); 0 }), 0); + assert!(!crate::hle::d3d12x::late_release::in_list_reset(), "and it is cleared after"); let second = begin_submit(&[list as *mut c_void]).unwrap().execution_possible(); first.finish_with_mark(0x71, &fence, 3); diff --git a/crates/xcl/src/hle/d3d12x/late_release.rs b/crates/xcl/src/hle/d3d12x/late_release.rs index 18987b3647..1c17726248 100644 --- a/crates/xcl/src/hle/d3d12x/late_release.rs +++ b/crates/xcl/src/hle/d3d12x/late_release.rs @@ -49,6 +49,8 @@ struct Held { open: Vec, sealed: VecDeque, last_seal: Option, + /// a batch is being closed (its signals are made with the lock released) + sealing: bool, } // (the interface pointers are only used under the lock) @@ -56,47 +58,89 @@ 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.sealing } - /// 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: what to release now. - 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; - for q in queues { - let key = q.as_raw() as usize; - if !self.fences.contains_key(&key) { - 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 { - ok = false; - break; - }; - self.fences.insert(key, (f, 0)); - } - let (fence, value) = self.fences.get_mut(&key).unwrap(); - if super::real::native_queue_signal(q, &*fence, *value + 1).is_err() { - ok = false; - break; - } - *value += 1; - marks.push((fence.clone(), *value)); - } - // (no fence or no signal: the device is gone – the batch stays open, and held) - if ok { - self.last_seal = Some(Instant::now()); - let dead = std::mem::take(&mut self.open); - self.sealed.push_back(Batch { dead, marks }); + /// Close the open batch (at most every `SEAL_EVERY`, or `seal_now`): take it out, and reserve a fence + /// value on each of `queues`. The signals themselves are not made here: a `Signal` takes the queue's + /// submit lease, and nothing that waits for a lease may run under `HELD` (the thread that holds the + /// lease may be waiting for a release that needs `HELD`). One batch is closed at a time (the + /// leases are not FIFO: signals of two seals could reach a queue in the wrong order); the open + /// batch waits for the next seal. `None`: nothing to close, another seal under way, or no fence. + unsafe fn begin_seal(&mut self, queues: &[ID3D12CommandQueue], seal_now: bool) -> Option { + if !seal_due(self.open.is_empty(), self.sealing, seal_now, self.last_seal.map(|t| t.elapsed())) { + return None; + } + let mut signals = Vec::with_capacity(queues.len()); + for q in queues { + let key = q.as_raw() as usize; + if !self.fences.contains_key(&key) { + 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()); + // (no fence: the device is gone – the batch stays open, and held) + self.fences.insert(key, (made?, 0)); } + let (fence, value) = self.fences.get_mut(&key).unwrap(); + // (a value whose signal fails is never used: a later one passes it) + *value += 1; + signals.push((q.clone(), fence.clone(), *value)); } + // (taken now: what is released after this is not behind the signals) + let seal = Seal { dead: std::mem::take(&mut self.open), signals, was_sealed: self.last_seal }; + self.last_seal = Some(Instant::now()); + self.sealing = true; + Some(seal) + } + + /// The signals of `seal` were made (`ok`) or not (the batch goes back to the open one). + fn end_seal(&mut self, seal: Seal, ok: bool) { + self.sealing = false; + if ok { + let marks = seal.signals.into_iter().map(|(_, f, v)| (f, v)).collect(); + self.sealed.push_back(Batch { dead: seal.dead, marks }); + } else { + self.last_seal = seal.was_sealed; + self.open.splice(0..0, seal.dead); + } + } + + /// Take out the batches every queue is past: what to release now. + unsafe fn take_gone(&mut self) -> Vec { let mut gone = Vec::new(); while self.sealed.front().is_some_and(|b| b.marks.iter().all(|(f, v)| super::real::fence_completed(&f) >= *v)) { gone.extend(self.sealed.pop_front().unwrap().dead); } gone } + + /// `begin_seal`, the signals, `end_seal` and `take_gone` in one, for a `Held` nobody else uses. + #[cfg(test)] + unsafe fn drain(&mut self, queues: &[ID3D12CommandQueue], seal_now: bool) -> Vec { + if let Some(seal) = self.begin_seal(queues, seal_now) { + let ok = seal.signal(); + self.end_seal(seal, ok); + } + self.take_gone() + } +} + +/// Whether the open batch is closed now: there is one, no other seal is under way, and it is +/// `seal_now` or the last seal is `SEAL_EVERY` back. +fn seal_due(open_is_empty: bool, sealing: bool, seal_now: bool, since_last: Option) -> bool { + !open_is_empty && !sealing && (seal_now || since_last.is_none_or(|t| t >= SEAL_EVERY)) +} + +/// A batch being closed: `signals` (queue, fence, value) are made outside the lock. +struct Seal { + dead: Vec, + signals: Vec<(ID3D12CommandQueue, ID3D12Fence, u64)>, + was_sealed: Option, +} + +impl Seal { + unsafe fn signal(&self) -> bool { + self.signals.iter().all(|(q, f, v)| super::real::native_queue_signal(q, f, *v).is_ok()) + } } static HELD: Mutex> = Mutex::new(None); @@ -140,6 +184,37 @@ impl Busy { static BUSY: Busy = Busy(Mutex::new(None)); +thread_local! { + static IN_LIST_RESET: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Set while this thread is inside a native command list `Reset`. D3D12Core holds its allocator/list +/// lock there and may release objects (DRED's breadcrumb buffer) into `hold`; a look at the queues +/// would take a queue's submit lease, which a thread waiting on that same lock holds. Releases made +/// there are left to the late-release thread. +pub(super) struct InListReset(bool); + +impl InListReset { + pub(super) fn enter() -> Self { + Self(IN_LIST_RESET.with(|c| c.replace(true))) + } +} + +impl Drop for InListReset { + fn drop(&mut self) { + IN_LIST_RESET.with(|c| c.set(self.0)); + } +} + +pub(super) fn in_list_reset() -> bool { + IN_LIST_RESET.with(|c| c.get()) +} + +/// Whether `hold` leaves the release to the thread without a look at the queues. +fn leaves_to_thread(pinned: bool, queues_busy: bool, in_list_reset: bool) -> bool { + !pinned || queues_busy || in_list_reset +} + /// `res` (an adopted resource) holds one reference that is now this module's. With `pinned` (it may /// be over pages that are freed next) and 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 @@ -148,7 +223,7 @@ static BUSY: Busy = Busy(Mutex::new(None)); pub unsafe fn hold(res: usize, pinned: bool) { HELD.lock().unwrap().get_or_insert_with(Held::default).open.push(Dead::Resource(res)); let start = Instant::now(); - let busy = !pinned || BUSY.is(start); + let busy = leaves_to_thread(pinned, BUSY.is(start), in_list_reset()); if !busy { drain_known(true); while start.elapsed() < IDLE_WAIT && HELD.lock().unwrap().as_ref().is_some_and(|h| !h.is_empty()) { @@ -235,8 +310,19 @@ pub unsafe fn drain_known(seal_now: bool) { let mut queues = super::present::active_queues_held(); queues.extend(super::sparse::queue()); queues.extend(super::title_textures::upload_queues()); + // (the signals are made with `HELD` unlocked: they take the queues' submit leases) + let seal = match HELD.lock().unwrap().as_mut() { + Some(h) => h.begin_seal(&queues, seal_now), + None => return, + }; + if let Some(seal) = seal { + let ok = seal.signal(); + if let Some(h) = HELD.lock().unwrap().as_mut() { + h.end_seal(seal, ok); + } + } let gone = match HELD.lock().unwrap().as_mut() { - Some(h) => h.drain(&queues, seal_now), + Some(h) => h.take_gone(), None => return, }; // (outside the lock: a release may end other objects, whose releases come back here) @@ -342,6 +428,28 @@ mod tests { assert!(busy.is(t + BUSY_FOR + BUSY_FOR / 2)); } + /// A release made inside a native list Reset is left to the thread: a look at the queues there + /// takes a submit lease that a thread waiting on the Reset's lock may hold. + #[test] + fn a_release_inside_a_list_reset_is_left_to_the_thread() { + assert!(!leaves_to_thread(true, false, false), "pinned, idle queues, outside a Reset: looked at"); + assert!(leaves_to_thread(true, false, true), "inside a Reset: left to the thread"); + assert!(leaves_to_thread(false, false, false) && leaves_to_thread(true, true, false)); + assert!(!in_list_reset()); + { + let _outer = InListReset::enter(); + assert!(in_list_reset()); + drop(InListReset::enter()); + assert!(in_list_reset(), "a nested guard restores the outer state"); + } + assert!(!in_list_reset()); + let r = std::panic::catch_unwind(|| { + let _g = InListReset::enter(); + panic!("inside"); + }); + assert!(r.is_err() && !in_list_reset(), "a panic does not leave it set"); + } + /// With no queue at all nothing can be in flight: the next drain lets the batch go. #[test] fn without_queues_a_batch_goes_at_once() { @@ -382,4 +490,81 @@ mod tests { assert_eq!(fake.refs.load(Ordering::SeqCst), 0, "released once the queues are past"); hold_pipeline(0); } + + /// Inside a native list Reset `hold` makes no look at the queues: the last release is not made on + /// the calling thread (the late-release thread lets it go, at its own time). + #[test] + fn hold_inside_a_list_reset_leaves_the_release_to_the_thread() { + use std::sync::atomic::AtomicU32; + use std::thread::ThreadId; + #[repr(C)] + struct Fake { + vt: *const usize, + refs: AtomicU32, + released_on: Mutex>, + } + unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 { + (*(this as *const Fake)).refs.fetch_add(1, Ordering::SeqCst) + 1 + } + unsafe extern "system" fn release(this: *mut c_void) -> u32 { + let f = &*(this as *const Fake); + *f.released_on.lock().unwrap() = Some(std::thread::current().id()); + f.refs.fetch_sub(1, Ordering::SeqCst) - 1 + } + // (an adopted object: the original table sits before the one the object points at) + let orig = [0usize, add_ref as usize, release as usize]; + let ext = [orig.as_ptr() as usize, 0, 0, 0]; + let fake = Box::new(Fake { vt: unsafe { ext.as_ptr().add(1) }, refs: AtomicU32::new(1), released_on: Mutex::new(None) }); + let p = &*fake as *const Fake as usize; + { + let _in_reset = InListReset::enter(); + unsafe { hold(p, true) }; + } + assert_ne!(*fake.released_on.lock().unwrap(), Some(std::thread::current().id()), "not released by the caller"); + let start = Instant::now(); + while fake.refs.load(Ordering::SeqCst) != 0 && start.elapsed() < Duration::from_secs(10) { + std::thread::sleep(Duration::from_millis(5)); + } + assert_eq!(fake.refs.load(Ordering::SeqCst), 0, "the thread lets it go"); + assert_ne!(*fake.released_on.lock().unwrap(), Some(std::thread::current().id())); + } + + /// Closing a batch takes the open one out (what is released meanwhile is behind later signals), + /// and a batch whose signals failed goes back, in order. + #[test] + fn a_batch_whose_signals_failed_goes_back_in_order() { + let mut held = Held::default(); + held.open.push(Dead::Resource(0x1000)); + let seal = unsafe { held.begin_seal(&[], true) }.expect("a batch to close"); + assert!(held.open.is_empty() && held.sealed.is_empty()); + held.open.push(Dead::Resource(0x2000)); + held.end_seal(seal, false); + assert_eq!(held.open, vec![Dead::Resource(0x1000), Dead::Resource(0x2000)], "back, in order"); + assert!(held.sealed.is_empty()); + let seal = unsafe { held.begin_seal(&[], true) }.unwrap(); + held.end_seal(seal, true); + assert!(held.open.is_empty() && held.sealed.len() == 1); + assert!(unsafe { held.begin_seal(&[], true) }.is_none(), "nothing open"); + } + + /// A batch in the middle of its seal still counts as held (a pinned `hold` waits for it), and + /// only one seal runs at a time: the open batch waits for the next one. + #[test] + fn a_seal_in_flight_counts_as_held_and_is_the_only_one() { + let mut held = Held::default(); + held.open.push(Dead::Resource(0x1000)); + let seal = unsafe { held.begin_seal(&[], true) }.unwrap(); + assert!(held.open.is_empty() && held.sealed.is_empty()); + assert!(!held.is_empty(), "the batch in the seal is not lost to is_empty"); + held.open.push(Dead::Resource(0x2000)); + assert!(unsafe { held.begin_seal(&[], true) }.is_none(), "no second seal at once"); + assert_eq!(held.open, vec![Dead::Resource(0x2000)], "left open for the next one"); + held.end_seal(seal, true); + assert!(!held.is_empty()); + let seal = unsafe { held.begin_seal(&[], true) }.expect("free again"); + held.end_seal(seal, true); + assert!(!seal_due(true, false, true, None) && !seal_due(false, true, true, None)); + assert!(seal_due(false, false, true, Some(Duration::ZERO))); + assert!(!seal_due(false, false, false, Some(Duration::ZERO)) && seal_due(false, false, false, Some(SEAL_EVERY))); + } } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index eafeccd069..cac203cd94 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -4140,7 +4140,10 @@ unsafe extern "system" fn cl_reset(this: *mut c_void, allocator: *mut c_void, in std::mem::transmute(orig_fn(this, pc_slot!("ID3D12GraphicsCommandList", "Reset"))); let prepared = super::bind::PreparedNativePipeline::new(initial_state as usize); let resolved = prepared.raw(); - let hr = f(this, allocator, resolved as *mut c_void); + let hr = { + let _in_reset = super::late_release::InListReset::enter(); + f(this, allocator, resolved as *mut c_void) + }; preserve_vtable(this, ext); if hr >= 0 { if !super::title_textures::is_own_work() && !super::present::presenting() {