diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs index 8b81b85913..eaade12616 100644 --- a/crates/xcl/src/hle/d3d12x/alloc_pool.rs +++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs @@ -15,7 +15,7 @@ //! one recording, so no more allocators are put aside than there are lists. use std::collections::{HashMap, HashSet}; use std::ffi::c_void; -use std::sync::Mutex; +use std::sync::{Condvar, Mutex}; use windows::core::Interface; use windows::Win32::Graphics::Direct3D12::*; @@ -28,11 +28,15 @@ struct Backing { users: HashSet, /// queue → (fence, value after the last submit of one of them) marks: HashMap, + /// true once this backing has been PC-reset while idle and no new recording/submit has touched it + already_reset: bool, + /// true while a thread is running `reset_pc_allocator` on this backing outside `STATE` + resetting: bool, } impl Backing { unsafe fn free(&self) -> bool { - self.users.is_empty() && self.marks.values().all(|(f, v)| f.GetCompletedValue() >= *v) + !self.resetting && self.users.is_empty() && self.marks.values().all(|(f, v)| f.GetCompletedValue() >= *v) } } @@ -54,6 +58,17 @@ struct State { /// PC list → recordings so far (a Reset or creation starts the next one) recordings: HashMap, resubmits: u64, + /// Busy backings retained past `forget(alloc)` until their remaining users detach and GPU marks complete. + orphaned: Vec, +} + +struct OrphanedBacking { + /// Native PC allocator handle detached from `s.backings` on `forget(alloc)` so future + /// address reuse of `backing` never collides with this retired backing. + backing: usize, + /// True for XCL-created PC allocators (`backing != alloc`), which must be COM-released once idle. + owned: bool, + state: Backing, } struct LastSubmit { @@ -66,6 +81,7 @@ struct LastSubmit { unsafe impl Send for State {} static STATE: Mutex> = Mutex::new(None); +static RESET_DONE: Condvar = Condvar::new(); /// `XCL_ALLOC_SWAP=0` turns it off. pub fn enabled() -> bool { @@ -73,6 +89,58 @@ pub fn enabled() -> bool { *ON.get_or_init(|| !std::env::var("XCL_ALLOC_SWAP").is_ok_and(|v| v.trim() == "0")) } +fn detach_from_orphans(s: &mut State, list: usize) { + for o in &mut s.orphaned { + o.state.users.remove(&list); + } +} + +fn finish_reset_flag(s: &mut State, backing: usize, ok: bool) { + if let Some(b) = s.backings.get_mut(&backing) { + b.resetting = false; + if ok { + b.marks.clear(); + b.already_reset = true; + } + } + for o in &mut s.orphaned { + if o.backing == backing && o.state.resetting { + o.state.resetting = false; + if ok { + o.state.marks.clear(); + o.state.already_reset = true; + } + } + } +} + +unsafe fn take_free_orphaned(s: &mut State) -> (Vec, Vec) { + let mut made = Vec::new(); + let mut free_backings = Vec::new(); + let mut i = 0; + while i < s.orphaned.len() { + if s.orphaned[i].state.free() { + let o = s.orphaned.swap_remove(i); + free_backings.push(o.backing); + if o.owned { + made.push(o.backing); + } + } else { + i += 1; + } + } + (made, free_backings) +} + +unsafe fn finish_reclaimed(made: Vec, free_backings: Vec) { + for b in free_backings { + super::console_list::allocator_reset(b as *mut c_void); + } + for b in made { + drop(ID3D12CommandAllocator::from_raw(b as *mut c_void)); + } +} + fn move_list(s: &mut State, list: usize, backing: usize) { if let Some(old) = s.of_list.insert(list, backing) { if old != backing { @@ -81,38 +149,145 @@ fn move_list(s: &mut State, list: usize, backing: usize) { } } } - s.backings.entry(backing).or_default().users.insert(list); + detach_from_orphans(s, list); + let b = s.backings.entry(backing).or_default(); + b.users.insert(list); + b.already_reset = false; +} + +/// A split segment or stand-in PC list has been retired into `title_list`'s spare pool (or +/// superseded by a new recording on `wrapper`): it will not be submitted again until a future +/// `Reset` binds it to a new backing. Removing it from `users` lets its old backing become +/// reusable once its already-submitted GPU `marks` complete, while keeping `last_submit` so +/// `in_flight(list)` still prevents premature reuse. +pub(super) fn retire_recording(list: usize) { + let (made, free_backings) = { + let mut g = STATE.lock().unwrap(); + let Some(s) = g.as_mut() else { return }; + if let Some(backing) = s.of_list.remove(&list) { + if let Some(b) = s.backings.get_mut(&backing) { + b.users.remove(&list); + } + } + detach_from_orphans(s, list); + unsafe { take_free_orphaned(s) } + }; + unsafe { finish_reclaimed(made, free_backings) }; } /// The PC list's final Release ended its recording. Submitted work still holds the backing /// through `marks`; removing the list must not remove those fences or the other users. pub(super) fn forget_list(list: usize) { - let mut g = STATE.lock().unwrap(); - let Some(s) = g.as_mut() else { return }; - s.last_submit.remove(&list); - s.recordings.remove(&list); - if let Some(backing) = s.of_list.remove(&list) { - if let Some(b) = s.backings.get_mut(&backing) { - b.users.remove(&list); + let (made, free_backings) = { + let mut g = STATE.lock().unwrap(); + let Some(s) = g.as_mut() else { return }; + s.last_submit.remove(&list); + s.recordings.remove(&list); + if let Some(backing) = s.of_list.remove(&list) { + if let Some(b) = s.backings.get_mut(&backing) { + b.users.remove(&list); + } } - } + detach_from_orphans(s, list); + unsafe { take_free_orphaned(s) } + }; + unsafe { finish_reclaimed(made, free_backings) }; } -/// Reset `list` on the title's allocator `alloc`, committing its new recording association -/// 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); - if hr < 0 || !enabled() || alloc == 0 { - return hr; +fn try_reserve_backing(s: &mut State, list: usize, alloc: usize, ty: i32) -> Option<(usize, Option)> { + let backing = s.cur.get(&alloc).copied().unwrap_or(alloc); + if s.backings.get(&backing).is_some_and(|b| b.resetting) { + return None; } - let mut g = STATE.lock().unwrap(); - let s = g.get_or_insert_with(State::default); + let prev = s.of_list.get(&list).copied(); if ty >= 0 { s.types.insert(alloc, ty); } - move_list(s, list, backing); + // Pin `backing` against concurrent `title_reset` while keeping `list` pinned in `prev` + // (and `s.of_list[list] == prev`) until native `Reset(backing)` succeeds. + s.backings.entry(backing).or_default().users.insert(list); + Some((backing, prev)) +} + +fn commit_backing(s: &mut State, list: usize, backing: usize, prev: Option) { + if let Some(old) = prev { + if old != backing { + if let Some(b) = s.backings.get_mut(&old) { + b.users.remove(&list); + } + } + } + let mut orphaned_backing = false; + for o in &mut s.orphaned { + if o.backing == backing && o.state.users.contains(&list) { + o.state.already_reset = false; + orphaned_backing = true; + } else { + o.state.users.remove(&list); + } + } + if orphaned_backing { + // `backing` was moved to `s.orphaned` by a concurrent `forget(alloc)` mid-`reset_list`: + // keep `list` pinned on its orphan and do not recreate a zombie `s.backings` entry. + s.of_list.remove(&list); + } else { + s.of_list.insert(list, backing); + let b = s.backings.entry(backing).or_default(); + b.users.insert(list); + b.already_reset = false; + } *s.recordings.entry(list).or_default() += 1; +} + +fn rollback_backing(s: &mut State, list: usize, backing: usize, prev: Option) { + // Only release the temporary reservation on `backing`; `prev` was never detached. + if prev != Some(backing) { + if let Some(b) = s.backings.get_mut(&backing) { + b.users.remove(&list); + } + for o in &mut s.orphaned { + if o.backing == backing { + o.state.users.remove(&list); + } + } + } +} + +/// Reset `list` on the title's allocator `alloc`, reserving the target backing before native Reset +/// without detaching the previous recording until Reset succeeds so a concurrent `title_reset` +/// cannot reset either backing mid-call. 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 { + if !enabled() || alloc == 0 { + return reset(alloc); + } + let (backing, prev) = { + let mut g = STATE.lock().unwrap(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + loop { + let s = g.get_or_insert_with(State::default); + if let Some(r) = try_reserve_backing(s, list, alloc, ty) { + break r; + } + let now = std::time::Instant::now(); + if now >= deadline { + return crate::util::E_FAIL; + } + let (ng, _) = RESET_DONE.wait_timeout(g, deadline - now).unwrap(); + g = ng; + } + }; + let hr = reset(backing); + let (made, free_backings) = { + let mut g = STATE.lock().unwrap(); + let s = g.get_or_insert_with(State::default); + if hr >= 0 { + commit_backing(s, list, backing, prev); + } else { + rollback_backing(s, list, backing, prev); + } + unsafe { take_free_orphaned(s) } + }; + unsafe { finish_reclaimed(made, free_backings) }; hr } @@ -210,11 +385,17 @@ pub unsafe fn executed(queue: *mut c_void, lists: &[*mut c_void]) { (f.clone(), *v) }; for &l in lists { - if let Some(&b) = s.of_list.get(&(l as usize)) { - s.backings.entry(b).or_default().marks.insert(key, (fence.clone(), value)); + let l_key = l as usize; + if let Some(o) = s.orphaned.iter_mut().find(|o| o.state.users.contains(&l_key)) { + o.state.marks.insert(key, (fence.clone(), value)); + o.state.already_reset = false; + } else if let Some(&b) = s.of_list.get(&l_key) { + let entry = s.backings.entry(b).or_default(); + entry.marks.insert(key, (fence.clone(), value)); + entry.already_reset = false; } - let recording = s.recordings.get(&(l as usize)).copied().unwrap_or(0); - s.last_submit.insert(l as usize, LastSubmit { queue: key, fence: fence.clone(), value, recording }); + let recording = s.recordings.get(&l_key).copied().unwrap_or(0); + s.last_submit.insert(l_key, LastSubmit { queue: key, fence: fence.clone(), value, recording }); } } @@ -231,71 +412,342 @@ pub(super) unsafe fn allocator_in_flight(alloc: usize) -> bool { /// allocator may get its address, and must not go on with this one's PC allocators. The ones /// made here go with it (those lists still record on are left alone: not freed, not tracked). pub unsafe fn forget(alloc: usize) { - let made: Vec = { + let (made, free_backings): (Vec, Vec) = { let mut g = STATE.lock().unwrap(); - let Some(s) = g.as_mut() else { return }; + let Some(s) = g.as_mut() else { + drop(g); + super::console_list::allocator_reset(alloc as *mut c_void); + return; + }; s.types.remove(&alloc); let mut mine: Vec = s.aside.remove(&alloc).unwrap_or_default(); mine.extend(s.cur.remove(&alloc)); mine.push(alloc); + mine.sort_unstable(); + mine.dedup(); let mut made = Vec::new(); + let mut free_backings = Vec::new(); for b in mine { - let free = s.backings.get(&b).is_none_or(|x| x.free()); - if let Some(gone) = s.backings.remove(&b) { - for l in gone.users { - s.of_list.remove(&l); + match s.backings.remove(&b) { + Some(busy) if !busy.free() => { + // Detach busy backing from `s.backings` so address reuse of `b` cannot + // collide, while preserving its users/marks until safe reclamation. + for &l in &busy.users { + if s.of_list.get(&l) == Some(&b) { + s.of_list.remove(&l); + } + } + s.orphaned.push(OrphanedBacking { backing: b, owned: b != alloc, state: busy }); + } + _ => { + free_backings.push(b); + if b != alloc { + made.push(b); + } } - } - if b != alloc && free { - made.push(b); } } - made + let (o_made, o_free) = take_free_orphaned(s); + made.extend(o_made); + free_backings.extend(o_free); + (made, free_backings) }; - // (outside the lock: their Release comes back here) - for b in made { - drop(ID3D12CommandAllocator::from_raw(b as *mut c_void)); + // (outside the lock: UMA frees and Release callbacks must not re-enter STATE) + finish_reclaimed(made, free_backings); +} + +/// Pop idle put-aside backings of title allocator `a` whose lists and GPU work have finished +/// so the caller can reset them OUTSIDE `STATE` (preventing re-entrant deadlocks if resetting +/// an allocator drops a prelude `ID3D12CommandAllocator` whose `Release` calls `forget`). +unsafe fn take_free_aside(s: &mut State, a: usize) -> Vec { + let Some(v) = s.aside.get_mut(&a) else { + return Vec::new(); + }; + let mut ready = Vec::new(); + let mut i = 0; + while i < v.len() { + let f = v[i]; + if s.backings.get(&f).is_some_and(|b| !b.already_reset && b.free()) { + ready.push(v.remove(i)); + s.backings.entry(f).or_default().resetting = true; + } else { + i += 1; + } + } + ready +} + +unsafe fn restore_aside(s: &mut State, a: usize, f: usize, ok: bool) -> bool { + finish_reset_flag(s, f, ok); + RESET_DONE.notify_all(); + if s.types.contains_key(&a) { + s.aside.entry(a).or_default().push(f); + true + } else { + s.backings.remove(&f); + false } } /// The title resets its allocator `alloc`. `None`: reset it as it is (nothing holds a /// recording on it, or this is off). `Some(hr)`: done here – the PC allocator in use was put /// aside with its recordings and another one took its place. +/// +/// Releases `STATE` before every `reset_pc_allocator` call so COM callbacks triggered while +/// releasing per-allocator resources (e.g. prelude `ID3D12CommandAllocator::Release` -> `forget`) +/// can never self-deadlock on `STATE`. pub unsafe fn title_reset(alloc: *mut c_void) -> Option { if !enabled() { return None; } - let mut g = STATE.lock().unwrap(); - let s = g.get_or_insert_with(State::default); - title_reset_in(s, alloc, |raw| super::real::reset_pc_allocator(raw)) + let a = alloc as usize; + enum Action { + CleanPrimary { aside: Vec }, + ResetCurrent { cur: usize, aside: Vec }, + SwapReuse { cur: usize, spare: usize, needs_reset: bool, aside: Vec }, + SwapNew { cur: usize, ty: i32, aside: Vec }, + } + let action = { + let mut g = STATE.lock().unwrap(); + let s = g.get_or_insert_with(State::default); + let c = s.cur.get(&a).copied().unwrap_or(a); + if s.backings.get(&c).is_none_or(|b| b.free()) { + let aside = take_free_aside(s, a); + s.backings.entry(c).or_default().resetting = true; + if c == a { + Action::CleanPrimary { aside } + } else { + Action::ResetCurrent { cur: c, aside } + } + } else { + let ty = *s.types.get(&a)?; + let reuse_idx = s.aside.get(&a).and_then(|v| v.iter().position(|f| s.backings.get(f).is_none_or(|b| b.free()))); + match reuse_idx { + Some(idx) => { + let spare = s.aside.get_mut(&a).unwrap().remove(idx); + let needs_reset = s.backings.get(&spare).is_none_or(|b| !b.already_reset); + if needs_reset { + s.backings.entry(spare).or_default().resetting = true; + } + let aside = take_free_aside(s, a); + Action::SwapReuse { cur: c, spare, needs_reset, aside } + } + None => { + let aside = take_free_aside(s, a); + Action::SwapNew { cur: c, ty, aside } + } + } + } + }; + + let finish_aside = |aside: Vec| { + if aside.is_empty() { + return; + } + let mut results = Vec::with_capacity(aside.len()); + for f in aside { + let hr = super::real::reset_pc_allocator(f as *mut c_void); + results.push((f, hr >= 0)); + } + let mut orphans = Vec::new(); + let (o_made, o_free) = { + let mut g = STATE.lock().unwrap(); + if let Some(s) = g.as_mut() { + for (f, ok) in results { + if !restore_aside(s, a, f, ok) && f != a { + orphans.push(f); + } + } + take_free_orphaned(s) + } else { + (Vec::new(), Vec::new()) + } + }; + finish_reclaimed(o_made, o_free); + for f in orphans { + drop(ID3D12CommandAllocator::from_raw(f as *mut c_void)); + } + }; + + match action { + Action::CleanPrimary { aside } => { + let hr = super::real::reset_pc_allocator(alloc); + let (o_made, o_free) = { + let mut g = STATE.lock().unwrap(); + if let Some(s) = g.as_mut() { + finish_reset_flag(s, a, hr >= 0); + take_free_orphaned(s) + } else { + (Vec::new(), Vec::new()) + } + }; + RESET_DONE.notify_all(); + finish_reclaimed(o_made, o_free); + finish_aside(aside); + Some(hr) + } + Action::ResetCurrent { cur, aside } => { + let hr = super::real::reset_pc_allocator(cur as *mut c_void); + let mut orphan = None; + let (o_made, o_free) = { + let mut g = STATE.lock().unwrap(); + if let Some(s) = g.as_mut() { + finish_reset_flag(s, cur, hr >= 0); + if !s.types.contains_key(&a) && cur != a && !s.orphaned.iter().any(|o| o.backing == cur) { + orphan = Some(cur); + } + take_free_orphaned(s) + } else { + (Vec::new(), Vec::new()) + } + }; + RESET_DONE.notify_all(); + finish_reclaimed(o_made, o_free); + if let Some(f) = orphan { + drop(ID3D12CommandAllocator::from_raw(f as *mut c_void)); + } + finish_aside(aside); + Some(hr) + } + Action::SwapReuse { cur, spare, needs_reset, aside } => { + let hr = if needs_reset { super::real::reset_pc_allocator(spare as *mut c_void) } else { 0 }; + let mut orphan = None; + let (o_made, o_free) = { + let mut g = STATE.lock().unwrap(); + if let Some(s) = g.as_mut() { + if hr < 0 { + if !restore_aside(s, a, spare, false) && spare != a && !s.orphaned.iter().any(|o| o.backing == spare) { + orphan = Some(spare); + } + } else { + finish_reset_flag(s, spare, true); + if s.types.contains_key(&a) { + s.aside.entry(a).or_default().push(cur); + s.cur.insert(a, spare); + s.swaps += 1; + if s.swaps.is_power_of_two() { + let aside_n: usize = s.aside.values().map(|v| v.len()).sum(); + crate::xlog_info!( + "D3D12.X: {} allocator resets so far with recordings still held or on the GPU – another PC allocator took its place ({} made, {aside_n} put aside now)", + s.swaps, + s.made + ); + } + } else if spare != a && !s.orphaned.iter().any(|o| o.backing == spare) { + s.backings.remove(&spare); + orphan = Some(spare); + } + } + take_free_orphaned(s) + } else { + (Vec::new(), Vec::new()) + } + }; + RESET_DONE.notify_all(); + finish_reclaimed(o_made, o_free); + if let Some(f) = orphan { + drop(ID3D12CommandAllocator::from_raw(f as *mut c_void)); + } + finish_aside(aside); + Some(hr) + } + Action::SwapNew { cur, ty, aside } => { + let made = ID3D12CommandAllocator::from_raw_borrowed(&alloc).and_then(|this| { + let mut dev: Option = None; + this.GetDevice(&mut dev).ok()?; + dev?.CreateCommandAllocator::(D3D12_COMMAND_LIST_TYPE(ty)).ok() + }); + let Some(made) = made else { + finish_aside(aside); + return None; + }; + let raw = made.into_raw(); + if !super::real::is_adopted(raw) { + super::real::adopt(raw, super::real::Kind::CommandAllocator); + } + let mut orphan = None; + { + let mut g = STATE.lock().unwrap(); + if let Some(s) = g.as_mut() { + if s.types.contains_key(&a) { + s.made += 1; + s.aside.entry(a).or_default().push(cur); + s.cur.insert(a, raw as usize); + s.swaps += 1; + if s.swaps.is_power_of_two() { + let aside_n: usize = s.aside.values().map(|v| v.len()).sum(); + crate::xlog_info!( + "D3D12.X: {} allocator resets so far with recordings still held or on the GPU – another PC allocator took its place ({} made, {aside_n} put aside now)", + s.swaps, + s.made + ); + } + } else { + orphan = Some(raw as usize); + } + } + } + if let Some(f) = orphan { + drop(ID3D12CommandAllocator::from_raw(f as *mut c_void)); + } + finish_aside(aside); + Some(0) + } + } +} + +/// Reset idle put-aside backings of title allocator `a` whose lists and GPU work have finished +/// (used by lock-free unit tests via `title_reset_in`). +#[cfg(test)] +unsafe fn reclaim_free_aside(s: &mut State, a: usize, reset: &mut impl FnMut(*mut c_void) -> HRESULT) { + let ready = take_free_aside(s, a); + for f in ready { + let ok = reset(f as *mut c_void) >= 0; + let _ = restore_aside(s, a, f, ok); + } } /// The allocator transition, with the PC Reset supplied so failure/retry needs no GPU in tests. +#[cfg(test)] unsafe fn title_reset_in(s: &mut State, alloc: *mut c_void, mut reset: impl FnMut(*mut c_void) -> HRESULT) -> Option { let a = alloc as usize; let c = s.cur.get(&a).copied().unwrap_or(a); if s.backings.get(&c).is_none_or(|b| b.free()) { - if let Some(b) = s.backings.get_mut(&c) { - b.marks.clear(); - } + #[cfg(test)] + reclaim_free_aside(s, a, &mut reset); if c == a { + if let Some(b) = s.backings.get_mut(&c) { + b.marks.clear(); + b.already_reset = true; + } return None; } - return Some(reset(c as *mut c_void)); + let hr = reset(c as *mut c_void); + if hr >= 0 { + if let Some(b) = s.backings.get_mut(&c) { + b.marks.clear(); + b.already_reset = true; + } + } + return Some(hr); } let ty = *s.types.get(&a)?; // one put aside earlier that nothing uses any more, or a new one let reuse = s.aside.get(&a).and_then(|v| v.iter().copied().find(|f| s.backings.get(f).is_none_or(|b| b.free()))); let next = match reuse { Some(f) => { - // Keep ownership until Reset succeeds so a failure can be retried. - let hr = reset(f as *mut c_void); - if hr < 0 { - return Some(hr); + let needs = s.backings.get(&f).is_none_or(|b| !b.already_reset); + if needs { + // Keep ownership until Reset succeeds so a failure can be retried. + let hr = reset(f as *mut c_void); + if hr < 0 { + return Some(hr); + } } s.aside.get_mut(&a).unwrap().retain(|&x| x != f); if let Some(b) = s.backings.get_mut(&f) { b.marks.clear(); + b.already_reset = true; } f } @@ -315,6 +767,8 @@ unsafe fn title_reset_in(s: &mut State, alloc: *mut c_void, mut reset: impl FnMu }; s.aside.entry(a).or_default().push(c); s.cur.insert(a, next); + #[cfg(test)] + reclaim_free_aside(s, a, &mut reset); s.swaps += 1; if s.swaps.is_power_of_two() { let aside: usize = s.aside.values().map(|v| v.len()).sum(); @@ -550,4 +1004,410 @@ mod tests { assert_eq!(after_forget, 0, "a forgotten list has no previous submit"); } } + + #[test] + fn retired_segment_releases_backing_after_gpu_completes_while_preserving_in_flight() { + 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 fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let mut ids = Box::new([0u8; 3]); + let alloc = ids.as_mut_ptr() as usize; + let seg = alloc + 1; + let queue = alloc + 2; + created_on(seg, alloc, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + { + let mut g = STATE.lock().unwrap(); + let s = g.as_mut().unwrap(); + s.backings.entry(alloc).or_default().marks.insert(queue, (fence.clone(), 1)); + let recording = s.recordings[&seg]; + s.last_submit.insert(seg, LastSubmit { queue, fence: fence.clone(), value: 1, recording }); + } + + // Retiring the segment into `title_list`'s spare pool detaches it from `users` + // while keeping GPU fence `marks` and `in_flight(seg)` intact until completion. + retire_recording(seg); + assert!(in_flight(seg), "retired segment must stay in_flight until GPU finishes"); + { + let g = STATE.lock().unwrap(); + let b = &g.as_ref().unwrap().backings[&alloc]; + assert!(b.users.is_empty(), "retired segment must no longer pin backing.users"); + assert!(!b.free(), "GPU mark must still hold the backing until signaled"); + } + + fence.Signal(1).unwrap(); + assert!(!in_flight(seg)); + { + let g = STATE.lock().unwrap(); + assert!(g.as_ref().unwrap().backings[&alloc].free(), "backing must become free once GPU completes"); + } + forget_list(seg); + forget(alloc); + } + } + + #[test] + fn clean_title_reset_reclaims_idle_aside_backings_once() { + let (alloc, spare1, spare2) = (0x7E57_1000usize, 0x7E57_2000usize, 0x7E57_3000usize); + let mut s = State::default(); + s.types.insert(alloc, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + s.aside.insert(alloc, vec![spare1, spare2]); + s.backings.insert(spare1, Backing::default()); + s.backings.insert(spare2, Backing::default()); + let mut resets = Vec::new(); + + unsafe { + assert_eq!(title_reset_in(&mut s, alloc as *mut c_void, |r| { resets.push(r as usize); 0 }), None); + assert_eq!(resets, vec![spare1, spare2], "clean reset must reclaim all idle aside backings"); + + // A second clean reset must not redundantly reset already-reclaimed aside backings. + resets.clear(); + assert_eq!(title_reset_in(&mut s, alloc as *mut c_void, |r| { resets.push(r as usize); 0 }), None); + assert!(resets.is_empty(), "already-reset aside backings should not be reset again"); + } + } + + #[test] + fn stalled_primary_stand_in_reset_keeps_uma_blocks_until_native_backing_resets() { + 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 fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let mut ids = Box::new([0u8; 5]); + let base = ids.as_mut_ptr() as usize; + let (title_alloc, spare_backing, primary, stand_in, queue) = (base, base + 1, base + 2, base + 3, base + 4); + + // 1. Primary records on logical `title_alloc` (native backing == `title_alloc`) + // with UMA block `0x1111` and is submitted while GPU fence stays unsignaled. + created_on(primary, title_alloc, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + super::super::bind::reset(primary as *mut c_void, title_alloc, 0); + super::super::bind::push_uma_for_test(primary as *mut c_void, 0x1111); + { + let mut g = STATE.lock().unwrap(); + let s = g.as_mut().unwrap(); + s.aside.insert(title_alloc, vec![spare_backing]); + s.backings.insert(spare_backing, Backing::default()); + s.backings.entry(title_alloc).or_default().marks.insert(queue, (fence.clone(), 1)); + let recording = s.recordings[&primary]; + s.last_submit.insert(primary, LastSubmit { queue, fence: fence.clone(), value: 1, recording }); + } + + // 2. Title resets list while `primary` is still in flight: `title_list::reset` selects + // `stand_in`, detaches `primary`'s bind blocks, and retires `primary`'s recording. + super::super::bind::reset(primary as *mut c_void, 0, 0); + retire_recording(primary); + assert!(in_flight(primary), "primary must remain in_flight until GPU finishes"); + + // 3. Title resets logical `title_alloc`: `alloc_pool` swaps to `spare_backing` and + // ONLY resets `spare_backing` (NOT `title_alloc`, which still has GPU work in flight). + let mut native_resets = Vec::new(); + { + let mut g = STATE.lock().unwrap(); + let s = g.as_mut().unwrap(); + assert_eq!( + title_reset_in(s, title_alloc as *mut c_void, |r| { native_resets.push(r as usize); 0 }), + Some(0) + ); + } + assert_eq!(native_resets, vec![spare_backing], "swap reset must only reset the idle spare backing"); + assert_eq!(current(title_alloc), spare_backing); + + // `stand_in` recording on logical `title_alloc` must key its UMA blocks to `spare_backing`. + super::super::bind::reset(stand_in as *mut c_void, title_alloc, 0); + super::super::bind::push_uma_for_test(stand_in as *mut c_void, 0x2222); + super::super::bind::reset(stand_in as *mut c_void, 0, 0); + + // Clearing `spare_backing` (what `reset_pc_allocator(spare_backing)` does) leaves + // `primary`'s blocks under stalled native backing `title_alloc` untouched. + assert_eq!(super::super::console_list::take_pending_for_test(spare_backing), vec![0x2222]); + assert_eq!(super::super::console_list::take_pending_for_test(title_alloc), vec![0x1111]); + + // 4. Once the GPU signals the fence on `title_alloc`, the next title reset reclaims + // and resets native backing `title_alloc`, which is when its blocks may be freed. + super::super::console_list::hold_until_reset(title_alloc, vec![0x1111]); + fence.Signal(1).unwrap(); + native_resets.clear(); + { + let mut g = STATE.lock().unwrap(); + let s = g.as_mut().unwrap(); + assert_eq!( + title_reset_in(s, title_alloc as *mut c_void, |r| { native_resets.push(r as usize); 0 }), + Some(0) + ); + } + assert!(native_resets.contains(&title_alloc), "completed aside backing must be reset on reclaim"); + assert_eq!(super::super::console_list::take_pending_for_test(title_alloc), vec![0x1111]); + + super::super::bind::forget(primary as *mut c_void); + super::super::bind::forget(stand_in as *mut c_void); + forget_list(primary); + forget_list(stand_in); + // Remove synthetic non-COM `spare_backing` before `forget` drops made PC allocators. + { + let mut g = STATE.lock().unwrap(); + if let Some(s) = g.as_mut() { + s.cur.remove(&title_alloc); + s.aside.remove(&title_alloc); + s.backings.remove(&spare_backing); + } + } + forget(title_alloc); + } + } + + #[test] + fn reset_list_blocks_concurrent_title_reset_and_rolls_back_on_failure() { + let mut ids = Box::new([0u8; 3]); + let base = ids.as_mut_ptr() as usize; + let (alloc, spare, list) = (base, base + 1, base + 2); + { + let mut g = STATE.lock().unwrap(); + let s = g.get_or_insert_with(State::default); + s.types.insert(alloc, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + s.aside.insert(alloc, vec![spare]); + s.backings.insert(spare, Backing::default()); + } + + let mut mid_reset_calls = Vec::new(); + let hr = reset_list(list, alloc, D3D12_COMMAND_LIST_TYPE_DIRECT.0, |backing| { + assert_eq!(backing, alloc); + // While `reset_list` is inside native Reset, `alloc` must already be pinned by `list` + // so a concurrent `title_reset` swaps to `spare` instead of resetting `alloc`. + let mut g = STATE.lock().unwrap(); + let s = g.as_mut().unwrap(); + assert!(s.backings[&alloc].users.contains(&list)); + assert!(!unsafe { s.backings[&alloc].free() }); + let r = unsafe { + title_reset_in(s, alloc as *mut c_void, |raw| { + mid_reset_calls.push(raw as usize); + 0 + }) + }; + assert_eq!(r, Some(0)); + crate::util::E_FAIL + }); + + assert_eq!(hr, crate::util::E_FAIL); + assert_eq!(mid_reset_calls, vec![spare], "concurrent title_reset must not reset the backing mid-reset_list"); + { + let mut g = STATE.lock().unwrap(); + let s = g.as_mut().unwrap(); + assert!(!s.of_list.contains_key(&list), "failed reset_list must roll back of_list"); + assert!(!s.backings[&alloc].users.contains(&list), "failed reset_list must roll back backing.users"); + assert_eq!(s.recordings.get(&list).copied().unwrap_or(0), 0, "failed reset_list must not bump recordings"); + // Clean up synthetic non-COM spare before forget. + s.cur.remove(&alloc); + s.aside.remove(&alloc); + s.backings.remove(&spare); + } + unsafe { forget(alloc) }; + } + + #[test] + fn reset_list_waits_while_backing_is_resetting() { + let mut ids = Box::new([0u8; 2]); + let base = ids.as_mut_ptr() as usize; + let (alloc, list) = (base, base + 1); + { + let mut g = STATE.lock().unwrap(); + let s = g.get_or_insert_with(State::default); + s.types.insert(alloc, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + let b = s.backings.entry(alloc).or_default(); + b.resetting = true; + assert!(!unsafe { b.free() }, "a resetting backing must never report free"); + assert!(try_reserve_backing(s, list, alloc, D3D12_COMMAND_LIST_TYPE_DIRECT.0).is_none()); + } + + let cleared = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let cleared_bg = cleared.clone(); + let bg = std::thread::spawn(move || { + std::thread::sleep(std::time::Duration::from_millis(5)); + { + let mut g = STATE.lock().unwrap(); + if let Some(b) = g.as_mut().and_then(|s| s.backings.get_mut(&alloc)) { + b.resetting = false; + } + cleared_bg.store(true, std::sync::atomic::Ordering::Release); + } + RESET_DONE.notify_all(); + }); + + let hr = reset_list(list, alloc, D3D12_COMMAND_LIST_TYPE_DIRECT.0, |backing| { + assert_eq!(backing, alloc); + assert!(cleared.load(std::sync::atomic::Ordering::Acquire), "reset_list must not hand out backing before resetting clears"); + 0 + }); + bg.join().unwrap(); + assert_eq!(hr, 0); + forget_list(list); + unsafe { forget(alloc) }; + } + + #[test] + fn reset_list_preserves_previous_backing_until_native_success() { + let mut ids = Box::new([0u8; 5]); + let base = ids.as_mut_ptr() as usize; + let (alloc, old, current, spare, list) = (base, base + 1, base + 2, base + 3, base + 4); + { + let mut g = STATE.lock().unwrap(); + let s = g.get_or_insert_with(State::default); + s.types.insert(alloc, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + s.cur.insert(alloc, current); + s.aside.insert(alloc, vec![old, spare]); + s.backings.insert(spare, Backing { already_reset: true, ..Backing::default() }); + move_list(s, list, old); + } + + let mut native_resets = Vec::new(); + let hr = reset_list(list, alloc, D3D12_COMMAND_LIST_TYPE_DIRECT.0, |backing| { + assert_eq!(backing, current); + let mut g = STATE.lock().unwrap(); + let s = g.as_mut().unwrap(); + assert!(s.backings[&old].users.contains(&list)); + assert!(s.backings[¤t].users.contains(&list)); + assert_eq!( + unsafe { + title_reset_in(s, alloc as *mut c_void, |raw| { + native_resets.push(raw as usize); + 0 + }) + }, + Some(0) + ); + crate::util::E_FAIL + }); + + assert_eq!(hr, crate::util::E_FAIL); + assert_eq!(recording_backing(list), Some(old)); + assert!(!native_resets.contains(&old), "the previous recording must stay pinned until native Reset succeeds"); + { + let g = STATE.lock().unwrap(); + let s = g.as_ref().unwrap(); + assert!(s.backings[&old].users.contains(&list)); + assert!(!s.backings[¤t].users.contains(&list)); + } + + // Now succeed: `list` moves cleanly from `old` to the current backing (`spare`). + let hr_ok = reset_list(list, alloc, D3D12_COMMAND_LIST_TYPE_DIRECT.0, |_| 0); + assert_eq!(hr_ok, 0); + assert_eq!(recording_backing(list), Some(spare)); + { + let mut g = STATE.lock().unwrap(); + let s = g.as_mut().unwrap(); + assert!(!s.backings[&old].users.contains(&list)); + assert!(s.backings[&spare].users.contains(&list)); + // Clean up synthetic non-COM backings before forget. + s.cur.remove(&alloc); + s.aside.remove(&alloc); + s.backings.remove(&old); + s.backings.remove(¤t); + s.backings.remove(&spare); + s.of_list.remove(&list); + } + forget_list(list); + unsafe { forget(alloc) }; + } + + #[test] + fn forget_does_not_release_a_busy_original_backing_twice_and_reclaims_when_idle() { + let mut ids = Box::new([0u8; 4]); + let base = ids.as_mut_ptr() as usize; + let (alloc, next, list_a, list_b) = (base, base + 1, base + 2, base + 3); + { + let mut g = STATE.lock().unwrap(); + let s = g.get_or_insert_with(State::default); + s.types.insert(alloc, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + s.aside.insert(alloc, vec![alloc]); + s.cur.insert(alloc, next); + move_list(s, list_a, alloc); + move_list(s, list_b, next); + } + super::super::console_list::hold_until_reset(alloc, vec![0x1111]); + + unsafe { forget(alloc) }; + + { + let g = STATE.lock().unwrap(); + let s = g.as_ref().unwrap(); + assert!(!s.backings.contains_key(&alloc), "forgotten busy backing must detach from active table for address-reuse safety"); + assert!(s.orphaned.iter().any(|o| o.backing == alloc && o.state.users.contains(&list_a))); + } + assert_eq!( + super::super::console_list::take_pending_for_test(alloc), + vec![0x1111], + "a live old recording must keep its pending UMA blocks" + ); + + // Re-hold pending UMA and retire the last live recording: orphaned backing must reclaim cleanly. + super::super::console_list::hold_until_reset(alloc, vec![0x2222]); + retire_recording(list_a); + assert!( + super::super::console_list::take_pending_for_test(alloc).is_empty(), + "retiring the last user of an orphaned backing must drain its pending UMA" + ); + { + let mut g = STATE.lock().unwrap(); + let s = g.as_mut().unwrap(); + assert!(!s.orphaned.iter().any(|o| o.backing == alloc)); + // Remove synthetic non-COM `next` orphan directly so Drop does not release a fake pointer. + s.orphaned.retain(|o| o.backing != next); + } + forget_list(list_a); + forget_list(list_b); + } + + #[test] + fn forget_racing_mid_reset_list_cleans_up_on_rollback_and_commit() { + let mut ids = Box::new([0u8; 4]); + let base = ids.as_mut_ptr() as usize; + let (prev_alloc, alloc, list) = (base, base + 1, base + 2); + created_on(list, prev_alloc, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + + // Rollback path: `forget(alloc)` runs mid-`reset_list`, then native Reset fails. + let hr = reset_list(list, alloc, D3D12_COMMAND_LIST_TYPE_DIRECT.0, |b| { + assert_eq!(b, alloc); + unsafe { forget(alloc) }; + crate::util::E_FAIL + }); + assert_eq!(hr, crate::util::E_FAIL); + { + let g = STATE.lock().unwrap(); + let s = g.as_ref().unwrap(); + assert!(!s.backings.contains_key(&alloc), "rolled-back forgotten backing must not remain in backings"); + assert!(!s.orphaned.iter().any(|o| o.backing == alloc), "rolled-back forgotten backing must be reclaimed"); + assert_eq!(s.of_list.get(&list), Some(&prev_alloc)); + assert!(s.backings.get(&prev_alloc).is_some_and(|b| b.users.contains(&list))); + } + + // Commit path: `forget(alloc)` runs mid-`reset_list`, then native Reset succeeds. + let hr = reset_list(list, alloc, D3D12_COMMAND_LIST_TYPE_DIRECT.0, |b| { + assert_eq!(b, alloc); + unsafe { forget(alloc) }; + 0 + }); + assert_eq!(hr, 0); + { + let g = STATE.lock().unwrap(); + let s = g.as_ref().unwrap(); + assert!(!s.backings.contains_key(&alloc), "committed forgotten backing must not recreate a zombie backing"); + assert!(!s.of_list.contains_key(&list), "committed forgotten backing must not leave a stale of_list entry"); + assert!(s.backings.get(&prev_alloc).is_none_or(|b| !b.users.contains(&list))); + assert!( + s.orphaned.iter().any(|o| o.backing == alloc && o.state.users.contains(&list) && !o.state.already_reset), + "committed list must stay pinned on the orphaned backing" + ); + } + + // Retiring the list reclaims the orphaned backing cleanly. + retire_recording(list); + { + let g = STATE.lock().unwrap(); + let s = g.as_ref().unwrap(); + assert!(!s.orphaned.iter().any(|o| o.backing == alloc)); + } + forget_list(list); + unsafe { forget(prev_alloc) }; + } } diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 3f31c48b43..8d5be8ad5e 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -70,11 +70,17 @@ fn with(list: *mut c_void, f: impl FnOnce(&mut State) -> R) -> R { } /// The list was created or reset onto `allocator` with `initial_pso`: the previous -/// recording's memory is the previous allocator's until that one is reset, and pipeline -/// and root signature state reset per D3D12 `CreateCommandList` / `Reset` semantics. +/// recording's memory is the previous native backing's until that backing is reset, and +/// pipeline and root signature state reset per D3D12 `CreateCommandList` / `Reset` semantics. pub(super) fn reset(list: *mut c_void, allocator: usize, initial_pso: usize) { + let backing = if allocator == 0 { + 0 + } else { + super::alloc_pool::recording_backing(list as usize) + .unwrap_or_else(|| super::alloc_pool::current(allocator)) + }; let (old, blocks) = with(list, |s| { - let old = std::mem::replace(&mut s.allocator, allocator); + let old = std::mem::replace(&mut s.allocator, backing); s.arena = Default::default(); s.pso = initial_pso; s.layout = None; @@ -104,11 +110,12 @@ pub(super) fn clear_state(list: *mut c_void, pso: usize) { /// deferred mid-list split (`to` records into `allocator` with its own fresh UMA arena while /// `from` retains its previously allocated blocks until `allocator` resets). pub(super) fn inherit_for_split(from: *mut c_void, to: *mut c_void, allocator: usize) { + let backing = if allocator == 0 { 0 } else { super::alloc_pool::current(allocator) }; let (layout, args, layout_gfx, args_gfx, rs_gfx, pso) = with(from, |s| { (s.layout.clone(), s.args.clone(), s.layout_gfx.clone(), s.args_gfx.clone(), s.rs_gfx, s.pso) }); let (old, blocks) = with(to, |s| { - let old = std::mem::replace(&mut s.allocator, allocator); + let old = std::mem::replace(&mut s.allocator, backing); s.arena = Default::default(); s.layout = layout; s.args = args; @@ -144,6 +151,11 @@ pub(super) fn forget(list: *mut c_void) { } } +#[cfg(test)] +pub(crate) fn push_uma_for_test(list: *mut c_void, block: usize) { + with(list, |s| s.uma.push(block)); +} + #[cfg(test)] pub(crate) fn seed_reset_state_for_test(list: *mut c_void, allocator: usize, pso: usize, uma: Vec) { with(list, |s| { diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index ee544dec22..5cece7f301 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -3377,6 +3377,7 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { for seg in reclaimed { super::bind::reset(seg as *mut c_void, 0, 0); clear_segment_state(seg); + super::alloc_pool::retire_recording(seg); } if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(primary as usize))) { s.allocator = alloc; diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 76f31d4daf..238e1f196b 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -7040,21 +7040,23 @@ pub(super) unsafe fn reset_pc_allocator(raw: *mut c_void) -> HRESULT { type F = unsafe extern "system" fn(*mut c_void) -> HRESULT; let f: F = std::mem::transmute(orig_fn(raw, slot_of(raw, "Reset"))); let hr = f(raw); - if hr >= 0 { dispatch_chain::allocator_reset(raw as usize); } + if hr >= 0 { + dispatch_chain::allocator_reset(raw as usize); + // the GPU is done with what lists recorded from this native backing used + super::console_list::allocator_reset(raw); + } hr } unsafe extern "system" fn alloc_reset(this: *mut c_void) -> HRESULT { - // (lists may still hold recordings on it that the title submits again: `alloc_pool`) - let hr = match super::alloc_pool::title_reset(this) { + // (lists may still hold recordings on it that the title submits again: `alloc_pool`; + // `reset_pc_allocator` releases pending UMA blocks per native backing once that backing + // itself is idle and reset, so swapping away from an in-flight backing keeps its blocks + // alive until its GPU work finishes) + match super::alloc_pool::title_reset(this) { Some(hr) => hr, None => reset_pc_allocator(this), - }; - if hr >= 0 { - // the GPU is done with what lists recorded from this allocator used - super::console_list::allocator_reset(this); } - hr } // --------------------------------------------------------------------------------------- diff --git a/crates/xcl/src/hle/d3d12x/title_list.rs b/crates/xcl/src/hle/d3d12x/title_list.rs index a41e5643fc..b67e51b493 100644 --- a/crates/xcl/src/hle/d3d12x/title_list.rs +++ b/crates/xcl/src/hle/d3d12x/title_list.rs @@ -194,6 +194,11 @@ pub(super) unsafe extern "system" fn reset(this: *mut c_void, alloc: usize, pso: for seg in moved { super::bind::reset(seg as *mut c_void, 0, 0); super::list_x::clear_segment_state(seg); + super::alloc_pool::retire_recording(seg); + } + if stand_in.is_some() { + super::bind::reset(primary, 0, 0); + super::alloc_pool::retire_recording(primary as usize); } } *((this as usize + F_RING_AT) as *mut usize) = 0; @@ -288,6 +293,7 @@ pub(super) fn pop_spare(wrapper: *mut c_void) -> Option<*mut c_void> { /// Give back to `wrapper`'s spare pool a closed PC command list that did not become a segment. pub(super) fn put_spare(wrapper: *mut c_void, pc: *mut c_void) { + super::alloc_pool::retire_recording(pc as usize); let mut sg = SEGMENTS.lock().unwrap(); sg.get_or_insert_with(HashMap::new).entry(wrapper as usize).or_default().spares.push(pc as usize); }