From 62f6d4737b28a5fc7e9808350724c0c1a4a0f168 Mon Sep 17 00:00:00 2001 From: Decodere <98278826+Decodere@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:01:24 +0300 Subject: [PATCH] D3D12.X: switch KickoffX onto an idle spare PC list when the submitted list is in flight Follow-up to #2163 (Part of #1452). `list_x::kickoff_x()` previously reset and resumed recording on the same PC command list it had just submitted (or on `primary` after a mid-list split), even when that list's submission was still executing on the GPU. A subsequent `KickoffX` or final `Close` + `ExecuteCommandLists` then resubmitted an in-flight PC command list, triggering D3D12 debug layer ID 553 (`EXECUTECOMMANDLISTS_COMMANDLIST_STILL_IN_FLIGHT`) and device removal on strict drivers. - Add `title_list::primary_of`, `title_list::switch_active_for_kickoff`, and `title_list::mark_kickoff_unreset` to switch `F_BACKING` / `WRAPPER_OF` / `book.first` / `book.spares` after `Reset` succeeds while keeping `F_PRIMARY` out of `book.first` and `book.spares`, and suppress `push_segments` (with empty-batch early return in `execute_with_waits_on`) if `KickoffX` cannot obtain/reset an idle target until the title's next `Reset`. - Extract shared `list_x::create_closed_spare` (used by both `reset_stand_in` and `kickoff_x`) so a spare whose initial `Close` fails is released instead of pooled, and `list_x::acquire_kickoff_target` so `kickoff_x` never falls back to resetting `current_target` while it is still in flight (trying idle `primary`, all idle pooled spares, then a fresh spare, and leaving `current_target` closed + unreset on failure). - Update `list_x::kickoff_x` to preserve `bind` / `ListState` / DRED pipeline state onto the new active list, clear retired segment state, and guard `init_pso` and predication restore for `COPY` command lists. - Add unit tests covering `switch_active_for_kickoff` and `kickoff_unreset` invariants, back-to-back in-flight `KickoffX` + return to `primary` after drain, `KickoffX` after a mid-list `Write64 -> Wait64` split, and gated-queue no-spare / spare-`Reset` failure paths. Assisted-by: Google Antigravity (Gemini 4 Neon) --- crates/xcl/src/hle/d3d12x/list_x.rs | 497 +++++++++++++++++++++--- crates/xcl/src/hle/d3d12x/title_list.rs | 114 ++++++ 2 files changed, 552 insertions(+), 59 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index ee544dec22..13609f95c6 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -2094,7 +2094,10 @@ pub(super) unsafe fn cpu_writes_after(queue: *mut c_void, lists: &[*mut c_void]) /// When `queue` is non-null, monotonic 64-bit waits backed by a recorded `Write64BitValue*` are /// bridged to GPU-side `queue.Wait` without blocking the submitter thread on the CPU. pub(super) unsafe fn execute_with_waits_on(queue: *mut c_void, lists: &[*mut c_void], mut submit: impl FnMut(&[*mut c_void])) { - if lists.is_empty() || PENDING_WAIT_LISTS.load(Ordering::Acquire) == 0 { + if lists.is_empty() { + return; + } + if PENDING_WAIT_LISTS.load(Ordering::Acquire) == 0 { submit(lists); return; } @@ -2586,6 +2589,24 @@ pub(super) unsafe extern "system" fn write64_bottom_x(this: *mut c_void, va: u64 write(this, va, &[value as u32, (value >> 32) as u32], D3D12_WRITEBUFFERIMMEDIATE_MODE_MARKER_OUT, W); } +/// Create a new adopted PC command list matching `template`'s device and type, closed and ready +/// for `Reset`. Releases and forgets the list instead of pooling it if `Close` fails. +unsafe fn create_closed_spare(template: *mut c_void, ty: D3D12_COMMAND_LIST_TYPE, alloc: usize) -> Option<*mut c_void> { + let pc_alloc = super::alloc_pool::current(alloc); + let made = real::create_raw_pc_command_list(device_of(template)?.as_raw(), ty, pc_alloc, 0)?; + let ext = *(made as *const usize); + let hr = pc:: i32>(made, PC_CLOSE)(made); + real::preserve_vtable(made, ext); + if hr < 0 { + super::bind::forget(made); + let rel: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*(*(made as *const *const usize)).add(2)); + rel(made); + return None; + } + on_create(made, pc_alloc, 0, ty); + Some(made) +} + /// The title Resets its list (`title_list` `wrapper`) while the GPU has not finished the last /// submit of the PC list `primary` behind it: a console lets the title submit the new recording /// at once, the PC does not let `primary` be submitted again yet (#1452, debug layer id 553; @@ -2598,20 +2619,7 @@ pub(super) unsafe fn reset_stand_in(wrapper: *mut c_void, primary: *mut c_void, } let spare = match super::title_list::pop_spare(wrapper) { Some(p) => p, - None => { - let pc_alloc = super::alloc_pool::current(alloc); - let made = real::create_raw_pc_command_list(device_of(primary)?.as_raw(), ty, pc_alloc, 0)?; - on_create(made, pc_alloc, 0, ty); - // (closed: it is reset below like a spare) - let ext = *(made as *const usize); - let hr = pc:: i32>(made, PC_CLOSE)(made); - real::preserve_vtable(made, ext); - if hr < 0 { - super::title_list::put_spare(wrapper, made); - return None; - } - made - } + None => create_closed_spare(primary, ty, alloc)?, }; if reset_pc(spare, alloc, pso) < 0 { super::title_list::put_spare(wrapper, spare); @@ -3245,6 +3253,96 @@ pub unsafe extern "system" fn set_predication_buffer_x(this: *mut c_void, desc: apply_predication_copy(this, uma_buf, off, pb, D3D12_PREDICATION_OP(op_raw as i32)); } +/// Select and `Reset` the next active PC command list after `KickoffX` has submitted +/// `current_target`. Preserves the idle-list invariant (#1452, D3D12 debug layer id 553): never +/// calls `reset_one(current_target)` while `in_flight(current_target)` is true. On failure, leaves +/// `current_target` closed and marks `wrapper` unreset so neither a subsequent `KickoffX` nor +/// `ExecuteCommandLists` can resubmit the already-submitted in-flight recording. +unsafe fn acquire_kickoff_target( + wrapper: Option<*mut c_void>, + current_target: *mut c_void, + mut in_flight: impl FnMut(*mut c_void) -> bool, + mut create_spare: impl FnMut() -> Option<*mut c_void>, + mut reset_one: impl FnMut(*mut c_void) -> i32, +) -> Result<*mut c_void, i32> { + const E_OUTOFMEMORY: i32 = 0x8007_000Eu32 as i32; + let Some(w) = wrapper else { + let hr = reset_one(current_target); + return if hr >= 0 { Ok(current_target) } else { Err(hr) }; + }; + let primary = super::title_list::primary_of(w); + let mut last_err: Option = None; + + if current_target != primary && !in_flight(primary) { + let hr = reset_one(primary); + if hr >= 0 { + super::title_list::switch_active_for_kickoff(w, current_target, primary); + return Ok(primary); + } + last_err = Some(hr); + } + + if !in_flight(current_target) { + let hr = reset_one(current_target); + if hr >= 0 { + return Ok(current_target); + } + super::title_list::mark_kickoff_unreset(w); + return Err(hr); + } + + let mut failed_spares = Vec::new(); + let mut switched = None; + while let Some(cand) = super::title_list::pop_spare(w) { + if cand == current_target || in_flight(cand) { + failed_spares.push(cand); + continue; + } + let hr = reset_one(cand); + if hr >= 0 { + switched = Some(cand); + break; + } + last_err = Some(hr); + failed_spares.push(cand); + } + if switched.is_none() { + if let Some(cand) = create_spare() { + if cand != current_target && !in_flight(cand) { + let hr = reset_one(cand); + if hr >= 0 { + switched = Some(cand); + } else { + last_err = Some(hr); + failed_spares.push(cand); + } + } else { + failed_spares.push(cand); + } + } + } + for sp in failed_spares { + if sp != primary && sp != current_target { + super::title_list::put_spare(w, sp); + } + } + if let Some(cand) = switched { + super::title_list::switch_active_for_kickoff(w, current_target, cand); + return Ok(cand); + } + + if !in_flight(current_target) { + let hr = reset_one(current_target); + if hr >= 0 { + return Ok(current_target); + } + super::title_list::mark_kickoff_unreset(w); + return Err(hr); + } + super::title_list::mark_kickoff_unreset(w); + Err(last_err.unwrap_or(E_OUTOFMEMORY)) +} + /// command list #93 KickoffX(): flush commands recorded so far by closing the list, submitting /// it to a compatible live command queue, and resetting it on the same command allocator so /// recording can continue seamlessly until the title's normal `Close` + `ExecuteCommandLists`. @@ -3263,7 +3361,7 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { 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 (alloc, queue, last_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 { if once(&NO_QUEUE, 4) { @@ -3296,7 +3394,7 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { let cpu_writes = std::mem::take(&mut s.cpu_writes); 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.allocator, q, s.last_queue, 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)) }; let (sparse_writes, write64_signals, cpu_writes) = sparse_writes; @@ -3325,8 +3423,9 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { type ExecFn = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void); let exec: ExecFn = transmute_copy(&real::orig_fn(q_raw, PC_QUEUE_EXECUTE_COMMAND_LISTS)); - // If this list was previously split mid-recording around a `Wait64`, flush all earlier closed - // segments in exact order before submitting `this`, then resume recording on `primary`. + // Capture wrapper before `reclaim_for_kickoff` updates `WRAPPER_OF`. If this list was split + // mid-recording around a `Wait64`, flush earlier closed segments in order before `this`. + let wrapper = super::title_list::wrapper_of(this); let kickoff_split = super::title_list::reclaim_for_kickoff(this); if let Some((_, ref prior, _)) = kickoff_split { if !prior.is_empty() { @@ -3364,7 +3463,40 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { } super::cpu_writes::after(q_raw, cpu_writes); - let target = if let Some((primary, _, reclaimed)) = kickoff_split { + let (current_target, prior_retired, reclaimed) = match kickoff_split { + Some((primary, prior, reclaimed)) => (primary, prior, reclaimed), + None => (this, Vec::new(), Vec::new()), + }; + let init_pso = if ty == D3D12_COMMAND_LIST_TYPE_COPY { 0 } else { super::pso_async::resolve_for_bind(bound_pso) }; + let reset_one = |pc_list: *mut c_void| -> i32 { + let ext_closed = *(pc_list as *const usize); + let hr = super::alloc_pool::reset_list(pc_list as usize, alloc, list_type(pc_list).0, |pc_alloc| { + pc:: i32>(pc_list, PC_RESET)(pc_list, pc_alloc, init_pso) + }); + real::preserve_vtable(pc_list, ext_closed); + hr + }; + // Avoid resuming on a PC command list whose submit is still in flight on the GPU (#1452, + // debug layer id 553): pick `primary` once idle, else an idle spare, else a fresh closed spare. + // If no idle candidate can be created or reset while `current_target` is in flight, leave it + // closed and suppress `push_segments` until the title's next `Reset`. + let target = match acquire_kickoff_target( + wrapper, + current_target, + |p| super::alloc_pool::in_flight(p as usize), + || create_closed_spare(current_target, ty, alloc), + reset_one, + ) { + Ok(t) => t, + Err(reset_hr) => { + return warn(&ERR, "KickoffX", format_args!("Reset after kickoff failed ({reset_hr:#x})")); + } + }; + super::dred::reset(target); + if init_pso != 0 { + super::dred::mark_pipeline(target, bound_pso, init_pso); + } + if target != this { let (ended_early, pred_buf_obj, bindings_copy) = { let mut g = LISTS.lock().unwrap(); if let Some(s) = g.as_mut().and_then(|m| m.get_mut(&(this as usize))) { @@ -3373,41 +3505,32 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { (Vec::new(), None, Bindings::default()) } }; - super::bind::inherit_for_split(this, primary, alloc); - for seg in reclaimed { - super::bind::reset(seg as *mut c_void, 0, 0); - clear_segment_state(seg); + super::bind::inherit_for_split(this, target, alloc); + for seg in reclaimed.into_iter().chain(prior_retired.into_iter().map(|p| p as usize)).chain([this as usize]) { + if seg != target as usize { + super::bind::reset(seg as *mut c_void, 0, 0); + clear_segment_state(seg); + } } - if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(primary as usize))) { - s.allocator = alloc; - s.bound_pso = bound_pso; - s.depth_bias = depth_bias; - s.index_buffer = index_buffer; - s.depth_bounds = depth_bounds; - s.predication = predication; - s.pred_buf = pred_buf_obj; - s.pred_in_state = false; - s.occlusion = Occlusion { active: None, ended_early }; - s.written_ranges.clear(); - s.clear_sparse_writes(); - s.clear_write64_signals(); - s.clear_waits(); - s.cpu_writes.clear(); - s.bindings = bindings_copy; - } - primary - } else { - this - }; - - let ext_closed = *(target as *const usize); - let init_pso = super::pso_async::resolve_for_bind(bound_pso); - let reset_hr = super::alloc_pool::reset_list(target as usize, alloc, list_type(target).0, |pc_alloc| { - 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})")); + let mut g = LISTS.lock().unwrap(); + let s = g.get_or_insert_with(HashMap::new).entry(target as usize).or_default(); + s.allocator = alloc; + s.list_type = Some(ty); + s.last_queue = last_queue.or(Some(queue)); + s.bound_pso = bound_pso; + s.depth_bias = depth_bias; + s.index_buffer = index_buffer; + s.depth_bounds = depth_bounds; + s.predication = predication; + s.pred_buf = pred_buf_obj; + s.pred_in_state = false; + s.occlusion = Occlusion { active: None, ended_early }; + s.written_ranges.clear(); + s.clear_sparse_writes(); + s.clear_write64_signals(); + s.clear_waits(); + s.cpu_writes.clear(); + s.bindings = bindings_copy; } reset_copy_scratch(target); let bindings = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(target as usize))).map(|s| s.bindings.clone()); @@ -3457,11 +3580,13 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { pc::(target, PC_OM_SET_DEPTH_BOUNDS)(target, min, max); } } - if let (Some(op), Some(pb)) = (predication, pred_buf) { - transition(target, pb, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_PREDICATION); - pc::(target, PC_SET_PREDICATION)(target, pb, 0, op); - if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(target as usize))) { - s.pred_in_state = true; + if ty != D3D12_COMMAND_LIST_TYPE_COPY { + if let (Some(op), Some(pb)) = (predication, pred_buf) { + transition(target, pb, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_PREDICATION); + pc::(target, PC_SET_PREDICATION)(target, pb, 0, op); + if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(target as usize))) { + s.pred_in_state = true; + } } } } @@ -7432,4 +7557,258 @@ mod tests { assert!(got.iter().all(|&v| v == 0xDEAD_BEEF), "the UAV was not cleared: {:x?}", &got[..4]); } } + + fn test_device_or_warp() -> Option { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + if let Ok(dev) = crate::gpu::agility::create_device(None, D3D_FEATURE_LEVEL_11_0) { + return Some(dev); + } + unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory1().ok()?; + let warp: IDXGIAdapter = factory.EnumWarpAdapter().ok()?; + let mut dev: Option = None; + D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).ok()?; + dev + } + } + + unsafe fn kickoff_test_setup(dev: &ID3D12Device) -> (ID3D12CommandQueue, ID3D12CommandAllocator, *mut c_void, *mut c_void, ID3D12Fence, ID3D12Fence) { + let ty = D3D12_COMMAND_LIST_TYPE_DIRECT; + let q: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: ty, ..Default::default() }).unwrap(); + let q_raw = q.as_raw(); + real::adopt(q_raw, real::Kind::CommandQueue); + on_queue_create(q_raw as usize, dev.as_raw() as usize, ty); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap(); + let a = alloc.as_raw() as usize; + let primary = dev.CreateCommandList::<_, _, ID3D12GraphicsCommandList>(0, ty, &alloc, None).unwrap().into_raw(); + real::adopt(primary, real::Kind::CommandList); + on_create(primary, a, 0, ty); + super::super::bind::reset(primary, a, 0); + if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(primary as usize))) { + s.last_queue = Some(q_raw as usize); + } + let w = super::super::title_list::wrap(primary); + let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let done: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + (q, alloc, primary, w, gate, done) + } + + static KICKOFF_GPU_TEST_LOCK: Mutex<()> = Mutex::new(()); + + /// Back-to-back `KickoffX` and final `ExecuteCommandLists` while the queue is gated on an + /// unsignalled fence must switch to idle spare PC lists (`note_resubmits == 0`), preserve + /// bindings across each kickoff, and return to `primary` once the GPU finishes (#1452). + #[test] + fn kickoff_x_while_in_flight_switches_to_idle_spare_and_preserves_state() { + let _guard = KICKOFF_GPU_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let Some(dev) = test_device_or_warp() else { return crate::gpu::recomp::runner::skip_test("no GPU or WARP"); }; + unsafe { + let (q, _alloc, primary, w, gate, done) = kickoff_test_setup(&dev); + let q_raw = q.as_raw(); + if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(primary as usize))) { + (s.bindings.stencil, s.bindings.topology) = (Some(0x5A), Some(4)); + } + let close: unsafe extern "system" fn(*mut c_void) -> i32 = std::mem::transmute(*(*(w as *const *const usize)).add(9)); + let release: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*(*(w as *const *const usize)).add(2)); + let exec: unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void) = + std::mem::transmute(real::orig_fn(q_raw, PC_QUEUE_EXECUTE_COMMAND_LISTS)); + let segs = || { let mut v = Vec::new(); assert!(super::super::title_list::push_segments(w, &mut v)); v }; + + q.Wait(&gate, 1).unwrap(); + assert_eq!(segs(), vec![primary]); + // KickoffX #1 & #2 while gated: must switch primary -> s1 -> s2 with 0 resubmits and keep bindings. + kickoff_x(primary); + let s1 = segs(); + assert_eq!(s1.len(), 1); + let resub1 = super::super::alloc_pool::note_resubmits(q_raw, &s1); + let state1 = { + let g = LISTS.lock().unwrap(); + let s = g.as_ref().unwrap().get(&(s1[0] as usize)).unwrap(); + (s.bindings.stencil, s.bindings.topology, s.last_queue) + }; + kickoff_x(s1[0]); + let s2 = segs(); + assert_eq!(s2.len(), 1); + let resub2 = super::super::alloc_pool::note_resubmits(q_raw, &s2); + let state2 = { + let g = LISTS.lock().unwrap(); + let s = g.as_ref().unwrap().get(&(s2[0] as usize)).unwrap(); + (s.bindings.stencil, s.bindings.topology) + }; + // Unblock GPU so primary & s1 drain; KickoffX #3 on s2 must switch directly back to primary. + gate.Signal(1).unwrap(); + q.Signal(&done, 1).unwrap(); + crate::gpu::fence::wait(&done, 1, &dev, None, 5000).expect("queue drains"); + kickoff_x(s2[0]); + let after_drain = segs(); + assert_eq!(close(w), 0); + let resub3 = super::super::alloc_pool::note_resubmits(q_raw, &after_drain); + exec(q_raw, after_drain.len() as u32, after_drain.as_ptr()); + super::super::alloc_pool::executed(q_raw, &after_drain); + q.Signal(&done, 2).unwrap(); + crate::gpu::fence::wait(&done, 2, &dev, None, 5000).expect("queue drains 2"); + let removed = dev.GetDeviceRemovedReason(); + assert_eq!(release(w), 0); + drop(q); + + assert_ne!(s1[0], primary, "KickoffX #1 must not keep recording on in-flight primary"); + assert_eq!((resub1, state1), (0, (Some(0x5A), Some(4), Some(q_raw as usize)))); + assert!(s2[0] != primary && s2[0] != s1[0], "KickoffX #2 must use a third distinct PC list"); + assert_eq!((resub2, state2), (0, (Some(0x5A), Some(4)))); + assert_eq!((after_drain, resub3), (vec![primary], 0)); + assert!(removed.is_ok()); + } + } + + /// `KickoffX` on a list split around a mid-list `Write64 -> Wait64` submits both `primary` + /// and the split segment; while in flight it must resume on an idle spare (`note_resubmits == 0`). + #[test] + fn kickoff_x_after_midlist_split_switches_to_idle_spare() { + let _guard = KICKOFF_GPU_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let Some(dev) = test_device_or_warp() else { return crate::gpu::recomp::runner::skip_test("no GPU or WARP"); }; + unsafe { + let (q, _alloc, primary, w, gate, done) = kickoff_test_setup(&dev); + let q_raw = q.as_raw(); + let close: unsafe extern "system" fn(*mut c_void) -> i32 = std::mem::transmute(*(*(w as *const *const usize)).add(9)); + let release: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*(*(w as *const *const usize)).add(2)); + let exec: unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void) = + std::mem::transmute(real::orig_fn(q_raw, PC_QUEUE_EXECUTE_COMMAND_LISTS)); + + let cell = Box::new(AtomicU64::new(0)); + let va = &*cell as *const AtomicU64 as u64; + note_write64_recorded(primary, va, 1); + wait64_x(primary, va, D3D12_COMPARISON_FUNC_GREATER_EQUAL.0 as u32, 1, 0, 0); + let mut split_segs = Vec::new(); + assert!(super::super::title_list::push_segments(w, &mut split_segs)); + assert_eq!(split_segs.len(), 2); + let seg1 = split_segs[1]; + assert!(split_segs[0] == primary && seg1 != primary); + + q.Wait(&gate, 1).unwrap(); + kickoff_x(seg1); + let mut after = Vec::new(); + assert!(super::super::title_list::push_segments(w, &mut after)); + assert_eq!((after.len(), close(w)), (1, 0)); + let resub = super::super::alloc_pool::note_resubmits(q_raw, &after); + exec(q_raw, after.len() as u32, after.as_ptr()); + super::super::alloc_pool::executed(q_raw, &after); + + gate.Signal(1).unwrap(); + q.Signal(&done, 1).unwrap(); + crate::gpu::fence::wait(&done, 1, &dev, None, 5000).expect("split kickoff drains"); + let removed = dev.GetDeviceRemovedReason(); + assert_eq!(release(w), 0); + drop(q); + if let Some(gr) = SYNC_GRAPH.lock().unwrap().as_mut() { + gr.cells.remove(&va); + } + assert!(after[0] != primary && after[0] != seg1, "split KickoffX must resume on an idle spare"); + assert_eq!(resub, 0); + assert!(removed.is_ok()); + } + } + + /// Failure paths while `primary` is gated in flight (no spare / create failure, and spare + /// `Reset` failure) must never fall back to resetting `primary` even when `Reset` on `primary` + /// would return `S_OK`, must keep `push_segments` empty so neither a follow-up `KickoffX` nor + /// `ExecuteCommandLists` resubmits it, and must recover cleanly on a second idle spare or + /// post-drain `Reset`. + #[test] + fn kickoff_x_failure_paths_never_reset_in_flight_target() { + const E_OUTOFMEMORY: i32 = 0x8007_000Eu32 as i32; + let _guard = KICKOFF_GPU_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let Some(dev) = test_device_or_warp() else { return crate::gpu::recomp::runner::skip_test("no GPU or WARP"); }; + unsafe { + let ty = D3D12_COMMAND_LIST_TYPE_DIRECT; + let (q, alloc, primary, w, gate, done) = kickoff_test_setup(&dev); + let (q_raw, a) = (q.as_raw(), alloc.as_raw() as usize); + let close: unsafe extern "system" fn(*mut c_void) -> i32 = std::mem::transmute(*(*(w as *const *const usize)).add(9)); + let reset_w: unsafe extern "system" fn(*mut c_void, usize, usize) -> i32 = std::mem::transmute(*(*(w as *const *const usize)).add(10)); + let release: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*(*(w as *const *const usize)).add(2)); + let exec: unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void) = + std::mem::transmute(real::orig_fn(q_raw, PC_QUEUE_EXECUTE_COMMAND_LISTS)); + let segs = || { let mut v = Vec::new(); assert!(super::super::title_list::push_segments(w, &mut v)); v }; + + // Gate the queue, close and submit `primary` so it is genuinely closed and in flight. + q.Wait(&gate, 1).unwrap(); + assert_eq!(close(w), 0); + let one = [primary]; + exec(q_raw, 1, one.as_ptr()); + super::super::alloc_pool::executed(q_raw, &one); + assert!(super::super::alloc_pool::in_flight(primary as usize)); + + // 1. No pooled spare and `create_spare` fails (`None`): must never call `reset_one(primary)` + // even though `reset_one` would return `S_OK`, and must suppress subsequent submits. + let mut reset_calls = Vec::new(); + let res_no_spare = acquire_kickoff_target( + Some(w), + primary, + |p| super::super::alloc_pool::in_flight(p as usize), + || None, + |p| { reset_calls.push(p); 0 }, + ); + assert_eq!(res_no_spare, Err(E_OUTOFMEMORY)); + assert!(reset_calls.is_empty(), "in-flight primary must never be reset when spare creation fails"); + let empty = segs(); + assert!(empty.is_empty(), "unreset kickoff wrapper must not expose in-flight primary to ExecuteCommandLists"); + assert!(close(w) < 0, "in-flight primary must remain closed"); + kickoff_x(primary); + assert!(segs().is_empty()); + let mut exec_batches = 0usize; + execute_with_waits_on(q_raw, &empty, |_| exec_batches += 1); + assert_eq!(exec_batches, 0); + + // 2. Pooled idle spare `s_fail` fails `Reset`: must never fall back to in-flight `primary`, + // must return `s_fail` to the spare pool, and must keep `push_segments` empty. + let s_fail = create_closed_spare(primary, ty, a).expect("spare 1"); + super::super::title_list::put_spare(w, s_fail); + reset_calls.clear(); + let res_spare_err = acquire_kickoff_target( + Some(w), + primary, + |p| super::super::alloc_pool::in_flight(p as usize), + || None, + |p| { reset_calls.push(p); if p == s_fail { E_OUTOFMEMORY } else { 0 } }, + ); + assert_eq!(res_spare_err, Err(E_OUTOFMEMORY)); + assert_eq!(reset_calls, vec![s_fail], "spare Reset failure must not fall back to in-flight primary"); + assert!(segs().is_empty()); + + // 3. With a second idle spare `s_good` behind `s_fail`, `acquire_kickoff_target` skips + // `s_fail`, switches to `s_good`, and keeps `s_fail` pooled with 0 resubmits. + assert_eq!(super::super::title_list::pop_spare(w), Some(s_fail)); + let s_good = create_closed_spare(primary, ty, a).expect("spare 2"); + super::super::title_list::put_spare(w, s_good); + super::super::title_list::put_spare(w, s_fail); + reset_calls.clear(); + let res_recovered = acquire_kickoff_target( + Some(w), + primary, + |p| super::super::alloc_pool::in_flight(p as usize), + || None, + |p| { reset_calls.push(p); if p == s_fail { E_OUTOFMEMORY } else { reset_pc(p, a, 0) } }, + ); + assert_eq!(res_recovered, Ok(s_good)); + assert_eq!(reset_calls, vec![s_fail, s_good]); + let segs_good = segs(); + assert_eq!(segs_good, vec![s_good]); + assert_eq!(super::super::alloc_pool::note_resubmits(q_raw, &segs_good), 0); + assert_eq!(close(w), 0); + + // 4. Mark unreset, drain the GPU, and verify normal `Reset` recovers `primary` cleanly. + super::super::title_list::mark_kickoff_unreset(w); + assert!(segs().is_empty()); + gate.Signal(1).unwrap(); + q.Signal(&done, 1).unwrap(); + crate::gpu::fence::wait(&done, 1, &dev, None, 5000).expect("failure-path queue drains"); + assert_eq!(reset_w(w, a, 0), 0); + assert_eq!(segs(), vec![primary]); + assert_eq!(close(w), 0); + let removed = dev.GetDeviceRemovedReason(); + assert_eq!(release(w), 0); + drop(q); + assert!(removed.is_ok()); + } + } } diff --git a/crates/xcl/src/hle/d3d12x/title_list.rs b/crates/xcl/src/hle/d3d12x/title_list.rs index a41e5643fc..18651d78dd 100644 --- a/crates/xcl/src/hle/d3d12x/title_list.rs +++ b/crates/xcl/src/hle/d3d12x/title_list.rs @@ -50,6 +50,9 @@ 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, + /// `KickoffX` already submitted the recording and could not reset an idle target; suppress + /// `push_segments` until the title's next `Reset` starts a new recording. + kickoff_unreset: bool, } /// Wrapper address -> split segment book (populated lazily only for lists that split). @@ -175,6 +178,7 @@ pub(super) unsafe extern "system" fn reset(this: *mut c_void, alloc: usize, pso: 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(); + b.kickoff_unreset = false; let mut old = std::mem::take(&mut b.extra_active); old.extend(std::mem::replace(&mut b.first, stand_in)); b.spares.extend(old.iter().copied()); @@ -252,6 +256,9 @@ 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))); + if book.is_some_and(|b| b.kickoff_unreset) { + 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 { @@ -269,6 +276,48 @@ pub(super) fn wrapper_of(pc: *mut c_void) -> Option<*mut c_void> { WRAPPER_OF.lock().unwrap().as_ref()?.get(&(pc as usize)).map(|&w| w as *mut c_void) } +/// The primary PC list behind `wrapper` (`F_PRIMARY`). +pub(super) unsafe fn primary_of(wrapper: *mut c_void) -> *mut c_void { + *((wrapper as usize + F_PRIMARY) as *const *mut c_void) +} + +/// Commit a `KickoffX` active-list switch on `wrapper` after `new_active` has been reset. +/// Keeps `F_PRIMARY` out of `book.first` / `book.spares`, moves any retired non-primary +/// active list into `book.spares`, and updates `F_BACKING` + `WRAPPER_OF`. +pub(super) unsafe fn switch_active_for_kickoff(wrapper: *mut c_void, old_active: *mut c_void, new_active: *mut c_void) { + if old_active == new_active { + return; + } + let primary = primary_of(wrapper) as usize; + let (old, new) = (old_active as usize, new_active as usize); + { + let mut sg = SEGMENTS.lock().unwrap(); + let b = sg.get_or_insert_with(HashMap::new).entry(wrapper as usize).or_default(); + b.kickoff_unreset = false; + if old != primary { + if b.first == Some(old) { + b.first = None; + } + if !b.spares.contains(&old) { + b.spares.push(old); + } + } + b.first = (new != primary).then_some(new); + } + *((wrapper as usize + F_BACKING) as *mut usize) = new; + let mut wg = WRAPPER_OF.lock().unwrap(); + let m = wg.get_or_insert_with(HashMap::new); + m.remove(&old); + m.insert(new, wrapper as usize); +} + +/// Mark `wrapper` as having no open recording after `KickoffX` submitted its active PC list and +/// failed to obtain/reset an idle target; `push_segments` emits nothing until `Reset` clears it. +pub(super) fn mark_kickoff_unreset(wrapper: *mut c_void) { + let mut sg = SEGMENTS.lock().unwrap(); + sg.get_or_insert_with(HashMap::new).entry(wrapper as usize).or_default().kickoff_unreset = true; +} + /// Whether `wrapper` may allocate/activate `n` more split segments for this recording. pub(super) fn can_split(wrapper: *mut c_void, n: usize) -> bool { let sg = SEGMENTS.lock().unwrap(); @@ -641,4 +690,69 @@ mod tests { drop(Box::from_raw(seg1)); } } + + #[test] + fn switch_active_for_kickoff_keeps_primary_out_of_spares() { + let mut vt = vec![0usize; LIST_SLOTS]; + vt[2] = fake_release as usize; + let primary = Box::into_raw(Box::new(Fake { vt: vt.as_ptr(), refs: 1 })); + let spare1 = Box::into_raw(Box::new(Fake { vt: vt.as_ptr(), refs: 1 })); + let spare2 = Box::into_raw(Box::new(Fake { vt: vt.as_ptr(), refs: 1 })); + let (p, s1, s2) = (primary as *mut c_void, spare1 as *mut c_void, spare2 as *mut c_void); + unsafe { + let w = wrap(p); + assert_eq!(primary_of(w), p); + switch_active_for_kickoff(w, p, s1); + assert_eq!((wrapper_of(p), wrapper_of(s1)), (None, Some(w))); + let mut segs = Vec::new(); + assert!(push_segments(w, &mut segs) && segs == vec![s1]); + switch_active_for_kickoff(w, s1, s2); + assert_eq!((wrapper_of(s1), wrapper_of(s2)), (None, Some(w))); + segs.clear(); + assert!(push_segments(w, &mut segs) && segs == vec![s2]); + switch_active_for_kickoff(w, s2, p); + assert_eq!((wrapper_of(s2), wrapper_of(p)), (None, Some(w))); + segs.clear(); + assert!(push_segments(w, &mut segs) && segs == vec![p]); + { + let sg = SEGMENTS.lock().unwrap(); + let b = sg.as_ref().unwrap().get(&(w as usize)).unwrap(); + assert_eq!(b.first, None); + assert!(!b.spares.contains(&(p as usize))); + assert_eq!(b.spares, vec![s1 as usize, s2 as usize]); + } + let rel: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*(*(w as *const *const usize)).add(2)); + assert_eq!(rel(w), 0); + assert_eq!(((*primary).refs, (*spare1).refs, (*spare2).refs), (0, 0, 0)); + drop(Box::from_raw(primary)); + drop(Box::from_raw(spare1)); + drop(Box::from_raw(spare2)); + } + } + + #[test] + fn kickoff_unreset_suppresses_push_segments_until_reset() { + unsafe extern "system" fn fake_reset_ok(_this: *mut c_void, _alloc: usize, _pso: usize) -> HRESULT { + 0 + } + let mut vt = vec![0usize; LIST_SLOTS]; + vt[2] = fake_release as usize; + vt[10] = fake_reset_ok as usize; + let primary = Box::into_raw(Box::new(Fake { vt: vt.as_ptr(), refs: 1 })); + let p = primary as *mut c_void; + unsafe { + let w = wrap(p); + let mut segs = Vec::new(); + assert!(push_segments(w, &mut segs) && segs == vec![p]); + mark_kickoff_unreset(w); + segs.clear(); + assert!(push_segments(w, &mut segs) && segs.is_empty()); + assert_eq!(reset(w, 0, 0), 0); + assert!(push_segments(w, &mut segs) && segs == vec![p]); + let rel: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*(*(w as *const *const usize)).add(2)); + assert_eq!(rel(w), 0); + assert_eq!((*primary).refs, 0); + drop(Box::from_raw(primary)); + } + } }