From 3671a8ca8d9bbbbe56f5becf1c0dac3b4547d898 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 21:39:28 -0800 Subject: [PATCH] D3D12.X: reserve allocator state before native submission Capture and pin each list recording before ExecuteCommandLists can reach the driver. Associate the reservation with exactly one queue fence after native execution, and fail closed before later chunks if bookkeeping cannot be reserved. This closes the reset/release race between native execution and allocator retirement while preserving exact effects for the chunks that actually ran. Checked with the GNU Windows-target cargo check; Windows/MSVC, GPU, and title smoke execution were not available on this host. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/alloc_pool.rs | 156 ++++++++++++++++++------ crates/xcl/src/hle/d3d12x/list_x.rs | 100 ++++++++++----- crates/xcl/src/hle/d3d12x/real.rs | 26 ++-- 3 files changed, 203 insertions(+), 79 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs index 1f9326fdde..e12db4060f 100644 --- a/crates/xcl/src/hle/d3d12x/alloc_pool.rs +++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs @@ -260,9 +260,11 @@ fn release_submit_pins(s: &mut State, entries: &[SubmitEntry]) { } } -fn record_submit(s: &mut State, entries: &[SubmitEntry], queue: usize, fence: &ID3D12Fence, value: u64) { +fn record_submit(s: &mut State, entries: &[SubmitEntry], queue: usize, fence: &ID3D12Fence, value: u64) -> u64 { + let mut backing_mark_writes = 0; for entry in entries { if let Some(backing) = entry.backing { + backing_mark_writes += 1; s.backings.entry(backing).or_default().marks.insert(queue, (fence.clone(), value)); } if s.list_lifetimes.get(&entry.list) == Some(&entry.lifetime) { @@ -273,6 +275,7 @@ fn record_submit(s: &mut State, entries: &[SubmitEntry], queue: usize, fence: &I } } release_submit_pins(s, entries); + backing_mark_writes } /// Capture and pin the exact backing and recording that a native submit will execute. The caller @@ -346,7 +349,7 @@ impl PendingSubmit { if self.entries.is_empty() { return true; } - let mut g = STATE.lock().unwrap(); + let mut g = lock_for_submit(); let Some(s) = g.as_mut() else { return false }; let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return false }; let key = queue as usize; @@ -359,13 +362,17 @@ impl PendingSubmit { } let (fence, value) = { let (fence, value) = s.fences.get_mut(&key).unwrap(); + SUBMIT.signal_attempts.fetch_add(1, Ordering::Relaxed); if q.Signal(&*fence, *value + 1).is_err() { + SUBMIT.signal_failures.fetch_add(1, Ordering::Relaxed); return false; } *value += 1; (fence.clone(), *value) }; - record_submit(s, &self.entries, key, &fence, value); + let backing_mark_writes = record_submit(s, &self.entries, key, &fence, value); + SUBMIT.lists_marked.fetch_add(self.entries.len() as u64, Ordering::Relaxed); + SUBMIT.backing_mark_writes.fetch_add(backing_mark_writes, Ordering::Relaxed); self.entries.clear(); drop(g); sweep_release_owners(); @@ -375,11 +382,62 @@ impl PendingSubmit { #[cfg(test)] fn finish_with_mark(mut self, queue: usize, fence: &ID3D12Fence, value: u64) { let mut g = STATE.lock().unwrap(); - record_submit(g.as_mut().unwrap(), &self.entries, queue, fence, value); + let _ = record_submit(g.as_mut().unwrap(), &self.entries, queue, fence, value); self.entries.clear(); } } +fn reserve_and_execute_with( + failed: &mut bool, + begin: impl FnOnce() -> Option, + prepare: impl FnOnce(), + arm: impl FnOnce(B) -> P, + execute: impl FnOnce(), + finish: impl FnOnce(P) -> bool, +) -> bool { + if *failed { + return false; + } + let Some(begin) = begin() else { + *failed = true; + return false; + }; + prepare(); + let pending = arm(begin); + execute(); + let _ = finish(pending); + true +} + +#[derive(Default)] +pub(super) struct SubmissionGate { + failed: bool, +} + +impl SubmissionGate { + /// `prepare` runs before the reservation is armed; `execute` must contain only the native call. + pub(super) unsafe fn submit( + &mut self, + queue: *mut c_void, + lists: &[*mut c_void], + prepare: impl FnOnce(), + execute: impl FnOnce(), + ) -> bool { + reserve_and_execute_with( + &mut self.failed, + || begin_submit(lists), + prepare, + BeginSubmit::execution_possible, + execute, + |pending| pending.finish(queue), + ) + } + + pub(super) fn failed(&self) -> bool { + self.failed + } +} + /// `XCL_ALLOC_SWAP=0` turns it off. pub fn enabled() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); @@ -510,43 +568,11 @@ pub fn in_flight(list: usize) -> bool { || s.last_submit.get(&list).is_some_and(|l| unsafe { l.fence.GetCompletedValue() } < l.value) } -/// `lists` were just submitted to `queue`. +/// Compatibility helper for tests that submit directly instead of using `SubmissionGate`. +#[cfg(test)] 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 = lock_for_submit(); - 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) { - 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(); - SUBMIT.signal_attempts.fetch_add(1, Ordering::Relaxed); - if q.Signal(&*f, *v + 1).is_err() { - SUBMIT.signal_failures.fetch_add(1, Ordering::Relaxed); - return; - } - *v += 1; - (f.clone(), *v) - }; - let mut backing_mark_writes = 0u64; - for &l in lists { - if let Some(&b) = s.of_list.get(&(l as usize)) { - backing_mark_writes += 1; - 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 }); - } - SUBMIT.lists_marked.fetch_add(lists.len() as u64, Ordering::Relaxed); - SUBMIT.backing_mark_writes.fetch_add(backing_mark_writes, Ordering::Relaxed); + let Some(begin) = begin_submit(lists) else { return }; + let _ = begin.execution_possible().finish(queue); } /// Whether the GPU may still run a recording made on the title's allocator `alloc`. @@ -820,6 +846,56 @@ mod tests { assert_eq!(execute_topology(4), (1, 3)); } + #[test] + fn reserved_submit_orders_prepare_arm_execute_and_finish() { + use std::cell::RefCell; + let calls = RefCell::new(Vec::new()); + let mut failed = false; + let submitted = reserve_and_execute_with( + &mut failed, + || { + calls.borrow_mut().push("begin"); + Some(1) + }, + || calls.borrow_mut().push("prepare"), + |begin| { + calls.borrow_mut().push("arm"); + begin + 1 + }, + || calls.borrow_mut().push("execute"), + |pending| { + calls.borrow_mut().push("finish-failed"); + assert_eq!(pending, 2); + false + }, + ); + assert!(submitted && !failed, "marker failure cannot undo a native execution"); + assert_eq!(*calls.borrow(), ["begin", "prepare", "arm", "execute", "finish-failed"]); + } + + #[test] + fn begin_failure_stops_later_chunks_and_publication() { + use std::cell::Cell; + let mut failed = false; + let executed = Cell::new(0); + let published = Cell::new(0); + for begin_succeeds in [true, false, true] { + let submitted = reserve_and_execute_with( + &mut failed, + || begin_succeeds.then_some(()), + || {}, + |()| (), + || executed.set(executed.get() + 1), + |_| true, + ); + if submitted { + published.set(published.get() + 1); + } + } + assert!(failed); + assert_eq!((executed.get(), published.get()), (1, 1)); + } + #[test] fn submit_reservation_keeps_pre_reset_attribution_across_queues() { use std::mem::{offset_of, size_of}; diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 69d0774a53..36a830bc15 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -2468,15 +2468,16 @@ unsafe fn execute_submission_plan_with_completions( queue: *mut c_void, plan: &SubmissionPlan, external_waits: &[PendingWait], - mut submit: impl FnMut(SubmissionChunk<'_>) -> Option, -) -> Vec { + mut submit: impl FnMut(SubmissionChunk<'_>) -> (bool, Option), +) -> (Vec, bool) { let chunk = |start, end| SubmissionChunk { lists: &plan.lists[start..end], effects: &plan.effects[start..end], needs_cpu_completion: plan.chunk_needs_cpu_completion(start, end, external_waits), }; if !plan.has_waits { - return submit(chunk(0, plan.lists.len())).into_iter().collect(); + let (submitted, completion) = submit(chunk(0, plan.lists.len())); + return (completion.into_iter().collect(), submitted); } let mut completions = Vec::new(); let mut start = 0usize; @@ -2489,7 +2490,11 @@ unsafe fn execute_submission_plan_with_completions( continue; } if i > start { - completions.extend(submit(chunk(start, i))); + let (submitted, completion) = submit(chunk(start, i)); + if !submitted { + return (completions, false); + } + completions.extend(completion); } if after_cpu_write { for completion in completions.drain(..) { @@ -2500,25 +2505,37 @@ unsafe fn execute_submission_plan_with_completions( start = i; } if start < plan.lists.len() { - completions.extend(submit(chunk(start, plan.lists.len()))); + let (submitted, completion) = submit(chunk(start, plan.lists.len())); + if !submitted { + return (completions, false); + } + completions.extend(completion); } - completions + (completions, true) +} + +pub(super) unsafe fn execute_submission_plan_until_failure_on( + queue: *mut c_void, + plan: &SubmissionPlan, + submit: impl FnMut(SubmissionChunk<'_>) -> (bool, Option), +) -> (Vec, bool) { + execute_submission_plan_with_completions(queue, plan, &[], submit) } /// Execute a plan for an ordinary queue submission, retaining deferred CPU-write receipts. pub(super) unsafe fn execute_submission_plan_with_completions_on( queue: *mut c_void, plan: &SubmissionPlan, - submit: impl FnMut(SubmissionChunk<'_>) -> Option, + mut submit: impl FnMut(SubmissionChunk<'_>) -> Option, ) -> Vec { - execute_submission_plan_with_completions(queue, plan, &[], submit) + execute_submission_plan_with_completions(queue, plan, &[], |chunk| (true, submit(chunk))).0 } /// Execute an immutable submission plan, splitting before an unsatisfied memory wait. pub(super) unsafe fn execute_submission_plan_on(queue: *mut c_void, plan: &SubmissionPlan, mut submit: impl FnMut(SubmissionChunk<'_>)) { let _ = execute_submission_plan_with_completions(queue, plan, &[], |chunk| { submit(chunk); - None + (true, None) }); } @@ -3807,25 +3824,29 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { let kickoff_split = super::title_list::reclaim_for_kickoff(this); let mut prior_cpu_completions = Vec::new(); let mut wait_after_cpu_write = false; + let mut gate = super::alloc_pool::SubmissionGate::default(); if let Some((_, ref prior, _)) = kickoff_split { if !prior.is_empty() { let plan = submission_plan(prior); wait_after_cpu_write = plan.cpu_producer_overlaps(&waits, plan.effects.len()); - prior_cpu_completions = execute_submission_plan_with_completions(q_raw, &plan, &waits, |chunk| { + let mut submitted = Vec::with_capacity(prior.len()); + let (completions, _) = execute_submission_plan_with_completions(q_raw, &plan, &waits, |chunk| { let lists = chunk.lists(); - exec(q_raw, lists.len() as u32, lists.as_ptr()); + if !gate.submit(q_raw, lists, || {}, || exec(q_raw, lists.len() as u32, lists.as_ptr())) { + return (false, None); + } + submitted.extend_from_slice(lists); copy_scratch_submitted(q_raw, lists); - super::alloc_pool::executed(q_raw, lists); - chunk.submit_effects(q_raw) + (true, chunk.submit_effects(q_raw)) }); - super::title_textures::submitted(prior); - for &p in prior { + prior_cpu_completions = completions; + super::title_textures::submitted(&submitted); + for &p in &submitted { super::title_textures::list_reset(p as usize); } } } - - if !waits.is_empty() { + if !gate.failed() && !waits.is_empty() { if wait_after_cpu_write { for completion in prior_cpu_completions.drain(..) { let _ = completion.wait(); @@ -3835,19 +3856,25 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { } let one = [this]; - exec(q_raw, 1, one.as_ptr()); - copy_scratch_submitted(q_raw, &one); - 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); - super::title_textures::list_reset(this as usize); - if !sparse_writes.is_empty() { - if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&q_raw) { - super::sparse::readback_after_execute(q, &sparse_writes); + let current_submitted = gate.submit(q_raw, &one, || {}, || exec(q_raw, 1, one.as_ptr())); + if current_submitted { + copy_scratch_submitted(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); + if !sparse_writes.is_empty() { + if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&q_raw) { + super::sparse::readback_after_execute(q, &sparse_writes); + } + } + super::cpu_writes::after(q_raw, cpu_writes); + } else { + if once(&ERR, 8) { + crate::xlog_warn!("D3D12.X: KickoffX – could not reserve submission retirement state; resetting the unsubmitted recording"); } } - super::cpu_writes::after(q_raw, cpu_writes); + // Submitted or discarded, `this` starts a new recording in the common Reset tail. + super::title_textures::list_reset(this as usize); let target = if let Some((primary, _, reclaimed)) = kickoff_split { let (ended_early, pred_buf_obj, bindings_copy) = { @@ -5763,16 +5790,27 @@ mod tests { completed.store(true, Ordering::Release); let _ = done.send(()); }); - Some(receipt) + (true, Some(receipt)) } else { assert!(!chunk.needs_cpu_completion()); assert!(completed.load(Ordering::Acquire), "the CPU producer must complete before the wait segment is submitted"); - None + (true, None) } - }); + }).0; assert!(leftovers.is_empty()); } assert_eq!(chunks, vec![vec![producer], vec![continuation]]); + + let mut callbacks = 0; + let completed_all = unsafe { + execute_submission_plan_with_completions(std::ptr::null_mut(), &plan, &[], |_| { + callbacks += 1; + (false, None) + }) + .1 + }; + assert!(!completed_all); + assert_eq!(callbacks, 1, "a failed first chunk suppresses later waits and submissions"); } #[test] diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index fac39f80b8..c15a0a1ab3 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -7866,19 +7866,29 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis let plan = super::list_x::submission_plan(&mapped); drop(preparation_stall); let mut chunks = 0usize; - let _ = super::list_x::execute_submission_plan_with_completions_on(this, &plan, |chunk| { - chunks += 1; + let mut gate = super::alloc_pool::SubmissionGate::default(); + let mut submitted = Vec::with_capacity(mapped.len()); + let _ = super::list_x::execute_submission_plan_until_failure_on(this, &plan, |chunk| { let lists = chunk.lists(); - let _ = super::alloc_pool::note_resubmits(this, lists); - f(this, lists.len() as u32, lists.as_ptr()); + if !gate.submit( + this, + lists, + || { + let _ = super::alloc_pool::note_resubmits(this, lists); + }, + || f(this, lists.len() as u32, lists.as_ptr()), + ) { + return (false, None); + } + chunks += 1; + submitted.extend_from_slice(lists); super::list_x::copy_scratch_submitted(this, lists); - super::alloc_pool::executed(this, lists); - chunk.submit_effects(this) + (true, chunk.submit_effects(this)) }); super::alloc_pool::note_execute_call(chunks); // the next uploads into textures kept in step start from the states these lists leave - super::title_textures::submitted(&mapped); - super::present::note_execute(this, &mapped); + super::title_textures::submitted(&submitted); + super::present::note_execute(this, &submitted); stop_if_device_removed(); }