From 637b82a72ccad39d365e302e600cdc0b6ca0dbb2 Mon Sep 17 00:00:00 2001 From: throny <11830644+throny@users.noreply.github.com> Date: Wed, 25 Nov 2026 06:35:20 +0100 Subject: [PATCH 1/2] D3D12.X: log a command list submitted while its previous submit runs PC D3D12 does not allow submitting a command list whose previous execution the GPU has not finished (debug layer id 553: "the command queue fence has not advanced past previous executions of the command list"); a console lets a title do it. With the debug layer on, the retail title's world load shows id 553 from 85.8 s, then cross-queue waits that stop one signal short, then the device removal (#1452). alloc_pool::executed signalled a per-queue fence after submits of the lists it tracks (title lists). It now does so after every submit, so the PC lists behind console lists are covered too, and remembers each list's last submit (queue, fence value, recording number). note_resubmits, called before each ExecuteCommandLists chunk, logs a list whose previous submit is still running: whether it is the same recording and the same queue (the first 8, then at powers of two). The only change besides the log is that extra fence signal on submits of untracked lists. Part of #1452. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/alloc_pool.rs | 96 +++++++++++++++++++++++-- crates/xcl/src/hle/d3d12x/real.rs | 1 + 2 files changed, 93 insertions(+), 4 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs index f5ed20cec1..d29bf1e16e 100644 --- a/crates/xcl/src/hle/d3d12x/alloc_pool.rs +++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs @@ -49,6 +49,18 @@ struct State { fences: HashMap, made: u64, swaps: u64, + /// PC list → its last submit (queue, fence, value after it, recording number then) + last_submit: HashMap, + /// PC list → recordings so far (a Reset or creation starts the next one) + recordings: HashMap, + resubmits: u64, +} + +struct LastSubmit { + queue: usize, + fence: ID3D12Fence, + value: u64, + recording: u64, } unsafe impl Send for State {} @@ -77,6 +89,8 @@ fn move_list(s: &mut State, list: usize, backing: usize) { 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); @@ -98,6 +112,7 @@ pub fn reset_list(list: usize, alloc: usize, ty: i32, reset: impl FnOnce(usize) s.types.insert(alloc, ty); } move_list(s, list, backing); + *s.recordings.entry(list).or_default() += 1; hr } @@ -124,6 +139,41 @@ pub fn created_on(list: usize, raw: usize, ty: i32) { let s = g.get_or_insert_with(State::default); s.types.entry(raw).or_insert(ty); move_list(s, list, raw); + *s.recordings.entry(list).or_default() += 1; +} + +/// Diagnostic (#1452): `lists` are about to be submitted to `queue`. A PC list whose previous +/// submit the GPU has not finished must not be submitted again on the PC (debug layer id 553, +/// "the command queue fence has not advanced past previous executions of the command list"); +/// a console lets a title do it. Logged (the first 8, then at powers of two) with whether it is +/// the same recording and the same queue. Every submitted PC list is seen (`executed` marks them all). +pub unsafe fn note_resubmits(queue: *mut c_void, lists: &[*mut c_void]) -> usize { + if !enabled() { + return 0; + } + let mut g = STATE.lock().unwrap(); + let Some(s) = g.as_mut() else { return 0 }; + let mut found = 0; + for &l in lists { + let l = l as usize; + let Some(last) = s.last_submit.get(&l) else { continue }; + if last.fence.GetCompletedValue() >= last.value { + continue; + } + let same_recording = s.recordings.get(&l).copied().unwrap_or(0) == last.recording; + let same_queue = last.queue == queue as usize; + found += 1; + s.resubmits += 1; + let n = s.resubmits; + if n <= 8 || n.is_power_of_two() { + crate::xlog_warn!( + "D3D12.X: a command list is submitted while its previous submit is still on the GPU ({}, {}; #{n} so far) – the PC does not allow it (debug layer id 553)", + if same_recording { "the same recording" } else { "a new recording" }, + if same_queue { "the same queue" } else { "another queue" }, + ); + } + } + found } /// `lists` were just submitted to `queue`. @@ -131,11 +181,10 @@ pub unsafe fn executed(queue: *mut c_void, lists: &[*mut c_void]) { if !enabled() || queue.is_null() { return; } + // (every submit is marked, also of lists this module does not track – the PC lists behind + // console lists – so note_resubmits sees them all) 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 s = g.get_or_insert_with(State::default); let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return }; let key = queue as usize; if !s.fences.contains_key(&key) { @@ -155,6 +204,8 @@ pub unsafe fn executed(queue: *mut c_void, lists: &[*mut c_void]) { if let Some(&b) = s.of_list.get(&(l as usize)) { s.backings.entry(b).or_default().marks.insert(key, (fence.clone(), value)); } + 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 }); } } @@ -444,4 +495,41 @@ mod tests { assert!(!STATE.lock().unwrap().as_ref().unwrap().types.contains_key(&(a as usize))); } } + + /// A list submitted again while its previous submit is still on the GPU is counted (and + /// logged); once that submit is done, or after the list is forgotten, it is not. + #[test] + fn a_resubmit_while_the_previous_submit_runs_is_noticed() { + 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"); + }; + // a fence the GPU has not reached stands for a submit still running + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let mut ids = Box::new([0u8; 2]); + let (alloc, list) = (ids.as_mut_ptr() as usize, ids.as_mut_ptr() as usize + 1); + let queue = 0x10usize as *mut c_void; + created_on(list, alloc, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + { + let mut g = STATE.lock().unwrap(); + let s = g.as_mut().unwrap(); + let recording = s.recordings[&list]; + s.last_submit.insert(list, LastSubmit { queue: queue as usize, fence: fence.clone(), value: 1, recording }); + } + let while_running = note_resubmits(queue, &[list as *mut c_void]); + fence.Signal(1).unwrap(); + let after_done = note_resubmits(queue, &[list as *mut c_void]); + { + // running again, then the list goes: nothing is left to compare with + let mut g = STATE.lock().unwrap(); + g.as_mut().unwrap().last_submit.get_mut(&list).unwrap().value = 2; + } + forget_list(list); + let after_forget = note_resubmits(queue, &[list as *mut c_void]); + forget(alloc); + assert_eq!(while_running, 1, "a submit while the previous one runs must be noticed"); + assert_eq!(after_done, 0, "a finished previous submit is not a resubmit"); + assert_eq!(after_forget, 0, "a forgotten list has no previous submit"); + } + } } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 9241a3a18d..73a2cd654a 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -6215,6 +6215,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| { + let _ = super::alloc_pool::note_resubmits(this, chunk); f(this, chunk.len() as u32, chunk.as_ptr()); super::list_x::copy_scratch_submitted(this, chunk); super::alloc_pool::executed(this, chunk); From 78fba7b6609c922cbd944ae78603b1617d5bb69c Mon Sep 17 00:00:00 2001 From: throny <11830644+throny@users.noreply.github.com> Date: Wed, 25 Nov 2026 07:04:05 +0100 Subject: [PATCH 2/2] D3D12.X: a list reset while its last submit runs records on a spare A console lets a title Reset a command list and submit the new recording on the same queue while the GPU still runs the previous one. The PC does not let a list be submitted again before its last execution is done (debug layer id 553, "the command queue fence has not advanced past previous executions of the command list"); on NVIDIA the device is removed about 12 s later. The retail title's world load does it (#1452): note_resubmits logs "a new recording, the same queue", 8 lists at once. A title's list is a title_list wrapper whose PC lists already change (mid-list split segments, a spare pool per list), so the fix uses that: at the title's Reset, when alloc_pool says the primary PC list's last submit has not completed, the new recording goes onto a spare whose submits are done (or a new PC list), reset like the primary would be (reset_pc), and push_segments submits it in the primary's place (SegmentBook::first). The next Reset after the GPU is done records on the primary again and the stand-in goes back to the spares. pop_spare now skips spares still on the GPU, so split segments do not hit the same error. No CPU wait. When the primary is not in flight nothing changes. The retail title does not Reset through the wrapper's #10: its runtime has the newer console list layout, whose Reset is #139 (allocator, NULL, 0). The wrapper's #139 is a thunk to the active PC list (F_BACKING), and there NEWER_LIST_SLOTS's layout split runs the #10 handler, reset_x, on that PC list. So the wrapper's Reset, and its in-flight check, never ran (measured: the stand-in 0 times, 64+ resubmits, each list last reset in reset_x and still the wrapper's active PC list). reset_x now hands a Reset of a PC list a wrapper records on to the wrapper's Reset; the PC list's own Reset is reset_pc, which the wrapper and the stand-in call. This also resets a split list from its primary on #139, not from its last segment. Test: a list reset and submitted three times while a queue Wait holds the first submit records on three different PC lists and note_resubmits sees none, then on the primary again once the GPU is done; once with the wrapper's #10 and once with reset_x on the active PC list, as #139 does. Without the stand-in the second submit is the primary and the test fails; without the hand-over in reset_x the #139 round fails the same way. Part of #1452. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/alloc_pool.rs | 7 ++ crates/xcl/src/hle/d3d12x/list_x.rs | 137 +++++++++++++++++++++++- crates/xcl/src/hle/d3d12x/title_list.rs | 86 ++++++++++----- 3 files changed, 199 insertions(+), 31 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs index d29bf1e16e..ba29bb3c44 100644 --- a/crates/xcl/src/hle/d3d12x/alloc_pool.rs +++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs @@ -176,6 +176,13 @@ pub unsafe fn note_resubmits(queue: *mut c_void, lists: &[*mut c_void]) -> usize found } +/// Whether the GPU has not finished the last submit of the PC list `list` (#1452: it must not be +/// submitted again before that; `title_list` records the title's next recording elsewhere). +pub fn in_flight(list: usize) -> bool { + let g = STATE.lock().unwrap(); + g.as_ref().and_then(|s| s.last_submit.get(&list)).is_some_and(|l| unsafe { l.fence.GetCompletedValue() } < l.value) +} + /// `lists` were just submitted to `queue`. pub unsafe fn executed(queue: *mut c_void, lists: &[*mut c_void]) { if !enabled() || queue.is_null() { diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 06cca160a5..97df3263c3 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -2477,6 +2477,45 @@ 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); } +/// 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; +/// NVIDIA removes the device). The new recording goes onto a spare PC list of the wrapper whose +/// submits are done, or a new one, reset like `primary` would be. None: it could not be. +pub(super) unsafe fn reset_stand_in(wrapper: *mut c_void, primary: *mut c_void, alloc: usize, pso: usize) -> Option { + let ty = list_type(primary); + if ty == D3D12_COMMAND_LIST_TYPE_BUNDLE || alloc == 0 { + return None; + } + 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 + } + }; + if reset_pc(spare, alloc, pso) < 0 { + super::title_list::put_spare(wrapper, spare); + return None; + } + static N: AtomicU64 = AtomicU64::new(0); + let n = N.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 4 || n.is_power_of_two() { + crate::xlog_info!("D3D12.X: a command list reset while its last submit is on the GPU records on another PC list (#{n})"); + } + Some(spare as usize) +} + /// Deferred mid-list split for `Wait32/64BitValueX` recorded after a `Write64BitValue*` in the /// same command list: closes `list` (preserving its earlier `Write64` signals on segment N) and /// opens/reuses a sibling PC command list on the same `ID3D12CommandAllocator` as segment N+1, @@ -3663,12 +3702,28 @@ fn is_occlusion(ty: D3D12_QUERY_TYPE) -> bool { type QueryFn = unsafe extern "system" fn(*mut c_void, usize, D3D12_QUERY_TYPE, u32); -/// command list #10 Reset(allocator, initial pipeline): updates allocator/pipeline and clears -/// per-recording state (queries, index buffer, depth bias, pending waits, written ranges) +/// command list #10 Reset(allocator, initial pipeline) as console code calls it on a PC list. +/// When `this` is the PC list a title's list (`title_list`) records on, the call came through +/// that list's thunk to its PC list – the newer console layout's Reset (#139, allocator, NULL, +/// 0) does, as it is not the title list's own #10 – and it is that list's Reset (`title_list:: +/// reset`: the primary PC list again, or a stand-in while the primary's last submit runs). Else +/// `reset_pc`. /// /// # Safety /// `this` must be a valid adopted `ID3D12GraphicsCommandList` pointer. pub unsafe extern "system" fn reset_x(this: *mut c_void, alloc: usize, pso: usize) -> i32 { + if let Some(w) = super::title_list::wrapper_of(this) { + return super::title_list::reset(w, alloc, pso); + } + reset_pc(this, alloc, pso) +} + +/// Reset of the PC list `this` (allocator, initial pipeline): updates allocator/pipeline and +/// clears per-recording state (queries, index buffer, depth bias, pending waits, written ranges) +/// +/// # Safety +/// `this` must be a valid adopted `ID3D12GraphicsCommandList` pointer. +pub(super) unsafe fn reset_pc(this: *mut c_void, alloc: usize, pso: usize) -> i32 { // A failed native Reset leaves the old recording alive. Do not discard its tracked state or // transfer its allocations until the driver accepts the new recording. let ext = *(this as *const usize); @@ -6137,6 +6192,84 @@ mod tests { } } + /// #1452: the title Resets its list and submits the new recording while the GPU still runs + /// the previous one (held here by a queue Wait on a fence not yet signalled). The new + /// recording must be on another PC list (the PC forbids submitting one again before its last + /// submit is done, debug layer id 553), also one more time; once the GPU is done, the list + /// records on its own PC list again. Both ways a title Resets: the list's #10, and the newer + /// console layout's #139, which goes through the list's thunk to the PC list it records on + /// (`reset_x` on that one) – the retail title's way, which the stand-in did not see at first. + #[test] + fn a_reset_while_the_last_submit_runs_records_on_another_pc_list() { + 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"); + }; + for newer_layout in [false, true] { + reset_while_the_last_submit_runs(&dev, newer_layout); + } + } + + fn reset_while_the_last_submit_runs(dev: &ID3D12Device, newer_layout: bool) { + unsafe { + let ty = D3D12_COMMAND_LIST_TYPE_DIRECT; + let q: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: ty, ..Default::default() }).unwrap(); + 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); + let w = super::super::title_list::wrap(primary); + let slot = |i: usize| *(*(w as *const *const usize)).add(i); + let close: unsafe extern "system" fn(*mut c_void) -> i32 = std::mem::transmute(slot(9)); + let reset_10: unsafe extern "system" fn(*mut c_void, usize, usize) -> i32 = std::mem::transmute(slot(10)); + // #139 (allocator, NULL, 0): the thunk passes the PC list last recorded on (`F_BACKING`) + let reset = |w: *mut c_void, a: usize, pso: usize, last: *mut c_void| if newer_layout { reset_x(last, a, pso) } else { reset_10(w, a, pso) }; + let release: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(slot(2)); + let exec: unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void) = + std::mem::transmute(*(*(q.as_raw() as *const *const usize)).add(PC_QUEUE_EXECUTE_COMMAND_LISTS)); + let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let done: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + // Close, then submit as ExecuteCommandLists does: the PC lists the title's list stands for + let submit = || { + assert_eq!(close(w), 0); + let mut segs = Vec::new(); + assert!(super::super::title_list::push_segments(w, &mut segs)); + let again = super::super::alloc_pool::note_resubmits(q.as_raw(), &segs); + exec(q.as_raw(), segs.len() as u32, segs.as_ptr()); + super::super::alloc_pool::executed(q.as_raw(), &segs); + (segs, again) + }; + + q.Wait(&gate, 1).unwrap(); + let (first, _) = submit(); + assert_eq!(first, vec![primary]); + assert_eq!(reset(w, a, 0, first[0]), 0); + let (second, again) = submit(); + assert_eq!(reset(w, a, 0, second[0]), 0); + let (third, again3) = submit(); + gate.Signal(1).unwrap(); + q.Signal(&done, 1).unwrap(); + crate::gpu::fence::wait(&done, 1, &dev, None, 5000).expect("the queue finishes"); + assert_eq!(reset(w, a, 0, third[0]), 0); + let (fourth, _) = submit(); + q.Signal(&done, 2).unwrap(); + crate::gpu::fence::wait(&done, 2, &dev, None, 5000).expect("the queue finishes"); + let removed = dev.GetDeviceRemovedReason(); + assert_eq!(release(w), 0); + + let how = if newer_layout { "Reset #139" } else { "Reset #10" }; + assert_eq!(second.len(), 1); + assert_ne!(second[0], primary, "{how}: the new recording must not be on the PC list still on the GPU"); + assert_eq!(again, 0, "{how}: no PC list is submitted while its last submit runs"); + assert_eq!(third.len(), 1); + assert!(third[0] != primary && third[0] != second[0], "{how}: nor on the one standing in, also still on the GPU"); + assert_eq!(again3, 0, "{how}"); + assert_eq!(fourth, vec![primary], "{how}: once the GPU is done the list records on its own PC list"); + assert!(removed.is_ok()); + } + } + /// Reproduces the exact intra-list fork-join pattern seen on retail compute queues: /// q_compute list O_c: Write64(cell_A, frame) -> Wait64(cell_B >= frame) -> Write64(cell_C, frame) /// q_direct list O_d: Wait64(cell_A >= frame) -> Write64(cell_B, frame) diff --git a/crates/xcl/src/hle/d3d12x/title_list.rs b/crates/xcl/src/hle/d3d12x/title_list.rs index 05de94b66d..0da7acd4cd 100644 --- a/crates/xcl/src/hle/d3d12x/title_list.rs +++ b/crates/xcl/src/hle/d3d12x/title_list.rs @@ -46,6 +46,10 @@ struct SegmentBook { extra_active: Vec, /// Closed extra PC command lists from earlier recordings, kept for reuse on future splits. spares: Vec, + /// A PC command list recording in place of `primary`: at the title's Reset the GPU had not + /// 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, } /// Wrapper address -> split segment book (populated lazily only for lists that split). @@ -140,39 +144,51 @@ unsafe extern "system" fn close(this: *mut c_void) -> HRESULT { hr } -/// #10 Reset(allocator, initial_pso): resets the primary PC list (`F_PRIMARY`) via `list_x::reset_x` +/// #10 Reset(allocator, initial_pso): resets the primary PC list (`F_PRIMARY`) via `list_x::reset_pc` /// (calling directly rather than through the dual-dispatch vtable thunk so console state always /// resets even though this wrapper sits in `xcl.exe`), restores `F_BACKING = F_PRIMARY`, and moves -/// any extra split segments into the per-list spare pool. -unsafe extern "system" fn reset(this: *mut c_void, alloc: usize, pso: usize) -> HRESULT { +/// any extra split segments into the per-list spare pool. While the GPU has not finished +/// primary's last submit, the new recording goes onto a spare instead (`first`). The newer console +/// layout's Reset (#139) reaches it through `list_x::reset_x` on the active PC list. +pub(super) unsafe extern "system" fn reset(this: *mut c_void, alloc: usize, pso: usize) -> HRESULT { let primary = *((this as usize + F_PRIMARY) as *const *mut c_void); - let hr = if super::real::is_adopted(primary) { - super::list_x::reset_x(primary, alloc, pso) + let adopted = super::real::is_adopted(primary); + let stand_in = if adopted && super::alloc_pool::in_flight(primary as usize) { + super::list_x::reset_stand_in(this, primary, alloc, pso) + } else { + None + }; + let hr = if stand_in.is_some() { + 0 + } else if adopted { + super::list_x::reset_pc(primary, alloc, pso) } else { let f: unsafe extern "system" fn(*mut c_void, usize, usize) -> HRESULT = std::mem::transmute(pc_slot(primary, 10)); f(primary, alloc, pso) }; if hr >= 0 { - *((this as usize + F_BACKING) as *mut usize) = primary as usize; + let active = stand_in.unwrap_or(primary as usize); + *((this as usize + F_BACKING) as *mut usize) = active; let moved = { let mut sg = SEGMENTS.lock().unwrap(); - sg.as_mut() - .and_then(|m| m.get_mut(&(this as usize))) - .map(|b| { - let old = std::mem::take(&mut b.extra_active); - b.spares.extend(old.iter().copied()); - old - }) - .unwrap_or_default() + let m = sg.get_or_insert_with(HashMap::new); + if stand_in.is_some() || m.contains_key(&(this as usize)) { + let b = m.entry(this as usize).or_default(); + let mut old = std::mem::take(&mut b.extra_active); + old.extend(std::mem::replace(&mut b.first, stand_in)); + b.spares.extend(old.iter().copied()); + old + } else { + Vec::new() + } }; - if !moved.is_empty() { + if !moved.is_empty() || stand_in.is_some() { let mut wg = WRAPPER_OF.lock().unwrap(); - if let Some(m) = wg.as_mut() { - for &seg in &moved { - m.remove(&seg); - } - m.insert(primary as usize, this as usize); + let m = wg.get_or_insert_with(HashMap::new); + for &seg in moved.iter().chain([primary as usize].iter()) { + m.remove(&seg); } + m.insert(active, this as usize); drop(wg); for seg in moved { super::bind::reset(seg as *mut c_void, 0, 0); @@ -219,9 +235,10 @@ pub fn push_segments(list: *mut c_void, out: &mut Vec<*mut c_void>) -> bool { let Some(primary) = backing(list) else { return false; }; - out.push(primary); let sg = SEGMENTS.lock().unwrap(); - if let Some(book) = sg.as_ref().and_then(|m| m.get(&(list as usize))) { + let book = sg.as_ref().and_then(|m| m.get(&(list as usize))); + 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 { out.push(seg as *mut c_void); } @@ -245,10 +262,19 @@ pub(super) fn can_split(wrapper: *mut c_void) -> bool { .is_none_or(|b| b.extra_active.len() < MAX_EXTRA_SEGMENTS) } -/// Pop a previously created closed extra PC command list from `wrapper`'s spare pool for reuse. +/// Pop a previously created closed extra PC command list from `wrapper`'s spare pool for reuse +/// (the last one whose submits the GPU has finished). pub(super) fn pop_spare(wrapper: *mut c_void) -> Option<*mut c_void> { let mut sg = SEGMENTS.lock().unwrap(); - sg.as_mut()?.get_mut(&(wrapper as usize))?.spares.pop().map(|p| p as *mut c_void) + let spares = &mut sg.as_mut()?.get_mut(&(wrapper as usize))?.spares; + let k = spares.iter().rposition(|&p| !super::alloc_pool::in_flight(p))?; + Some(spares.remove(k) as *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) { + let mut sg = SEGMENTS.lock().unwrap(); + sg.get_or_insert_with(HashMap::new).entry(wrapper as usize).or_default().spares.push(pc as usize); } /// Switch `wrapper` from closed segment `old_pc` to newly opened segment `new_pc`. @@ -271,15 +297,16 @@ pub(super) unsafe fn activate_segment(wrapper: *mut c_void, old_pc: *mut c_void, /// For `KickoffX` on an already-split list: returns `(primary, prior_closed_segments, extra_to_reclaim)` /// when `active_pc != primary`, switches `F_BACKING` back to `primary`, and moves all extra /// segments (including `active_pc`) into `spares` so recording resumes cleanly on `primary`. +/// (`primary` here is the recording's first segment: `first` when one stands in.) pub(super) unsafe fn reclaim_for_kickoff(active_pc: *mut c_void) -> Option<(*mut c_void, Vec<*mut c_void>, Vec)> { let wrapper = wrapper_of(active_pc)?; - let primary = *((wrapper as usize + F_PRIMARY) as *const *mut c_void); + let mut sg = SEGMENTS.lock().unwrap(); + let book = sg.as_mut().and_then(|m| m.get_mut(&(wrapper as usize)))?; + let primary = book.first.map_or_else(|| *((wrapper as usize + F_PRIMARY) as *const *mut c_void), |f| f as *mut c_void); if primary == active_pc { return None; } let (prior, reclaimed) = { - let mut sg = SEGMENTS.lock().unwrap(); - let book = sg.as_mut().and_then(|m| m.get_mut(&(wrapper as usize)))?; let extra = std::mem::take(&mut book.extra_active); let mut prior = Vec::with_capacity(extra.len()); prior.push(primary); @@ -291,6 +318,7 @@ pub(super) unsafe fn reclaim_for_kickoff(active_pc: *mut c_void) -> Option<(*mut book.spares.extend(extra.iter().copied()); (prior, extra) }; + drop(sg); *((wrapper as usize + F_BACKING) as *mut usize) = primary as usize; { let mut wg = WRAPPER_OF.lock().unwrap(); @@ -357,14 +385,14 @@ unsafe extern "system" fn release(this: *mut c_void) -> u32 { if let Some(m) = wg.as_mut() { m.remove(&(pc as usize)); if let Some(ref b) = book { - for &seg in b.extra_active.iter().chain(b.spares.iter()) { + for &seg in b.extra_active.iter().chain(b.spares.iter()).chain(b.first.iter()) { m.remove(&seg); } } } } if let Some(b) = book { - for seg in b.extra_active.into_iter().chain(b.spares.into_iter()) { + for seg in b.extra_active.into_iter().chain(b.spares.into_iter()).chain(b.first) { let raw = seg as *mut c_void; super::bind::forget(raw); let rel: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(pc_slot(raw, 2));