From 11920b5e0d127f04d45363ac8475e82d174d9e40 Mon Sep 17 00:00:00 2001 From: theaustinayers <153482135+theaustinayers@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:52:04 -0500 Subject: [PATCH] D3D12.X: an allocator Reset keeps the recordings the title still submits A retail title's device was removed (0x887a0001) a few seconds into its world. The debug layer: "The command allocator was reset after the command list was recorded" (id 541). A trace of every list reset, allocator reset and submit showed the title's own order: one recording made at 61.4 s, submitted at 61.6 s, at 63.2 s on a second queue, the allocator it was given reset at 67.2 s, and the same recording submitted a third time at 67.8 s. Its console lets it; on the PC the recording lives in the allocator and is gone. The title's allocator now stands for a PC allocator that changes. At the title's Reset, when lists still hold recordings on the PC allocator in use or the GPU has not finished them, that one is put aside as it is and another takes its place: one put aside earlier that nothing uses any more, or a new one. A list reset on the title's allocator records on the one in use. A list holds one recording, so no more are put aside than there are lists. Measured on the retail title (RTX 5090) with this change on a build that also carried the trace: no device removal and no stale submit in the trace in five runs (before: removed 5-9 s into the world in every run). Four of them reached their limit of 100-120 s; the first ran 134 s and was ended on an NVIDIA driver error (nvlddmkm 153) whose cause is not known. In 60 s of world: 240 resets swapped, 163 allocators made, 77 reuses. XCL_ALLOC_SWAP=0 turns it off. Assisted-by: Claude Code (Claude Fable 5.2) --- crates/xcl/src/hle/d3d12x/alloc_pool.rs | 270 ++++++++++++++++++++++++ crates/xcl/src/hle/d3d12x/list_x.rs | 16 +- crates/xcl/src/hle/d3d12x/mod.rs | 1 + crates/xcl/src/hle/d3d12x/real.rs | 16 +- 4 files changed, 296 insertions(+), 7 deletions(-) create mode 100644 crates/xcl/src/hle/d3d12x/alloc_pool.rs diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs new file mode 100644 index 000000000..4adba6057 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs @@ -0,0 +1,270 @@ +//! A title's command allocator Reset does not take recordings the title still submits. +//! +//! On the PC a list's recording lives in its allocator: after `allocator.Reset()` a list that +//! recorded on it must not be submitted again ("The command allocator was reset after the +//! command list was recorded", debug layer id 541 – the runtime removes the device, +//! 0x887a0001). A retail title does exactly that, which its console lets it: one recording, +//! submitted at 61.6 s, at 63.2 s on a second queue and at 67.8 s again, with the allocator +//! it had been given reset at 67.2 s. +//! +//! So the title's allocator is a name for a PC allocator that changes: at the title's Reset, +//! when lists still hold recordings on the PC allocator in use (or the GPU has not finished +//! them), that one is put aside as it is and the title's allocator goes on with another – one +//! put aside earlier whose lists have all been reset since and whose submits are done, or a new +//! one. A list reset on the title's allocator records on the PC allocator in use. A list holds +//! 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 windows::core::Interface; +use windows::Win32::Graphics::Direct3D12::*; + +use crate::util::HRESULT; + +#[derive(Default)] +struct Backing { + /// PC lists whose recording is on this allocator + users: HashSet, + /// queue → (fence, value after the last submit of one of them) + marks: HashMap, +} + +impl Backing { + unsafe fn free(&self) -> bool { + self.users.is_empty() && self.marks.values().all(|(f, v)| f.GetCompletedValue() >= *v) + } +} + +#[derive(Default)] +struct State { + /// title allocator → the PC allocator in use (absent: itself) + cur: HashMap, + /// title allocator → PC allocators put aside + aside: HashMap>, + backings: HashMap, + of_list: HashMap, + /// title allocator → the type of the lists on it + types: HashMap, + fences: HashMap, + made: u64, + swaps: u64, +} + +unsafe impl Send for State {} + +static STATE: Mutex> = Mutex::new(None); + +/// `XCL_ALLOC_SWAP=0` turns it off. +pub fn enabled() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| !std::env::var("XCL_ALLOC_SWAP").is_ok_and(|v| v.trim() == "0")) +} + +fn move_list(s: &mut State, list: usize, backing: usize) { + if let Some(old) = s.of_list.insert(list, backing) { + if old != backing { + if let Some(b) = s.backings.get_mut(&old) { + b.users.remove(&list); + } + } + } + s.backings.entry(backing).or_default().users.insert(list); +} + +/// `list` (of type `ty`; negative: not known) is reset on the title's allocator `alloc`: the +/// PC allocator to give the PC list. +pub fn for_list(list: usize, alloc: usize, ty: i32) -> usize { + if !enabled() || alloc == 0 { + return alloc; + } + let mut g = STATE.lock().unwrap(); + let s = g.get_or_insert_with(State::default); + if ty >= 0 { + s.types.insert(alloc, ty); + } + let backing = s.cur.get(&alloc).copied().unwrap_or(alloc); + move_list(s, list, backing); + backing +} + +/// The PC allocator the title's allocator `alloc` stands for now. +pub fn current(alloc: usize) -> usize { + if !enabled() { + return alloc; + } + STATE.lock().unwrap().as_ref().and_then(|s| s.cur.get(&alloc).copied()).unwrap_or(alloc) +} + +/// `list` (of type `ty`) was made recording on the PC allocator `raw` itself +/// (CreateCommandList). +pub fn created_on(list: usize, raw: usize, ty: i32) { + if !enabled() || raw == 0 { + return; + } + let mut g = STATE.lock().unwrap(); + let s = g.get_or_insert_with(State::default); + s.types.entry(raw).or_insert(ty); + move_list(s, list, raw); +} + +/// `lists` were just submitted to `queue`. +pub unsafe fn executed(queue: *mut c_void, lists: &[*mut c_void]) { + if !enabled() || queue.is_null() { + return; + } + let mut g = STATE.lock().unwrap(); + let Some(s) = g.as_mut() else { return }; + if !lists.iter().any(|l| s.of_list.contains_key(&(*l as usize))) { + return; + } + let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return }; + let key = queue as usize; + if !s.fences.contains_key(&key) { + let mut dev: Option = None; + let Some(f) = q.GetDevice(&mut dev).ok().and(dev).and_then(|d| d.CreateFence::(0, D3D12_FENCE_FLAG_NONE).ok()) else { return }; + s.fences.insert(key, (f, 0)); + } + let (fence, value) = { + let (f, v) = s.fences.get_mut(&key).unwrap(); + if q.Signal(&*f, *v + 1).is_err() { + return; + } + *v += 1; + (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)); + } + } +} + +/// 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. +pub unsafe fn title_reset(alloc: *mut c_void) -> Option { + if !enabled() { + return None; + } + let a = alloc as usize; + 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()) { + if let Some(b) = s.backings.get_mut(&c) { + b.marks.clear(); + } + if c == a { + return None; + } + return Some(super::real::reset_pc_allocator(c as *mut c_void)); + } + 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) => { + s.aside.get_mut(&a).unwrap().retain(|&x| x != f); + if let Some(b) = s.backings.get_mut(&f) { + b.marks.clear(); + } + let hr = super::real::reset_pc_allocator(f as *mut c_void); + if hr < 0 { + return Some(hr); + } + f + } + None => { + let this = ID3D12CommandAllocator::from_raw_borrowed(&alloc)?; + let mut dev: Option = None; + this.GetDevice(&mut dev).ok()?; + let made: ID3D12CommandAllocator = dev?.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE(ty)).ok()?; + let raw = made.into_raw(); + // (made through the title's device it is adopted already) + if !super::real::is_adopted(raw) { + super::real::adopt(raw, super::real::Kind::CommandAllocator); + } + s.made += 1; + raw as usize + } + }; + s.aside.entry(a).or_default().push(c); + s.cur.insert(a, next); + s.swaps += 1; + if s.swaps.is_power_of_two() { + let aside: 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} put aside now)", + s.swaps, + s.made + ); + } + Some(0) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A list recorded once and submitted again after the title reset its allocator: the + /// recording is still there (the device is not removed), the title's allocator goes on with + /// another PC allocator, and the first one is used again once the list has moved on. + #[test] + fn a_recording_outlives_the_reset_of_the_titles_allocator() { + unsafe { + let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let a = alloc.as_raw(); + if !super::super::real::is_adopted(a) { + super::super::real::adopt(a, super::super::real::Kind::CommandAllocator); + } + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + let l = list.as_raw(); + created_on(l as usize, a as usize, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + list.Close().unwrap(); + let lists = [Some(list.cast::().unwrap())]; + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let done = |v: u64| { + queue.Signal(&fence, v).unwrap(); + let start = std::time::Instant::now(); + while fence.GetCompletedValue() < v && start.elapsed().as_secs() < 10 { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + assert!(fence.GetCompletedValue() >= v, "the queue finishes"); + }; + + queue.ExecuteCommandLists(&lists); + executed(queue.as_raw(), &[l]); + done(1); + + // the title resets its allocator (through the hook: `real::alloc_reset`) … + alloc.Reset().unwrap(); + let second = current(a as usize); + assert_ne!(second, a as usize, "the list still holds its recording: another PC allocator takes the place"); + // … and submits the recording again + queue.ExecuteCommandLists(&lists); + executed(queue.as_raw(), &[l]); + done(2); + assert!(dev.GetDeviceRemovedReason().is_ok(), "the recording was still there"); + + // the list is reset on the title's allocator: it records on the PC allocator in use + let pc = for_list(l as usize, a as usize, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + assert_eq!(pc, second); + let second_alloc = ID3D12CommandAllocator::from_raw_borrowed(&(second as *mut c_void)).unwrap().clone(); + list.Reset(&second_alloc, None).unwrap(); + list.Close().unwrap(); + queue.ExecuteCommandLists(&lists); + executed(queue.as_raw(), &[l]); + done(3); + + // the next reset: the first PC allocator holds nothing now and is used again + alloc.Reset().unwrap(); + assert_eq!(current(a as usize), a as usize, "the allocator put aside is free again"); + assert!(dev.GetDeviceRemovedReason().is_ok()); + } + } +} diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index fb17d4d2d..2995f05b0 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -745,6 +745,7 @@ pub unsafe fn on_create(list: *mut c_void, alloc: usize, pso: usize, ty: D3D12_C WRITE64_SIGNAL_LISTS.fetch_sub(1, Ordering::AcqRel); } } + super::alloc_pool::created_on(key, alloc, ty.0); m.insert(key, ListState { allocator: alloc, list_type: Some(ty), bound_pso: pso, ..Default::default() }); old }; @@ -2292,7 +2293,8 @@ unsafe fn try_split_for_wait(list: *mut c_void) -> Option<*mut c_void> { let mut next_pc: Option<*mut c_void> = None; if let Some(spare) = super::title_list::pop_spare(wrapper) { let ext_spare = *(spare as *const usize); - let reset_hr = pc:: i32>(spare, PC_RESET)(spare, alloc, init_pso); + let pc_alloc = super::alloc_pool::for_list(spare as usize, alloc, ty.0); + let reset_hr = pc:: i32>(spare, PC_RESET)(spare, pc_alloc, init_pso); real::preserve_vtable(spare, ext_spare); if reset_hr >= 0 { next_pc = Some(spare); @@ -2300,7 +2302,7 @@ unsafe fn try_split_for_wait(list: *mut c_void) -> Option<*mut c_void> { } let next_pc = match next_pc { Some(p) => p, - None => match real::create_raw_pc_command_list(dev.as_raw(), ty, alloc, init_pso) { + None => match real::create_raw_pc_command_list(dev.as_raw(), ty, super::alloc_pool::current(alloc), init_pso) { Some(p) => p, None => { static CREATE_ERR: AtomicU64 = AtomicU64::new(0); @@ -2763,6 +2765,7 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { if !prior.is_empty() { execute_with_waits_on(q_raw, prior, |chunk| { exec(q_raw, chunk.len() as u32, chunk.as_ptr()); + super::alloc_pool::executed(q_raw, chunk); signal_write64_fences(q_raw, chunk); readback_sparse_writes(q_raw, chunk); cpu_writes_after(q_raw, chunk); @@ -2780,6 +2783,7 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { let one = [this]; exec(q_raw, 1, one.as_ptr()); + super::alloc_pool::executed(q_raw, &one); signal_write64_pairs(q_raw, &write64_signals); // what ran is in the textures' states; the list records anew after its Reset below super::title_textures::submitted(&one); @@ -2829,7 +2833,8 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { let ext_closed = *(target as *const usize); let init_pso = super::pso_async::resolve_for_bind(bound_pso); - let reset_hr = pc:: i32>(target, PC_RESET)(target, alloc, init_pso); + let pc_alloc = super::alloc_pool::for_list(target as usize, alloc, list_type(target).0); + let reset_hr = pc:: i32>(target, PC_RESET)(target, pc_alloc, init_pso); real::preserve_vtable(target, ext_closed); if reset_hr < 0 { return warn(&ERR, "KickoffX", format_args!("Reset after kickoff failed ({reset_hr:#x})")); @@ -3367,7 +3372,10 @@ pub unsafe extern "system" fn reset_x(this: *mut c_void, alloc: usize, pso: usiz // transfer its allocations until the driver accepts the new recording. let ext = *(this as *const usize); let resolved = super::pso_async::resolve_for_bind(pso); - let hr = pc:: i32>(this, PC_RESET)(this, alloc, resolved); + // (the PC allocator the title's allocator stands for now: `alloc_pool`) + let ty = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(this as usize))).and_then(|s| s.list_type).map_or(-1, |t| t.0); + let pc_alloc = super::alloc_pool::for_list(this as usize, alloc, ty); + let hr = pc:: i32>(this, PC_RESET)(this, pc_alloc, resolved); real::preserve_vtable(this, ext); if hr < 0 { return hr; diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index 92f7bc928..5da6eced0 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -9,6 +9,7 @@ #![allow(non_snake_case)] +mod alloc_pool; pub mod bind; pub mod console_heap; pub mod console_list; diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 9168a5d66..27a642ac0 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -4866,10 +4866,19 @@ unsafe extern "system" fn alloc_release(this: *mut c_void) -> u32 { n } -unsafe extern "system" fn alloc_reset(this: *mut c_void) -> HRESULT { +/// Reset the (adopted) PC allocator `raw` itself. +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(this, slot_of(this, "Reset"))); - let hr = f(this); + let f: F = std::mem::transmute(orig_fn(raw, slot_of(raw, "Reset"))); + f(raw) +} + +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) { + 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); @@ -5090,6 +5099,7 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis super::list_x::note_queue_for_lists(this as usize, &mapped); super::list_x::execute_with_waits_on(this, &mapped, |chunk| { f(this, chunk.len() as u32, chunk.as_ptr()); + super::alloc_pool::executed(this, chunk); super::list_x::signal_write64_fences(this, chunk); super::list_x::readback_sparse_writes(this, chunk); super::list_x::cpu_writes_after(this, chunk);