From 5718395d2ff928c52cb9bff7a824a3c5bba1d09e Mon Sep 17 00:00:00 2001 From: KOLESNiii <102358205+KOLESNiii@users.noreply.github.com> Date: Thu, 26 Nov 2026 20:22:11 +0000 Subject: [PATCH] D3D12.X: KickoffX keeps a failed Close's effects and goes on with a closed list KickoffX took the list's pending waits, Write64 signals and CPU writes before the native Close. When Close failed they were gone, and the console list kept recording into (and later submitting) a PC list that can no longer be Reset. Kickoff of a console list now reserves a closed stand-in list (an idle spare, or one made on an allocator of its own) and the bookkeeping for it before it changes anything; without them it leaves the work to the title's Close + ExecuteCommandLists. The effects are taken only after Close succeeds. On failure the wrapper records into and submits the closed stand-in, the failed list is never reset, submitted or reused (the primary is marked broken, other lists are quarantined), and the title's next Reset reopens the stand-in and drops the abandoned recording's effects. The fail-closed bookkeeping in title_list is adapted from 617b493d and the Kickoff change from 73898793 (#2778), part of #2787 item 2. The new test drives kickoff_x with a native Close returning E_OUTOFMEMORY; on main it fails with the waits, signals and CPU writes all lost. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/list_x.rs | 215 ++++++++++++++++++++++-- crates/xcl/src/hle/d3d12x/title_list.rs | 103 +++++++++++- 2 files changed, 293 insertions(+), 25 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index ee544dec22..9f168f9382 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -722,6 +722,29 @@ impl ListState { } self.pending_waits.push(w); } + + /// What a `KickoffX` submits along with the list: taken only once its native Close has + /// succeeded, so a failed Close leaves them with the recording. + fn take_kickoff_effects(&mut self) -> KickoffEffects { + let waits = if self.pending_waits.is_empty() { + Vec::new() + } else { + PENDING_WAIT_LISTS.fetch_sub(1, Ordering::AcqRel); + std::mem::take(&mut self.pending_waits) + }; + let sparse_writes = self.clear_sparse_writes(); + let write64_signals = self.clear_write64_signals(); + self.written_ranges.clear(); + KickoffEffects { waits, sparse_writes, write64_signals, cpu_writes: std::mem::take(&mut self.cpu_writes) } + } +} + +#[derive(Default)] +struct KickoffEffects { + waits: Vec, + sparse_writes: Vec<(usize, usize)>, + write64_signals: Vec<(u64, u64)>, + cpu_writes: Vec, } #[derive(Clone, Copy)] @@ -2625,6 +2648,36 @@ pub(super) unsafe fn reset_stand_in(wrapper: *mut c_void, primary: *mut c_void, Some(spare as usize) } +/// A closed PC list of `wrapper`'s that does not record: an idle spare, or one made on an +/// allocator of its own (the list's allocator is recording the list itself) and closed at once. +unsafe fn reserve_closed_list(wrapper: *mut c_void, dev: &ID3D12Device, ty: D3D12_COMMAND_LIST_TYPE) -> Option<*mut c_void> { + if let Some(spare) = super::title_list::pop_spare(wrapper) { + clear_segment_state(spare as usize); + let mut g = LISTS.lock().unwrap(); + let s = g.get_or_insert_with(HashMap::new).entry(spare as usize).or_default(); + s.allocator = 0; + s.list_type = Some(ty); + return Some(spare); + } + let own: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).ok()?; + if !real::is_adopted(own.as_raw()) { + real::adopt(own.as_raw(), real::Kind::CommandAllocator); + } + let made = real::create_raw_pc_command_list(dev.as_raw(), ty, own.as_raw() as usize, 0)?; + super::alloc_pool::created_on(made as usize, own.as_raw() as usize, ty.0); + let ext = *(made as *const usize); + let hr = pc:: i32>(made, PC_CLOSE)(made); + real::preserve_vtable(made, ext); + if hr < 0 { + on_release(made as usize); + pc:: u32>(made, 2)(made); + return None; + } + // (no allocator of the title's: a KickoffX on it does nothing; its own outlives its commands) + LISTS.lock().unwrap().get_or_insert_with(HashMap::new).insert(made as usize, ListState { list_type: Some(ty), own_alloc: Some(own), ..Default::default() }); + Some(made) +} + /// Deferred mid-list split for `Wait32/64BitValueX` recorded after a `Write64BitValue*` in the /// same command list: closes `list` (preserving its earlier `Write64` signals on segment N) and /// opens/reuses a sibling PC command list on the same `ID3D12CommandAllocator` as segment N+1, @@ -3262,10 +3315,11 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { if ty == D3D12_COMMAND_LIST_TYPE_BUNDLE { return; } - let dev_raw = device_of(this).map_or(0, |d| d.as_raw() as usize); - let (alloc, queue, bound_pso, depth_bias, index_buffer, depth_bounds, predication, pred_buf, pred_in_state, active_query, waits, sparse_writes) = { - let mut g = LISTS.lock().unwrap(); - let Some(s) = g.as_mut().and_then(|m| m.get_mut(&(this as usize))) else { + let dev = device_of(this); + let dev_raw = dev.as_ref().map_or(0, |d| d.as_raw() as usize); + let (alloc, queue) = { + let g = LISTS.lock().unwrap(); + let Some(s) = g.as_ref().and_then(|m| m.get(&(this as usize))) else { if once(&NO_QUEUE, 4) { crate::xlog_info!("D3D12.X: KickoffX – list allocator unknown, deferring to Close + ExecuteCommandLists"); } @@ -3283,22 +3337,34 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { } return; }; - let active_query = s.occlusion.end_active_early(); - let waits = if s.pending_waits.is_empty() { - Vec::new() - } else { - PENDING_WAIT_LISTS.fetch_sub(1, Ordering::AcqRel); - std::mem::take(&mut s.pending_waits) + (s.allocator, q) + }; + // A failed native Close leaves the list unable to Reset: a console list's wrapper then needs + // a closed list to go on with. Get it (and the bookkeeping) before anything changes, or + // leave the work to the title's Close + ExecuteCommandLists. + let wrapper = super::title_list::wrapper_of(this); + let standby = match (wrapper, dev.as_ref()) { + (None, _) => None, + (Some(wrapper), Some(dev)) if super::title_list::prepare_fail_closed(wrapper) => match reserve_closed_list(wrapper, dev, ty) { + Some(standby) => Some((wrapper, standby)), + None => return warn(&ERR, "KickoffX", format_args!("no closed list to fall back on, deferring to Close + ExecuteCommandLists")), + }, + (Some(_), _) => return warn(&ERR, "KickoffX", format_args!("could not prepare for a failed Close, deferring to Close + ExecuteCommandLists")), + }; + let (bound_pso, depth_bias, index_buffer, depth_bounds, predication, pred_buf, pred_in_state, active_query) = { + let mut g = LISTS.lock().unwrap(); + let Some(s) = g.as_mut().and_then(|m| m.get_mut(&(this as usize))) else { + drop(g); + if let Some((wrapper, standby)) = standby { + super::title_list::put_spare(wrapper, standby); + } + return; }; - let sparse_writes = s.clear_sparse_writes(); - let write64_signals = s.clear_write64_signals(); - s.written_ranges.clear(); - let cpu_writes = std::mem::take(&mut s.cpu_writes); + let active_query = s.occlusion.end_active_early(); let pred_in_state = std::mem::replace(&mut s.pred_in_state, false); let pred_buf = s.pred_buf.as_ref().map(|r| r.as_raw() as usize); - (s.allocator, q, s.bound_pso, s.depth_bias, s.index_buffer, s.depth_bounds, s.predication, pred_buf, pred_in_state, active_query, waits, (sparse_writes, write64_signals, cpu_writes)) + (s.bound_pso, s.depth_bias, s.index_buffer, s.depth_bounds, s.predication, pred_buf, pred_in_state, active_query) }; - let (sparse_writes, write64_signals, cpu_writes) = sparse_writes; // End any active occlusion query before Close (PC forbids closing with an open query). if let Some(((h, i), qty)) = active_query { @@ -3314,9 +3380,16 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { let close_hr = pc:: i32>(this, PC_CLOSE)(this); real::preserve_vtable(this, ext); if close_hr < 0 { + // (the waits, writes and signals stay with the lost recording until the title's Reset) + if let Some((wrapper, standby)) = standby { + super::title_list::fail_closed(wrapper, this, standby); + } return warn(&ERR, "KickoffX", format_args!("Close failed ({close_hr:#x})")); } - if let Some(wrapper) = super::title_list::wrapper_of(this) { + let KickoffEffects { waits, sparse_writes, write64_signals, cpu_writes } = + LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(this as usize))).map(ListState::take_kickoff_effects).unwrap_or_default(); + if let Some((wrapper, standby)) = standby { + super::title_list::put_spare(wrapper, standby); record_deferred(wrapper); } @@ -7432,4 +7505,112 @@ mod tests { assert!(got.iter().all(|&v| v == 0xDEAD_BEEF), "the UAV was not cleared: {:x?}", &got[..4]); } } + + /// A PC list (or device) for `kickoff_x` without a GPU: `vt` is one past the slot holding + /// the PC vtable (`real::orig_fn` reads `vt[-1]`). + #[repr(C)] + struct KickoffFake { + vt: *const usize, + refs: u32, + resets: u32, + dev: usize, + } + + unsafe extern "system" fn kf_add_ref(this: *mut c_void) -> u32 { + (*(this as *mut KickoffFake)).refs += 1; + (*(this as *mut KickoffFake)).refs + } + unsafe extern "system" fn kf_release(this: *mut c_void) -> u32 { + (*(this as *mut KickoffFake)).refs -= 1; + (*(this as *mut KickoffFake)).refs + } + unsafe extern "system" fn kf_get_device(this: *mut c_void, _riid: *const windows::core::GUID, ppv: *mut *mut c_void) -> i32 { + let dev = (*(this as *mut KickoffFake)).dev as *mut c_void; + kf_add_ref(dev); + *ppv = dev; + 0 + } + unsafe extern "system" fn kf_type(_: *mut c_void) -> D3D12_COMMAND_LIST_TYPE { + D3D12_COMMAND_LIST_TYPE_DIRECT + } + unsafe extern "system" fn kf_close_out_of_memory(_: *mut c_void) -> i32 { + 0x8007_000Eu32 as i32 + } + unsafe extern "system" fn kf_reset(this: *mut c_void, _: usize, _: usize) -> i32 { + (*(this as *mut KickoffFake)).resets += 1; + 0 + } + + /// The native Close of a console list's KickoffX fails (#2787): the waits, Write64 signals + /// and CPU writes stay with the lost recording, which is never submitted, reset or reused; + /// the wrapper goes on with a closed list, which the title's Reset reopens, and the lost + /// recording's effects go with that Reset. + #[test] + fn kickoff_close_failure_keeps_effects_and_goes_on_with_a_closed_list() { + use super::super::title_list; + let mut pc_vt = vec![0usize; 16]; + pc_vt[2] = kf_release as usize; + pc_vt[PC_GET_TYPE] = kf_type as usize; + pc_vt[PC_CLOSE] = kf_close_out_of_memory as usize; + pc_vt[PC_RESET] = kf_reset as usize; + let mut ext = vec![0usize; 17]; + ext[0] = pc_vt.as_ptr() as usize; + ext[1 + 1] = kf_add_ref as usize; + ext[1 + 2] = kf_release as usize; + ext[1 + 7] = kf_get_device as usize; // ID3D12DeviceChild::GetDevice + let vt = ext[1..].as_ptr(); + let fake = |dev: usize| Box::into_raw(Box::new(KickoffFake { vt, refs: 1, resets: 0, dev })); + let device = fake(0); + let (primary, standby) = (fake(device as usize), fake(device as usize)); + let (p, sb) = (primary as *mut c_void, standby as *mut c_void); + let queue = 0x7ffe_6000usize; + on_queue_create(queue, device as usize, D3D12_COMMAND_LIST_TYPE_DIRECT); + let wait = PendingWait { va: 0x4000, width: 8, comparison: 3, value: 1, mask: u64::MAX, after_write64: false }; + { + let mut g = LISTS.lock().unwrap(); + let s = g.get_or_insert_with(HashMap::new).entry(p as usize).or_default(); + s.allocator = 0xa110; + s.list_type = Some(D3D12_COMMAND_LIST_TYPE_DIRECT); + s.push_wait(wait); + s.push_write64_signal(0x4100, 7); + s.cpu_writes.push(super::super::cpu_writes::Write::Immediate(0x4200, vec![1])); + } + unsafe { + let wrapper = title_list::wrap(p); + title_list::put_spare(wrapper, sb); + kickoff_x(p); + + let kept = |list: *mut c_void| { + let g = LISTS.lock().unwrap(); + let s = &g.as_ref().unwrap()[&(list as usize)]; + (s.pending_waits.clone(), s.write64_signals.clone(), s.cpu_writes.len()) + }; + assert_eq!(kept(p), (vec![wait], vec![(0x4100, 7)], 1), "a failed Close keeps the recording's effects"); + let mut segs = Vec::new(); + assert!(title_list::push_segments(wrapper, &mut segs)); + assert_eq!(segs, vec![sb], "only the closed list is submitted"); + assert_eq!(title_list::wrapper_of(sb), Some(wrapper)); + assert_eq!(title_list::wrapper_of(p), None); + assert_eq!(title_list::pop_spare(wrapper), None, "neither list is a spare"); + + // the title's Reset reopens the closed list, not the one whose Close failed + assert_eq!(title_list::reset(wrapper, 0xa110, 0), 0); + assert_eq!(((*primary).resets, (*standby).resets), (0, 1)); + assert_eq!(kept(p), (Vec::new(), Vec::new(), 0), "the abandoned recording's effects go at Reset"); + segs.clear(); + assert!(title_list::push_segments(wrapper, &mut segs)); + assert_eq!(segs, vec![sb]); + assert_eq!(title_list::wrapper_of(sb), Some(wrapper)); + + let rel: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*(*(wrapper as *const *const usize)).add(2)); + assert_eq!(rel(wrapper), 0); + assert_eq!(((*primary).refs, (*standby).refs, (*device).refs), (0, 0, 1)); + on_release(p as usize); + on_release(sb as usize); + on_queue_release(queue); + for f in [primary, standby, device] { + drop(Box::from_raw(f)); + } + } + } } diff --git a/crates/xcl/src/hle/d3d12x/title_list.rs b/crates/xcl/src/hle/d3d12x/title_list.rs index a41e5643fc..7ef65416ea 100644 --- a/crates/xcl/src/hle/d3d12x/title_list.rs +++ b/crates/xcl/src/hle/d3d12x/title_list.rs @@ -50,6 +50,14 @@ struct SegmentBook { /// finished primary's last submit, and the PC does not let a list be submitted again before /// that (#1452, debug layer id 553). A console does. first: Option, + /// A closed PC command list the wrapper records into (and submits) after a native Close of + /// its active list failed, until the title's next Reset. + failed: Option, + /// The primary's native Close failed: the PC cannot Reset it again, so every later recording + /// goes onto another PC list (`first`). + primary_broken: bool, + /// Lists other than the primary whose native Close failed: never reset, submitted or reused. + unresettable: Vec, } /// Wrapper address -> split segment book (populated lazily only for lists that split). @@ -154,13 +162,30 @@ unsafe extern "system" fn close(this: *mut c_void) -> HRESULT { pub(super) unsafe extern "system" fn reset(this: *mut c_void, alloc: usize, pso: usize) -> HRESULT { let primary = *((this as usize + F_PRIMARY) as *const *mut c_void); let adopted = super::real::is_adopted(primary); - let stand_in = if adopted && super::alloc_pool::in_flight(primary as usize) { + let (failed, primary_broken, first) = SEGMENTS + .lock() + .unwrap() + .as_ref() + .and_then(|m| m.get(&(this as usize))) + .map_or((None, false, None), |b| (b.failed, b.primary_broken, b.first)); + let idle = |p: usize| !super::alloc_pool::in_flight(p); + let stand_in = if let Some(failed) = failed.filter(|&p| idle(p)) { + (super::list_x::reset_pc(failed as *mut c_void, alloc, pso) >= 0).then_some(failed) + } else if primary_broken { + match first.filter(|&p| idle(p)) { + Some(first) => (super::list_x::reset_pc(first as *mut c_void, alloc, pso) >= 0).then_some(first), + None => super::list_x::reset_stand_in(this, primary, alloc, pso), + } + } else if adopted && !idle(primary as usize) { super::list_x::reset_stand_in(this, primary, alloc, pso) } else { None }; let hr = if stand_in.is_some() { 0 + } else if primary_broken { + // E_FAIL: the primary cannot record again and no other list could + 0x8000_4005u32 as HRESULT } else if adopted { super::list_x::reset_pc(primary, alloc, pso) } else { @@ -170,19 +195,32 @@ pub(super) unsafe extern "system" fn reset(this: *mut c_void, alloc: usize, pso: if hr >= 0 { let active = stand_in.unwrap_or(primary as usize); *((this as usize + F_BACKING) as *mut usize) = active; - let moved = { + let (moved, abandoned) = { let mut sg = SEGMENTS.lock().unwrap(); let m = sg.get_or_insert_with(HashMap::new); if stand_in.is_some() || m.contains_key(&(this as usize)) { let b = m.entry(this as usize).or_default(); let mut old = std::mem::take(&mut b.extra_active); - old.extend(std::mem::replace(&mut b.first, stand_in)); + old.extend(std::mem::replace(&mut b.first, stand_in).filter(|&p| Some(p) != stand_in)); + old.extend(b.failed.take().filter(|&p| Some(p) != stand_in)); b.spares.extend(old.iter().copied()); - old + // the recording whose Close failed is abandoned: its effects go with it + let mut abandoned = Vec::new(); + if failed.is_some() { + abandoned.extend(b.unresettable.iter().copied()); + if b.primary_broken { + abandoned.push(primary as usize); + } + } + (old, abandoned) } else { - Vec::new() + (Vec::new(), Vec::new()) } }; + for &seg in &abandoned { + super::bind::reset(seg as *mut c_void, 0, 0); + super::list_x::clear_segment_state(seg); + } if !moved.is_empty() || stand_in.is_some() { let mut wg = WRAPPER_OF.lock().unwrap(); let m = wg.get_or_insert_with(HashMap::new); @@ -252,6 +290,11 @@ pub fn push_segments(list: *mut c_void, out: &mut Vec<*mut c_void>) -> bool { }; let sg = SEGMENTS.lock().unwrap(); let book = sg.as_ref().and_then(|m| m.get(&(list as usize))); + // (after a failed Close only the closed stand-in runs: the failed recording is lost) + if let Some(failed) = book.and_then(|b| b.failed) { + out.push(failed as *mut c_void); + return true; + } out.push(book.and_then(|b| b.first).map_or(primary, |f| f as *mut c_void)); if let Some(book) = book { for &seg in &book.extra_active { @@ -274,7 +317,48 @@ pub(super) fn can_split(wrapper: *mut c_void, n: usize) -> bool { let sg = SEGMENTS.lock().unwrap(); sg.as_ref() .and_then(|m| m.get(&(wrapper as usize))) - .is_none_or(|b| b.extra_active.len() + n <= MAX_EXTRA_SEGMENTS) + .is_none_or(|b| b.failed.is_none() && b.extra_active.len() + n <= MAX_EXTRA_SEGMENTS) +} + +/// Reserve the bookkeeping `fail_closed` (or giving the stand-in back with `put_spare`) needs, +/// so neither allocates once the native Close has run. False after a failure until Reset. +pub(super) fn prepare_fail_closed(wrapper: *mut c_void) -> bool { + let mut sg = SEGMENTS.lock().unwrap(); + let m = sg.get_or_insert_with(HashMap::new); + if m.try_reserve(1).is_err() { + return false; + } + let b = m.entry(wrapper as usize).or_default(); + if b.failed.is_some() || b.spares.try_reserve(1).is_err() || b.unresettable.try_reserve(1).is_err() { + return false; + } + drop(sg); + WRAPPER_OF.lock().unwrap().get_or_insert_with(HashMap::new).try_reserve(1).is_ok() +} + +/// The native Close of `broken_pc`, `wrapper`'s active list, failed: the PC cannot Reset that +/// list again. Until the title's Reset, the wrapper records into and submits the closed +/// `closed_pc` instead, and `broken_pc` is never submitted or reused. +pub(super) unsafe fn fail_closed(wrapper: *mut c_void, broken_pc: *mut c_void, closed_pc: *mut c_void) { + *((wrapper as usize + F_BACKING) as *mut usize) = closed_pc as usize; + { + let mut sg = SEGMENTS.lock().unwrap(); + let b = sg.get_or_insert_with(HashMap::new).entry(wrapper as usize).or_default(); + b.failed = Some(closed_pc as usize); + if broken_pc as usize == *((wrapper as usize + F_PRIMARY) as *const usize) { + b.primary_broken = true; + } else { + b.extra_active.retain(|&p| p != broken_pc as usize); + if b.first == Some(broken_pc as usize) { + b.first = None; + } + b.unresettable.push(broken_pc as usize); + } + } + let mut wg = WRAPPER_OF.lock().unwrap(); + let m = wg.get_or_insert_with(HashMap::new); + m.remove(&(broken_pc as usize)); + m.insert(closed_pc as usize, wrapper as usize); } /// Pop a previously created closed extra PC command list from `wrapper`'s spare pool for reuse @@ -322,6 +406,9 @@ pub(super) unsafe fn reclaim_for_kickoff(active_pc: *mut c_void) -> Option<(*mut let wrapper = wrapper_of(active_pc)?; let mut sg = SEGMENTS.lock().unwrap(); let book = sg.as_mut().and_then(|m| m.get_mut(&(wrapper as usize)))?; + if book.failed.is_some() { + return None; + } let primary = book.first.map_or_else(|| *((wrapper as usize + F_PRIMARY) as *const *mut c_void), |f| f as *mut c_void); if primary == active_pc { return None; @@ -405,14 +492,14 @@ unsafe extern "system" fn release(this: *mut c_void) -> u32 { if let Some(m) = wg.as_mut() { m.remove(&(pc as usize)); if let Some(ref b) = book { - for &seg in b.extra_active.iter().chain(b.spares.iter()).chain(b.first.iter()) { + for &seg in b.extra_active.iter().chain(b.spares.iter()).chain(b.first.iter()).chain(b.failed.iter()).chain(b.unresettable.iter()) { m.remove(&seg); } } } } if let Some(b) = book { - for seg in b.extra_active.into_iter().chain(b.spares.into_iter()).chain(b.first) { + for seg in b.extra_active.into_iter().chain(b.spares.into_iter()).chain(b.first).chain(b.failed).chain(b.unresettable) { let raw = seg as *mut c_void; super::bind::forget(raw); let rel: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(pc_slot(raw, 2));