diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index d68197e4a..fb530f3df 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -100,6 +100,27 @@ pub(super) fn clear_state(list: *mut c_void, pso: usize) { }); } +/// Carry bound pipeline and root-signature / root-argument state from `from` to `to` across a +/// deferred mid-list split (`to` records into `allocator` with its own fresh UMA arena while +/// `from` retains its previously allocated blocks until `allocator` resets). +pub(super) fn inherit_for_split(from: *mut c_void, to: *mut c_void, allocator: usize) { + let (layout, args, layout_gfx, args_gfx, rs_gfx, pso) = with(from, |s| { + (s.layout.clone(), s.args.clone(), s.layout_gfx.clone(), s.args_gfx.clone(), s.rs_gfx, s.pso) + }); + let (old, blocks) = with(to, |s| { + let old = std::mem::replace(&mut s.allocator, allocator); + s.arena = Default::default(); + s.layout = layout; + s.args = args; + s.layout_gfx = layout_gfx; + s.args_gfx = args_gfx; + s.rs_gfx = rs_gfx; + s.pso = pso; + (old, std::mem::take(&mut s.uma)) + }); + console_list::hold_until_reset(old, blocks); +} + /// The list is gone. pub(super) fn forget(list: *mut c_void) { if let Some(s) = STATES.lock().unwrap().as_mut().and_then(|m| m.remove(&(list as usize))) { diff --git a/crates/xcl/src/hle/d3d12x/fence_x.rs b/crates/xcl/src/hle/d3d12x/fence_x.rs index 1a9cc140e..aea8e598d 100644 --- a/crates/xcl/src/hle/d3d12x/fence_x.rs +++ b/crates/xcl/src/hle/d3d12x/fence_x.rs @@ -21,6 +21,8 @@ struct Fence { cell: Option<&'static Cell>, /// the highest value a queue was told to signal signalled: u64, + /// the highest value a queue was told to wait for + waited: u64, } /// (fences are never freed: XCL holds a reference to each) @@ -77,6 +79,13 @@ pub(super) unsafe fn note_queue_signal(fence: usize, value: u64) { } } +/// A queue was told to wait for `fence` (one of the title's) to reach `value`. +pub(super) fn note_queue_wait(fence: usize, value: u64) { + let mut g = FENCES.lock().unwrap_or_else(|e| e.into_inner()); + let f = g.get_or_insert_with(HashMap::new).entry(fence).or_default(); + f.waited = f.waited.max(value); +} + /// The CPU signalled `fence`. pub(super) fn note_cpu_signal(fence: usize) { let known = FENCES.lock().unwrap_or_else(|e| e.into_inner()).as_ref().is_some_and(|m| m.get(&fence).is_some_and(|f| f.cell.is_some())); @@ -85,6 +94,23 @@ pub(super) fn note_cpu_signal(fence: usize) { } } +/// Diagnostic summary of title fences whose completed value lags their signalled or waited value. +pub(super) fn pending_summary() -> String { + let g = FENCES.lock().unwrap_or_else(|e| e.into_inner()); + let mut parts = Vec::new(); + for (&p, f) in g.iter().flatten() { + let done = unsafe { borrowed(p, |f| f.GetCompletedValue()) }.unwrap_or(0); + if done < f.signalled || done < f.waited { + parts.push(format!("{p:#x}(done={done:#x}/sig={:#x}/wait={:#x},cell={})", f.signalled, f.waited, f.cell.is_some())); + } + } + if parts.is_empty() { + "none".into() + } else { + parts.join(", ") + } +} + /// fence #12: the address of its completed value pub(super) unsafe extern "system" fn completed_value_address(this: *mut c_void) -> *const u64 { let (cell, pending) = { diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 208010030..fb17d4d2d 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -21,7 +21,7 @@ use std::collections::HashMap; use std::ffi::c_void; use std::mem::{transmute_copy, ManuallyDrop}; use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, AtomicUsize, Ordering}; -use std::sync::Mutex; +use std::sync::{Condvar, Mutex, OnceLock}; use std::time::{Duration, Instant}; use windows::core::Interface; @@ -55,10 +55,27 @@ const TOP_TIMESTAMPS: u32 = 0xC; /// fills larger than this are not done (one pattern buffer per value, up to this size) const MAX_FILL: u64 = 256 << 20; /// Bounded wait timeout for Wait32BitValueX / Wait64BitValueX so an unsatisfied wait never hangs. +/// Overridable via `XCL_WAIT_TIMEOUT_MS` for diagnostics. const WAIT_TIMEOUT: Duration = Duration::from_secs(2); +/// Watchdog timeout for GPU `queue.Wait` so a genuinely hung GPU cycle never triggers a 30 s +/// hang, while giving heavy initial 3D frames (>1 s of dispatches) plenty of room to finish +/// cleanly without prematurely breaking synchronization. +const GPU_WAIT_WATCHDOG_TIMEOUT: Duration = Duration::from_millis(5000); /// Cap on tracked per-list written UMA ranges (for same-list write-then-wait detection). const MAX_WRITTEN_RANGES: usize = 256; +fn wait_timeout() -> Duration { + static T: OnceLock = OnceLock::new(); + *T.get_or_init(|| { + std::env::var("XCL_WAIT_TIMEOUT_MS") + .ok() + .and_then(|v| v.parse::().ok()) + .filter(|&ms| ms > 0) + .map(Duration::from_millis) + .unwrap_or(WAIT_TIMEOUT) + }) +} + fn once(counter: &AtomicU64, n: u64) -> bool { counter.fetch_add(1, Ordering::Relaxed) < n } @@ -165,6 +182,9 @@ struct PendingWait { comparison: u32, value: u64, mask: u64, + /// True if this list already recorded a `Write64BitValue*` before this wait (potential + /// intra-list fork-join where hoisting a GPU wait before list submission could deadlock). + after_write64: bool, } fn compare_u64(op: u32, lhs: u64, rhs: u64) -> Option { @@ -482,11 +502,17 @@ pub(super) unsafe fn note_render_targets(this: *mut c_void, n: u32, rtvs: *const with_bindings(this, |b| b.render_targets = Some(RenderTargets { num_targets, handles, single, dsv: d })); } -/// Set again what `b` holds (after KickoffX's Reset). -unsafe fn restore_bindings(this: *mut c_void, b: &Bindings) { +/// Set again what `b` holds (after KickoffX's Reset or a deferred mid-list split). +unsafe fn restore_bindings(this: *mut c_void, b: &Bindings, ty: D3D12_COMMAND_LIST_TYPE) { + if ty == D3D12_COMMAND_LIST_TYPE_COPY { + return; + } if !b.heaps.is_empty() { pc::(this, 28)(this, b.heaps.len() as u32, b.heaps.as_ptr()); } + if ty != D3D12_COMMAND_LIST_TYPE_DIRECT { + return; + } if let Some(t) = b.topology { pc::(this, PC_IA_SET_PRIMITIVE_TOPOLOGY)(this, t); } @@ -544,6 +570,10 @@ struct ListState { /// Sparse-window `(va, bytes)` ranges written by memory ops (`Write32/64`, `Fill*`, /// `CopyMemoryToMemoryX`, timestamps) to copy back to the CPU view after execution. sparse_writes: Vec<(usize, usize)>, + /// Non-timestamp 64-bit `(va, value)` writes recorded by `Write64BitValue{Bottom,Top}OfPipeX` + /// so `ExecuteCommandLists` / `KickoffX` can signal per-address GPU fences for cross-queue + /// `Wait64BitValueX` without blocking the submitter thread on the CPU. + write64_signals: Vec<(u64, u64)>, /// External memory waits recorded on this list pending_waits: Vec, /// bottom-of-pipe writes into memory the GPU does not see (`cpu_writes`) @@ -586,6 +616,21 @@ impl ListState { std::mem::take(&mut self.sparse_writes) } + fn push_write64_signal(&mut self, va: u64, value: u64) { + if self.write64_signals.is_empty() { + WRITE64_SIGNAL_LISTS.fetch_add(1, Ordering::AcqRel); + } + self.write64_signals.push((va, value)); + } + + fn clear_write64_signals(&mut self) -> Vec<(u64, u64)> { + if self.write64_signals.is_empty() { + return Vec::new(); + } + WRITE64_SIGNAL_LISTS.fetch_sub(1, Ordering::AcqRel); + std::mem::take(&mut self.write64_signals) + } + fn has_prior_write(&self, va: u64, size: u64) -> bool { let end = va.saturating_add(size); self.written_ranges.iter().any(|&(s, e)| va < e && s < end) @@ -619,6 +664,8 @@ static LIVE_QUEUES: Mutex> = Mutex::new(Vec::new()); static PENDING_WAIT_LISTS: AtomicUsize = AtomicUsize::new(0); /// Number of lists with recorded sparse-window memory writes (fast-path guard for post-execute readback). static SPARSE_WRITE_LISTS: AtomicUsize = AtomicUsize::new(0); +/// Number of lists with recorded non-timestamp `Write64BitValue*` signals (fast-path guard). +static WRITE64_SIGNAL_LISTS: AtomicUsize = AtomicUsize::new(0); /// Set once any list uses `RSSetDepthBiasX` (fast-path guard for Draw* hooks). static DEPTH_BIAS_USED: AtomicBool = AtomicBool::new(false); /// Set once any list uses `SetPredicationBufferX` (fast-path guard for Close/Reset hooks). @@ -694,6 +741,9 @@ pub unsafe fn on_create(list: *mut c_void, alloc: usize, pso: usize, ty: D3D12_C if !old.sparse_writes.is_empty() { SPARSE_WRITE_LISTS.fetch_sub(1, Ordering::AcqRel); } + if !old.write64_signals.is_empty() { + WRITE64_SIGNAL_LISTS.fetch_sub(1, Ordering::AcqRel); + } } m.insert(key, ListState { allocator: alloc, list_type: Some(ty), bound_pso: pso, ..Default::default() }); old @@ -724,6 +774,25 @@ pub(super) fn on_release(list: usize) { if !old.sparse_writes.is_empty() { SPARSE_WRITE_LISTS.fetch_sub(1, Ordering::AcqRel); } + if !old.write64_signals.is_empty() { + WRITE64_SIGNAL_LISTS.fetch_sub(1, Ordering::AcqRel); + } + } +} + +/// Clear per-recording sync/write tracking on a split segment moved into `title_list`'s spare pool. +pub(super) fn clear_segment_state(list: usize) { + super::title_textures::list_reset(list); + if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&list)) { + s.occlusion = Occlusion::default(); + s.written_ranges.clear(); + s.clear_sparse_writes(); + s.clear_write64_signals(); + s.clear_waits(); + s.cpu_writes.clear(); + s.predication = None; + s.pred_in_state = false; + s.bindings = Bindings::default(); } } @@ -875,20 +944,924 @@ fn note_write(list: usize, va: u64, size: u64) { LISTS.lock().unwrap().get_or_insert_with(HashMap::new).entry(list).or_default().note_write(va, size); } -unsafe fn wait_all(waits: &[PendingWait]) { +// --------------------------------------------------------------------------------------- +// per-address GPU fence bridge for monotonic 64-bit Write64BitValue* -> Wait64BitValueX +// --------------------------------------------------------------------------------------- + +/// Recent `Write32/64BitValue*` call for timeout diagnostics. +#[derive(Clone, Copy)] +struct WriteTraceEntry { + va: u64, + value: u64, + flags: u32, + list_type: i32, + what: &'static str, +} + +struct WriteTraceRing { + entries: [Option; 32], + next: usize, + total: u64, +} + +impl WriteTraceRing { + const fn new() -> Self { + Self { entries: [None; 32], next: 0, total: 0 } + } + + fn push(&mut self, e: WriteTraceEntry) { + self.entries[self.next] = Some(e); + self.next = (self.next + 1) % self.entries.len(); + self.total += 1; + } + + fn snapshot(&self) -> (u64, Vec) { + let mut out = Vec::with_capacity(self.entries.len()); + for i in 0..self.entries.len() { + let idx = (self.next + i) % self.entries.len(); + if let Some(e) = self.entries[idx] { + out.push(e); + } + } + (self.total, out) + } +} + +static WRITE_TRACE: Mutex = Mutex::new(WriteTraceRing::new()); + +fn record_write_trace(list: *mut c_void, va: u64, value: u64, flags: u32, what: &'static str) { + let ty = LISTS + .lock() + .unwrap() + .as_ref() + .and_then(|m| m.get(&(list as usize))) + .and_then(|s| s.list_type) + .map_or(-1, |t| t.0); + WRITE_TRACE.lock().unwrap().push(WriteTraceEntry { va, value, flags, list_type: ty, what }); +} + +/// Active GPU `queue.Wait(&fence, val)` tracked for exact cycle detection and deadlock watchdog. +#[derive(Clone, Copy)] +struct ArmedGpuWait { + val: u64, + waiting_queue: usize, + waiting_queue_ty: i32, + /// Per-queue submission sequence number at which this `Wait` was issued on `waiting_queue`. + wait_seq: u64, + armed_at: Instant, + after_write64: bool, +} + +/// Exact GPU `queue.Signal(&fence, val)` submission point on `queue`. +#[derive(Clone, Copy)] +struct SubmittedSignal { + val: u64, + queue: usize, + /// Per-queue submission sequence number at which this `Signal` was issued on `queue`. + seq: u64, +} + +/// Per-address GPU fence state bridging `Write64BitValue{Bottom,Top}OfPipeX` to cross-queue +/// `Wait64BitValueX` (`GREATER_EQUAL`, full 64-bit mask). +#[derive(Default)] +struct SyncCell { + fence: Option, + /// Raw `ID3D12Device` pointer owning `fence`. + device: usize, + /// Highest non-zero value recorded in a `Write64BitValue*` targeting this VA. + recorded_max: u64, + /// Command list type of the most recent recording advancing `recorded_max`. + recorded_list_type: Option, + /// Last queue the recording list was executed on (if known). + recorded_last_queue: Option, + /// Highest value submitted via `queue.Signal(&fence, v)` or released on CPU. + submitted_max: u64, + /// Queue that issued the latest GPU `Signal` (`None` if released on CPU). + submitted_queue: Option, + /// Highest value explicitly released on CPU (cycle-break or watchdog). Protects against + /// vkd3d-proton rewinding `fence->virtual_value` when an older in-flight GPU signal retires. + cpu_signaled_max: u64, + /// Set once a strictly decreasing write (`value < submitted_max`) is observed at this VA, + /// disabling GPU-fence bridging and falling back to CPU polling. + non_monotonic: bool, + /// Active GPU `queue.Wait(&fence, v)` calls on this cell not yet confirmed completed on GPU. + armed_waits: Vec, + /// Active GPU `queue.Signal(&fence, v)` calls on this cell not yet confirmed completed on GPU. + submitted_signals: Vec, +} + +// SAFETY: `ID3D12Fence` is a free-threaded COM object in D3D12. +unsafe impl Send for SyncCell {} + +/// Tracked title `ID3D12CommandQueue::Wait` / `Signal` edges on a title `ID3D12Fence`, used so +/// exact cycle detection sees mixed cycles involving both `Wait64BitValueX` and title fences. +#[derive(Default)] +struct TitleFenceSync { + waits: Vec<(u64, usize, u64)>, // (val, waiting_queue, wait_seq) + signals: Vec, // (val, signaling_queue, sig_seq) +} + +#[derive(Default)] +struct SyncGraph { + cells: HashMap, + title_fences: HashMap, + queue_seq: HashMap, +} + +impl SyncGraph { + fn next_seq(&mut self, queue: usize) -> u64 { + let s = self.queue_seq.entry(queue).or_insert(0); + *s += 1; + *s + } +} + +static SYNC_GRAPH: Mutex> = Mutex::new(None); +static ARMED_GPU_WAITS: AtomicUsize = AtomicUsize::new(0); +static SYNC_WATCHDOG_WAKE: OnceLock<(Mutex<()>, Condvar)> = OnceLock::new(); +static QUEUE_IDS: Mutex> = Mutex::new(Vec::new()); + +fn queue_id(q: usize) -> usize { + let mut g = QUEUE_IDS.lock().unwrap(); + if let Some(pos) = g.iter().position(|&x| x == q) { + pos + } else { + let id = g.len(); + g.push(q); + id + } +} + +/// Remove any `armed_waits` and `submitted_signals` already satisfied on the GPU (or if the device +/// was removed). Returns the fence's current completed value (or `0` if no fence exists yet). +unsafe fn prune_completed_waits(cell: &mut SyncCell) -> u64 { + let Some(ref fence) = cell.fence else { return 0 }; + let completed = fence.GetCompletedValue(); + if completed == u64::MAX { + let removed = cell.armed_waits.len(); + cell.armed_waits.clear(); + cell.submitted_signals.clear(); + if removed > 0 { + ARMED_GPU_WAITS.fetch_sub(removed, Ordering::AcqRel); + } + return completed; + } + if !cell.armed_waits.is_empty() { + let before = cell.armed_waits.len(); + cell.armed_waits.retain(|aw| aw.val > completed); + let removed = before - cell.armed_waits.len(); + if removed > 0 { + ARMED_GPU_WAITS.fetch_sub(removed, Ordering::AcqRel); + } + } + if !cell.submitted_signals.is_empty() { + cell.submitted_signals.retain(|s| s.val > completed); + } + completed +} + +/// Prune completed waits/signals from a tracked title `ID3D12Fence`. +unsafe fn prune_title_fence(fence_raw: usize, tf: &mut TitleFenceSync) { + if tf.waits.is_empty() && tf.signals.is_empty() { + return; + } + let p = fence_raw as *mut c_void; + let Some(f) = ID3D12Fence::from_raw_borrowed(&p) else { return }; + let completed = f.GetCompletedValue(); + if completed == u64::MAX { + tf.waits.clear(); + tf.signals.clear(); + } else if completed > 0 { + tf.waits.retain(|&(val, _, _)| val > completed); + tf.signals.retain(|s| s.val > completed); + } +} + +/// Exact `(queue, seq)` cycle detection BEFORE emitting `sig_q.Signal(&cell_va_fence, sig_val)`. +/// +/// Theorem: in any GPU deadlock cycle of length `k >= 1` (`q_0 -> q_1 -> ... -> q_0`), every queue +/// `q_i` submits its `Wait` strictly before its `Signal` (`wait_seq < sig_seq`). Therefore the +/// chronologically last call closing any cycle is ALWAYS a `Signal`. Checking the exact submitted +/// `(queue, seq)` graph right before emitting each `Signal` catches 100% of cycles (including +/// same-queue self-deadlocks, 2..N-queue cycles across rotating compute queues, and mixed cycles +/// involving title `ID3D12Fence` waits/signals) before any cyclic wait-signal pair reaches Vulkan. +/// +/// Returns `true` iff emitting `sig_q.Signal` for `(target_va, sig_val)` would close a cycle. +unsafe fn would_signal_close_cycle(graph: &mut SyncGraph, sig_q: usize, target_va: u64, sig_val: u64) -> bool { + // Prune completed waits/signals on target cell first. + let target_waiters: Vec<(usize, u64)> = { + let Some(target) = graph.cells.get_mut(&target_va) else { return false }; + let completed = prune_completed_waits(target); + if completed == u64::MAX || target.armed_waits.is_empty() { + return false; + } + target.armed_waits.iter().filter(|aw| aw.val <= sig_val).map(|aw| (aw.waiting_queue, aw.wait_seq)).collect() + }; + if target_waiters.is_empty() { + return false; + } + // k = 1: direct same-queue self-deadlock (`sig_q` is already waiting on `target_va <= sig_val`). + if target_waiters.iter().any(|&(wq, _)| wq == sig_q) { + return true; + } + + // Prune all cells & title fences and build exact edge list: (waiter_q, wait_seq, prod_q, prod_sig_seq). + // Include earlier submitted signals on `target_va` too (e.g. frame N-1 wait -> signal). + let mut edges: Vec<(usize, u64, usize, u64)> = Vec::new(); + for (&_va, cell) in graph.cells.iter_mut() { + if cell.armed_waits.is_empty() { + continue; + } + let completed = prune_completed_waits(cell); + if completed == u64::MAX || cell.armed_waits.is_empty() { + continue; + } + for aw in &cell.armed_waits { + // Earliest submitted GPU signal satisfying `aw.val` (matches vkd3d-proton update_count order). + if let Some(s) = cell.submitted_signals.iter().find(|s| s.val >= aw.val) { + edges.push((aw.waiting_queue, aw.wait_seq, s.queue, s.seq)); + } + } + } + for (&tf_raw, tf) in graph.title_fences.iter_mut() { + prune_title_fence(tf_raw, tf); + for &(val, wq, wseq) in &tf.waits { + if let Some(s) = tf.signals.iter().find(|s| s.val >= val) { + edges.push((wq, wseq, s.queue, s.seq)); + } + } + } + if edges.is_empty() { + return false; + } + + // BFS over `(queue, limit_seq)`: all waits on `sig_q` sit before our new `sig_q.Signal` (`u64::MAX`). + let mut best_limit: HashMap = HashMap::new(); + let mut stack: Vec<(usize, u64)> = vec![(sig_q, u64::MAX)]; + best_limit.insert(sig_q, u64::MAX); + while let Some((cur_q, limit_seq)) = stack.pop() { + for &(wq, wseq, pq, pseq) in &edges { + if wq != cur_q || wseq >= limit_seq { + continue; + } + // If `pq` has a wait on `target_va <= sig_val` strictly BEFORE `pq`'s signal `pseq`, + // then `pq`'s signal cannot execute until `target_va` completes -> exact cycle! + if target_waiters.iter().any(|&(twq, twseq)| twq == pq && twseq < pseq) { + return true; + } + let prev = best_limit.get(&pq).copied().unwrap_or(0); + if pseq > prev { + best_limit.insert(pq, pseq); + stack.push((pq, pseq)); + } + } + } + false +} + +/// Record a title `ID3D12CommandQueue::Wait(fence, value)` in the exact sync graph. +pub(super) unsafe fn note_title_queue_wait(queue: usize, fence: usize, value: u64) { + if queue == 0 || fence == 0 || value == 0 { + return; + } + static LOGGED: AtomicU64 = AtomicU64::new(0); + if once(&LOGGED, 8) { + crate::xlog_info!("D3D12.X: title ID3D12CommandQueue::Wait on q{} fence {fence:#x} >= {value:#x}", queue_id(queue)); + } + let mut g = SYNC_GRAPH.lock().unwrap(); + let graph = g.get_or_insert_with(SyncGraph::default); + let seq = graph.next_seq(queue); + let tf = graph.title_fences.entry(fence).or_default(); + prune_title_fence(fence, tf); + tf.waits.push((value, queue, seq)); +} + +/// Record a title `ID3D12CommandQueue::Signal(fence, value)` in the exact sync graph. +pub(super) unsafe fn note_title_queue_signal(queue: usize, fence: usize, value: u64) { + if queue == 0 || fence == 0 || value == 0 { + return; + } + let mut g = SYNC_GRAPH.lock().unwrap(); + let graph = g.get_or_insert_with(SyncGraph::default); + let seq = graph.next_seq(queue); + let tf = graph.title_fences.entry(fence).or_default(); + prune_title_fence(fence, tf); + tf.signals.push(SubmittedSignal { val: value, queue, seq }); +} + +/// Before a title `ID3D12CommandQueue::Signal(title_fence, value)` is submitted, check if it would +/// close a mixed cycle passing through any `Wait64BitValueX` `SyncCell`. If so, release that +/// `SyncCell` on CPU BEFORE the title signal executes so Vulkan never enters a semaphore cycle. +pub(super) unsafe fn break_cycles_before_title_signal(sig_q: usize, title_fence: usize, sig_val: u64) { + if sig_q == 0 || title_fence == 0 || sig_val == 0 { + return; + } + let to_release: Vec<(u64, u64, ID3D12Fence)> = { + let mut g = SYNC_GRAPH.lock().unwrap(); + let Some(graph) = g.as_mut() else { return }; + let Some(tf) = graph.title_fences.get_mut(&title_fence) else { return }; + prune_title_fence(title_fence, tf); + let target_waiters: Vec<(usize, u64)> = tf.waits.iter().filter(|&&(v, _, _)| v <= sig_val).map(|&(_, wq, wseq)| (wq, wseq)).collect(); + if target_waiters.is_empty() { + return; + } + // Build edges tagging whether each edge is a Wait64 SyncCell `(Some((va, aw_val)))` or title fence (`None`). + let mut edges: Vec<(usize, u64, usize, u64, Option<(u64, u64)>)> = Vec::new(); + for (&va, cell) in graph.cells.iter_mut() { + if cell.armed_waits.is_empty() { + continue; + } + let completed = prune_completed_waits(cell); + if completed == u64::MAX || cell.armed_waits.is_empty() { + continue; + } + for aw in &cell.armed_waits { + if let Some(s) = cell.submitted_signals.iter().find(|s| s.val >= aw.val) { + edges.push((aw.waiting_queue, aw.wait_seq, s.queue, s.seq, Some((va, aw.val)))); + } + } + } + for (&tf_raw, other_tf) in graph.title_fences.iter_mut() { + if tf_raw == title_fence { + continue; + } + prune_title_fence(tf_raw, other_tf); + for &(val, wq, wseq) in &other_tf.waits { + if let Some(s) = other_tf.signals.iter().find(|s| s.val >= val) { + edges.push((wq, wseq, s.queue, s.seq, None)); + } + } + } + // BFS carrying the first Wait64 SyncCell edge encountered on the path from `sig_q`. + let mut best_limit: HashMap = HashMap::new(); + let mut stack: Vec<(usize, u64, Option<(u64, u64)>)> = vec![(sig_q, u64::MAX, None)]; + best_limit.insert(sig_q, u64::MAX); + let mut break_cells: Vec<(u64, u64)> = Vec::new(); + while let Some((cur_q, limit_seq, first_cell)) = stack.pop() { + for &(wq, wseq, pq, pseq, cell_edge) in &edges { + if wq != cur_q || wseq >= limit_seq { + continue; + } + let tracked = first_cell.or(cell_edge); + if target_waiters.iter().any(|&(twq, twseq)| twq == pq && twseq < pseq) { + if let Some((va, val)) = tracked { + if !break_cells.iter().any(|&(bva, bval)| bva == va && bval >= val) { + break_cells.push((va, val)); + } + } + continue; + } + let prev = best_limit.get(&pq).copied().unwrap_or(0); + if pseq > prev { + best_limit.insert(pq, pseq); + stack.push((pq, pseq, tracked)); + } + } + } + let mut out = Vec::new(); + for (va, val) in break_cells { + if let Some(cell) = graph.cells.get_mut(&va) { + cell.cpu_signaled_max = cell.cpu_signaled_max.max(val); + let before = cell.armed_waits.len(); + cell.armed_waits.retain(|aw| aw.val > val); + let removed = before - cell.armed_waits.len(); + if removed > 0 { + ARMED_GPU_WAITS.fetch_sub(removed, Ordering::AcqRel); + } + cell.submitted_signals.retain(|s| s.val > val); + if let Some(ref f) = cell.fence { + out.push((va, val, f.clone())); + } + } + } + out + }; + for (va, val, fence) in to_release { + let _ = fence.Signal(val); + static MIXED_WARN: AtomicU64 = AtomicU64::new(0); + if once(&MIXED_WARN, 16) { + crate::xlog_warn!( + "D3D12.X: Wait64 fence {va:#x} >= {val:#x} released on CPU before title queue q{} Signal({title_fence:#x}, {sig_val:#x}) to break mixed GPU cycle", + queue_id(sig_q) + ); + } + } +} + +fn wake_sync_watchdog() { + let pair = SYNC_WATCHDOG_WAKE.get_or_init(|| { + let pair = (Mutex::new(()), Condvar::new()); + let _ = std::thread::Builder::new().name("xcl-sync-watchdog".into()).spawn(|| loop { + let (lock, cv) = SYNC_WATCHDOG_WAKE.get().unwrap(); + let guard = lock.lock().unwrap(); + if ARMED_GPU_WAITS.load(Ordering::Acquire) == 0 { + let _g = cv.wait(guard).unwrap(); + continue; + } + let _ = cv.wait_timeout(guard, Duration::from_millis(50)).unwrap(); + let (expired, rewinds) = { + let mut g = SYNC_GRAPH.lock().unwrap(); + let mut out: Vec<(u64, u64, ID3D12Fence, usize, i32, Option, Option, u64, u64, u64)> = Vec::new(); + let mut rew: Vec<(ID3D12Fence, u64)> = Vec::new(); + if let Some(graph) = g.as_mut() { + for (&va, cell) in graph.cells.iter_mut() { + if cell.armed_waits.is_empty() && cell.cpu_signaled_max == 0 { + continue; + } + let completed = unsafe { prune_completed_waits(cell) }; + if completed == u64::MAX { + continue; + } + // Guard against vkd3d-proton rewinding `fence->virtual_value` when an older + // in-flight GPU signal retires after a CPU cycle-break/watchdog signal. + if cell.cpu_signaled_max > completed { + if let Some(ref f) = cell.fence { + rew.push((f.clone(), cell.cpu_signaled_max)); + } + } + if cell.armed_waits.is_empty() { + continue; + } + let mut max_exp = 0u64; + let mut waiter_q = 0usize; + let mut waiter_ty = -1i32; + let before = cell.armed_waits.len(); + cell.armed_waits.retain(|aw| { + if aw.armed_at.elapsed() >= GPU_WAIT_WATCHDOG_TIMEOUT { + if aw.val >= max_exp { + max_exp = aw.val; + waiter_q = aw.waiting_queue; + waiter_ty = aw.waiting_queue_ty; + } + return false; + } + true + }); + let removed = before - cell.armed_waits.len(); + if removed > 0 { + ARMED_GPU_WAITS.fetch_sub(removed, Ordering::AcqRel); + } + if max_exp > 0 { + cell.cpu_signaled_max = cell.cpu_signaled_max.max(max_exp); + cell.submitted_signals.retain(|s| s.val > max_exp); + if let Some(ref f) = cell.fence { + out.push(( + va, + max_exp, + f.clone(), + waiter_q, + waiter_ty, + cell.submitted_queue.or(cell.recorded_last_queue), + cell.recorded_list_type.map(|t| t.0), + cell.recorded_max, + cell.submitted_max, + completed, + )); + } + } + } + } + (out, rew) + }; + for (fence, val) in rewinds { + unsafe { + let _ = fence.Signal(val); + } + } + let had_expired = !expired.is_empty(); + for (va, val, fence, waiter_q, waiter_ty, prod_q, prod_ty, rec, sub, done) in expired { + unsafe { + let _ = fence.Signal(val); + } + let wq = queue_id(waiter_q); + let pq = prod_q.map(queue_id); + crate::xlog_warn!( + "D3D12.X: GPU queue.Wait at {va:#x} >= {val:#x} did not complete within {} ms (waiter=q{wq}/ty{waiter_ty}, prod=q{pq:?}/ty{prod_ty:?}, recorded={rec:#x}, submitted={sub:#x}, completed={done:#x}) – released on CPU to prevent GPU hang", + GPU_WAIT_WATCHDOG_TIMEOUT.as_millis() + ); + } + if had_expired { + crate::xlog_warn!("D3D12.X: pending title ID3D12Fences during GPU wait timeout: {}", super::fence_x::pending_summary()); + } + }); + pair + }); + pair.1.notify_one(); +} + +unsafe fn queue_device_and_type(queue: *mut c_void) -> Option<(ID3D12Device, usize, D3D12_COMMAND_LIST_TYPE)> { + if queue.is_null() { + return None; + } + let q = ID3D12CommandQueue::from_raw_borrowed(&queue)?; + let ty = q.GetDesc().Type; + let mut dev: Option = None; + q.GetDevice(&mut dev).ok()?; + let dev = dev?; + let raw = dev.as_raw() as usize; + Some((dev, raw, ty)) +} + +unsafe fn ensure_cell_fence(va: u64, dev: &ID3D12Device, dev_raw: usize) -> Option { + { + let g = SYNC_GRAPH.lock().unwrap(); + if let Some(cell) = g.as_ref().and_then(|gr| gr.cells.get(&va)) { + if cell.non_monotonic { + return None; + } + if let Some(ref f) = cell.fence { + return (cell.device == dev_raw).then(|| f.clone()); + } + } + } + let created: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; + let mut g = SYNC_GRAPH.lock().unwrap(); + let cell = g.get_or_insert_with(SyncGraph::default).cells.entry(va).or_default(); + if cell.non_monotonic { + return None; + } + if let Some(ref existing) = cell.fence { + return (cell.device == dev_raw).then(|| existing.clone()); + } + cell.fence = Some(created.clone()); + cell.device = dev_raw; + Some(created) +} + +fn note_write64_recorded(list: *mut c_void, va: u64, value: u64) { + if value == 0 || !va.is_multiple_of(8) { + return; + } + let (lty, last_q) = { + let mut g = LISTS.lock().unwrap(); + let s = g.get_or_insert_with(HashMap::new).entry(list as usize).or_default(); + s.push_write64_signal(va, value); + (s.list_type, s.last_queue) + }; + let rescue: Option<(ID3D12Fence, u64, u64)> = { + let mut g = SYNC_GRAPH.lock().unwrap(); + let cell = g.get_or_insert_with(SyncGraph::default).cells.entry(va).or_default(); + if cell.non_monotonic { + return; + } + // Strictly decreasing write (`value < submitted_max`) marks this address non-monotonic. + // Duplicate same-value writes from parallel command-list recording threads remain monotonic. + if value < cell.submitted_max { + let max_armed = cell.armed_waits.iter().map(|aw| aw.val).max().unwrap_or(0); + let removed = cell.armed_waits.len(); + if removed > 0 { + cell.armed_waits.clear(); + ARMED_GPU_WAITS.fetch_sub(removed, Ordering::AcqRel); + } + cell.submitted_signals.clear(); + cell.non_monotonic = true; + let prev_sub = cell.submitted_max; + let old_fence = cell.fence.take(); + old_fence.filter(|_| max_armed > 0).map(|f| (f, max_armed, prev_sub)) + } else { + if value > cell.recorded_max { + cell.recorded_max = value; + if lty.is_some() { + cell.recorded_list_type = lty; + } + if last_q.is_some() { + cell.recorded_last_queue = last_q; + } + } + None + } + }; + // Rescue any armed GPU waits BEFORE dropping the fence so no vkd3d_queue thread can be orphaned. + if let Some((old_fence, max_armed, prev_sub)) = rescue { + unsafe { + let _ = old_fence.Signal(max_armed); + } + static NON_MONO_WARN: AtomicU64 = AtomicU64::new(0); + if once(&NON_MONO_WARN, 16) { + crate::xlog_warn!( + "D3D12.X: Write64 at {va:#x} became non-monotonic ({value:#x} < submitted {prev_sub:#x}) – released armed GPU waits up to {max_armed:#x} on CPU" + ); + } + } +} + +unsafe fn signal_write64_pairs(queue: *mut c_void, pairs: &[(u64, u64)]) { + if queue.is_null() || pairs.is_empty() { + return; + } + let Some((dev, dev_raw, q_ty)) = queue_device_and_type(queue) else { return }; + let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return }; + let sig_q = queue as usize; + // Coalesce per-VA max value within this batch. + let mut max_by_va: Vec<(u64, u64)> = Vec::with_capacity(pairs.len()); + for &(va, val) in pairs { + if val == 0 { + continue; + } + if let Some(entry) = max_by_va.iter_mut().find(|e| e.0 == va) { + entry.1 = entry.1.max(val); + } else { + max_by_va.push((va, val)); + } + } + for (va, val) in max_by_va { + let skip = { + let g = SYNC_GRAPH.lock().unwrap(); + g.as_ref() + .and_then(|gr| gr.cells.get(&va)) + .is_some_and(|c| c.non_monotonic || c.submitted_max >= val) + }; + if skip { + continue; + } + let Some(fence) = ensure_cell_fence(va, &dev, dev_raw) else { continue }; + enum SignalAction { + Skip, + GpuSignal, + CpuCycleBreak(Vec<(usize, bool)>), + } + let action = { + let mut g = SYNC_GRAPH.lock().unwrap(); + let graph = g.get_or_insert_with(SyncGraph::default); + let eligible = match graph.cells.get_mut(&va) { + Some(cell) => { + let completed = prune_completed_waits(cell); + if cell.non_monotonic || cell.device != dev_raw || val <= cell.submitted_max { + None + } else { + Some(completed) + } + } + None => None, + }; + match eligible { + None => SignalAction::Skip, + Some(completed) => { + if would_signal_close_cycle(graph, sig_q, va, val) { + let cell = graph.cells.get_mut(&va).unwrap(); + let waiters: Vec<(usize, bool)> = + cell.armed_waits.iter().filter(|aw| aw.val <= val).map(|aw| (aw.waiting_queue, aw.after_write64)).collect(); + cell.submitted_max = val; + cell.submitted_queue = None; + cell.cpu_signaled_max = cell.cpu_signaled_max.max(val); + if val > cell.recorded_max { + cell.recorded_max = val; + } + let before = cell.armed_waits.len(); + cell.armed_waits.retain(|aw| aw.val > val); + let removed = before - cell.armed_waits.len(); + if removed > 0 { + ARMED_GPU_WAITS.fetch_sub(removed, Ordering::AcqRel); + } + cell.submitted_signals.retain(|s| s.val > val); + SignalAction::CpuCycleBreak(waiters) + } else { + let sig_seq = graph.next_seq(sig_q); + let cell = graph.cells.get_mut(&va).unwrap(); + cell.submitted_max = val; + cell.submitted_queue = Some(sig_q); + if val > cell.recorded_max { + cell.recorded_max = val; + } + if completed < val && cell.cpu_signaled_max < val { + cell.submitted_signals.push(SubmittedSignal { val, queue: sig_q, seq: sig_seq }); + SignalAction::GpuSignal + } else { + SignalAction::Skip + } + } + } + } + }; + match action { + SignalAction::Skip => {} + SignalAction::GpuSignal => { + if let Err(e) = q.Signal(&fence, val) { + crate::xlog_warn!("D3D12.X: Write64 fence Signal({va:#x}, {val:#x}) failed ({e}) – signalling on CPU"); + let _ = fence.Signal(val); + } + } + SignalAction::CpuCycleBreak(waiters) => { + let _ = fence.Signal(val); + static BREAK_WARN: AtomicU64 = AtomicU64::new(0); + if once(&BREAK_WARN, 32) { + let sq = queue_id(sig_q); + let mut wids: Vec = waiters + .into_iter() + .map(|(w, aw)| if aw { format!("q{}(after_w64)", queue_id(w)) } else { format!("q{}", queue_id(w)) }) + .collect(); + wids.sort(); + wids.dedup(); + crate::xlog_warn!( + "D3D12.X: Write64 Signal at {va:#x} = {val:#x} on q{sq}/ty{} would close a GPU cycle (waiters=[{}]) – signalled on CPU", + q_ty.0, + wids.join(",") + ); + } + } + } + } +} + +/// After `queue.ExecuteCommandLists(lists)`: signal per-address GPU fences for any +/// `Write64BitValue{Bottom,Top}OfPipeX` commands recorded on `lists`. +pub(super) unsafe fn signal_write64_fences(queue: *mut c_void, lists: &[*mut c_void]) { + if WRITE64_SIGNAL_LISTS.load(Ordering::Acquire) == 0 || queue.is_null() || lists.is_empty() { + return; + } + let pairs: Vec<(u64, u64)> = { + let g = LISTS.lock().unwrap(); + let Some(m) = g.as_ref() else { return }; + let mut out = Vec::new(); + for &l in lists { + if let Some(s) = m.get(&(l as usize)) { + out.extend_from_slice(&s.write64_signals); + } + } + out + }; + signal_write64_pairs(queue, &pairs); +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum GpuWaitOutcome { + /// Satisfied on GPU (via `queue.Wait` or same-queue FIFO order) — no CPU wait needed. + Handled, + /// Skipping this wait avoids a same-batch self-deadlock. + CycleSkip, + /// Not eligible for GPU fence bridging — fall back to bounded CPU poll. + FallbackCpu, +} + +/// Attempt to satisfy a `Wait64BitValueX(GREATER_EQUAL, u64::MAX)` on the GPU via +/// `queue.Wait(&fence, w.value)` (or same-queue FIFO ordering) instead of blocking the +/// submission thread on the CPU. +/// +/// Cycle breaking is performed with 100% precision at `Signal` time (`signal_write64_pairs` / +/// `break_cycles_before_title_signal`) rather than guessing producer queues from previous frames, +/// so rotating multi-queue schedules neither skip valid barriers nor form Vulkan timeline cycles. +unsafe fn try_gpu_wait(queue: *mut c_void, w: &PendingWait, list_writes: &[(u64, u64)]) -> GpuWaitOutcome { + if queue.is_null() + || w.width != 8 + || w.comparison != D3D12_COMPARISON_FUNC_GREATER_EQUAL.0 as u32 + || w.mask != u64::MAX + || w.value == 0 + { + return GpuWaitOutcome::FallbackCpu; + } + let Some((dev, dev_raw, q_ty)) = queue_device_and_type(queue) else { return GpuWaitOutcome::FallbackCpu }; + let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return GpuWaitOutcome::FallbackCpu }; + let q_raw = queue as usize; + + // Fast path: check eligibility, CPU-released bypass, and same-queue FIFO before allocating a fence. + let pre = { + let g = SYNC_GRAPH.lock().unwrap(); + g.as_ref().and_then(|gr| gr.cells.get(&w.va)).map(|c| { + (c.non_monotonic, c.recorded_max, c.submitted_max, c.submitted_queue, c.cpu_signaled_max) + }) + }; + let Some((non_mono, rec_max, sub_max, sub_q, cpu_sig_max)) = pre else { + return GpuWaitOutcome::FallbackCpu; + }; + if non_mono || rec_max < w.value { + return GpuWaitOutcome::FallbackCpu; + } + // Already released on CPU (cycle break or watchdog): never re-arm a GPU wait that could + // observe a vkd3d-proton fence rewind. + if cpu_sig_max >= w.value { + return GpuWaitOutcome::Handled; + } + // Producer already submitted earlier on THIS EXACT queue: D3D12 FIFO executes it strictly + // before this list without needing a CPU wait or redundant queue.Wait. + if sub_max >= w.value && sub_q == Some(q_raw) { + return GpuWaitOutcome::Handled; + } + // Same-batch self-wait: this very submission writes `(w.va, >= w.value)`, so hoisting a GPU + // Wait ahead of it on the same queue would immediately self-deadlock. + if sub_max < w.value && list_writes.iter().any(|&(wva, wv)| wva == w.va && wv >= w.value) { + static SELF_WARN: AtomicU64 = AtomicU64::new(0); + if once(&SELF_WARN, 8) { + crate::xlog_warn!( + "D3D12.X: Wait64BitValueX at {:#x} >= {:#x} skipped to avoid same-batch self-deadlock (q{}/ty{})", + w.va, + w.value, + queue_id(q_raw), + q_ty.0 + ); + } + return GpuWaitOutcome::CycleSkip; + } + + let Some(fence) = ensure_cell_fence(w.va, &dev, dev_raw) else { return GpuWaitOutcome::FallbackCpu }; + + let (unsubmitted, final_rec_ty, final_prod_q, wait_seq) = { + let mut g = SYNC_GRAPH.lock().unwrap(); + let Some(graph) = g.as_mut() else { return GpuWaitOutcome::FallbackCpu }; + let pre_ok = match graph.cells.get_mut(&w.va) { + Some(cell) => { + if cell.non_monotonic || cell.device != dev_raw || cell.recorded_max < w.value { + return GpuWaitOutcome::FallbackCpu; + } + if cell.cpu_signaled_max >= w.value { + return GpuWaitOutcome::Handled; + } + let completed = prune_completed_waits(cell); + if completed >= w.value { + // Fence already reached `w.value`: trust it if CPU memory agrees (not reset). + return if w.is_satisfied() { GpuWaitOutcome::Handled } else { GpuWaitOutcome::FallbackCpu }; + } + if cell.submitted_max >= w.value && cell.submitted_queue == Some(q_raw) { + return GpuWaitOutcome::Handled; + } + (cell.submitted_max < w.value, cell.recorded_list_type, cell.submitted_queue.or(cell.recorded_last_queue)) + } + None => return GpuWaitOutcome::FallbackCpu, + }; + let wait_seq = graph.next_seq(q_raw); + let cell = graph.cells.get_mut(&w.va).unwrap(); + cell.armed_waits.push(ArmedGpuWait { + val: w.value, + waiting_queue: q_raw, + waiting_queue_ty: q_ty.0, + wait_seq, + armed_at: Instant::now(), + after_write64: w.after_write64, + }); + ARMED_GPU_WAITS.fetch_add(1, Ordering::AcqRel); + (pre_ok.0, pre_ok.1, pre_ok.2, wait_seq) + }; + + if let Err(e) = q.Wait(&fence, w.value) { + let mut g = SYNC_GRAPH.lock().unwrap(); + if let Some(cell) = g.as_mut().and_then(|gr| gr.cells.get_mut(&w.va)) { + if let Some(pos) = cell.armed_waits.iter().rposition(|aw| aw.val == w.value && aw.waiting_queue == q_raw && aw.wait_seq == wait_seq) { + cell.armed_waits.remove(pos); + ARMED_GPU_WAITS.fetch_sub(1, Ordering::AcqRel); + } + } + crate::xlog_warn!("D3D12.X: Wait64 GPU queue.Wait({:#x}, {:#x}) failed ({e}) – falling back to CPU wait", w.va, w.value); + return GpuWaitOutcome::FallbackCpu; + } + + wake_sync_watchdog(); + if unsubmitted { + static LOGGED: AtomicU64 = AtomicU64::new(0); + if once(&LOGGED, 8) { + crate::xlog_info!( + "D3D12.X: Wait64BitValueX at {:#x} >= {:#x} bridged to GPU queue.Wait (waiter=q{}/ty{}, prod=q{:?}/ty{:?}; wait-before-signal, after_write64={})", + w.va, + w.value, + queue_id(q_raw), + q_ty.0, + final_prod_q.map(queue_id), + final_rec_ty.map(|t| t.0), + w.after_write64 + ); + } + } + GpuWaitOutcome::Handled +} + +unsafe fn wait_all_on(queue: *mut c_void, waits: &[PendingWait], list_writes: &[(u64, u64)]) { static TIMEOUTS: AtomicU64 = AtomicU64::new(0); + static RING_DUMPED: AtomicU64 = AtomicU64::new(0); + let timeout = wait_timeout(); + let q_ty = queue_device_and_type(queue).map_or(-1, |(_, _, t)| t.0); for w in waits { - if !w.wait_until_satisfied(WAIT_TIMEOUT) && once(&TIMEOUTS, 40) { + if w.is_satisfied() { + continue; + } + match try_gpu_wait(queue, w, list_writes) { + GpuWaitOutcome::Handled | GpuWaitOutcome::CycleSkip => continue, + GpuWaitOutcome::FallbackCpu => {} + } + if !w.wait_until_satisfied(timeout) && once(&TIMEOUTS, 40) { + let cell_diag = { + let g = SYNC_GRAPH.lock().unwrap(); + g.as_ref().and_then(|gr| gr.cells.get(&w.va)).map(|c| (c.recorded_max, c.submitted_max, c.non_monotonic, c.recorded_list_type.map(|t| t.0))) + }; crate::xlog_warn!( - "D3D12.X: Wait{}BitValueX timed out after {} ms at {:#x} (op {}, want {:#x}, mask {:#x}; memory holds {:x?})", + "D3D12.X: Wait{}BitValueX timed out after {} ms at {:#x} (op {}, want {:#x}, mask {:#x}; memory holds {:x?}; queue_type={}, after_write64={}, sync={cell_diag:x?})", w.width * 8, - WAIT_TIMEOUT.as_millis(), + timeout.as_millis(), w.va, w.comparison, w.value, w.mask, - w.read_value() + w.read_value(), + q_ty, + w.after_write64 ); + if once(&RING_DUMPED, 2) { + let (total, entries) = WRITE_TRACE.lock().unwrap().snapshot(); + let summary: Vec = entries + .iter() + .rev() + .take(16) + .map(|e| format!("{}({:#x}={:#x},f={:#x},ty={})", e.what, e.va, e.value, e.flags, e.list_type)) + .collect(); + crate::xlog_warn!("D3D12.X: recent Write32/64 calls ({total} total): [{}]", summary.join(", ")); + } } } } @@ -930,32 +1903,34 @@ pub(super) unsafe fn cpu_writes_after(queue: *mut c_void, lists: &[*mut c_void]) /// Submit `lists` through `submit`, splitting the batch before any list whose `Wait32/64BitValueX` /// condition is not yet satisfied so earlier lists in the same batch can run on the GPU first. -pub(super) unsafe fn execute_with_waits(lists: &[*mut c_void], mut submit: impl FnMut(&[*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 { submit(lists); return; } - let per_list: Vec> = { + let per_list: Vec<(Vec, Vec<(u64, u64)>)> = { let g = LISTS.lock().unwrap(); lists .iter() .map(|&l| { g.as_ref() .and_then(|m| m.get(&(l as usize))) - .map(|s| s.pending_waits.clone()) + .map(|s| (s.pending_waits.clone(), s.write64_signals.clone())) .unwrap_or_default() }) .collect() }; let mut start = 0usize; - for (i, waits) in per_list.iter().enumerate() { + for (i, (waits, list_writes)) in per_list.iter().enumerate() { if waits.is_empty() || waits.iter().all(|w| w.is_satisfied()) { continue; } if i > start { submit(&lists[start..i]); } - wait_all(waits); + wait_all_on(queue, waits, list_writes); start = i; } if start < lists.len() { @@ -963,6 +1938,11 @@ pub(super) unsafe fn execute_with_waits(lists: &[*mut c_void], mut submit: impl } } +#[cfg(test)] +pub(super) unsafe fn execute_with_waits(lists: &[*mut c_void], submit: impl FnMut(&[*mut c_void])) { + execute_with_waits_on(std::ptr::null_mut(), lists, submit); +} + // --------------------------------------------------------------------------------------- // memory copy / fill / immediate write / timestamp // --------------------------------------------------------------------------------------- @@ -1219,26 +2199,224 @@ unsafe fn timestamp(list: *mut c_void, va: u64, what: &str) { /// /// # Safety /// `this` must be a valid adopted `ID3D12GraphicsCommandList` pointer. -pub unsafe extern "system" fn write32_bottom_x(this: *mut c_void, va: u64, value: u32, _flush: u32, _flags: u32) { +pub unsafe extern "system" fn write32_bottom_x(this: *mut c_void, va: u64, value: u32, _flush: u32, flags: u32) { + record_write_trace(this, va, value as u64, flags, "W32B"); write(this, va, &[value], D3D12_WRITEBUFFERIMMEDIATE_MODE_MARKER_OUT, "Write32BitValueBottomOfPipeX"); } /// command list #70 Write64BitValueBottomOfPipeX(address, value, flush, flags) pub(super) unsafe extern "system" fn write64_bottom_x(this: *mut c_void, va: u64, value: u64, _flush: u32, flags: u32) { const W: &str = "Write64BitValueBottomOfPipeX"; + record_write_trace(this, va, value, flags, "W64B"); if flags & BOTTOM_TIMESTAMPS != 0 { return timestamp(this, va, W); } + note_write64_recorded(this, va, value); write(this, va, &[value as u32, (value >> 32) as u32], D3D12_WRITEBUFFERIMMEDIATE_MODE_MARKER_OUT, W); } +/// 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, +/// carrying all bound D3D12 + XCL root-argument state across the split. +/// +/// At `ExecuteCommandLists`, `title_list::push_segments` expands the wrapper into `[seg_0, seg_1, ...]` +/// and `execute_with_waits_on` submits `seg_0` + emits `queue.Signal` for its `Write64`s BEFORE +/// emitting `queue.Wait` for `seg_1`'s `Wait64`, preserving exact Xbox chronological order with +/// zero artificial GPU cycles. +unsafe fn try_split_for_wait(list: *mut c_void) -> Option<*mut c_void> { + static ENABLED: OnceLock = OnceLock::new(); + if !*ENABLED.get_or_init(|| std::env::var("XCL_SPLIT_MIDLIST_WAIT").map_or(true, |v| v.trim() != "0")) { + return None; + } + let wrapper = super::title_list::wrapper_of(list)?; + if !super::title_list::can_split(wrapper) { + return None; + } + let ty = list_type(list); + if ty == D3D12_COMMAND_LIST_TYPE_BUNDLE { + return None; + } + let (alloc, last_queue, bound_pso, depth_bias, index_buffer, depth_bounds, predication, pred_buf, pred_in_state, active_query, ended_early, written_ranges, bindings) = { + let mut g = LISTS.lock().unwrap(); + let s = g.as_mut()?.get_mut(&(list as usize))?; + if s.allocator == 0 { + return None; + } + let active_query = s.occlusion.end_active_early(); + let ended_early = std::mem::take(&mut s.occlusion.ended_early); + let pred_in_state = std::mem::replace(&mut s.pred_in_state, false); + ( + s.allocator, + s.last_queue, + s.bound_pso, + s.depth_bias, + s.index_buffer, + s.depth_bounds, + s.predication, + s.pred_buf.clone(), + pred_in_state, + active_query, + ended_early, + s.written_ranges.clone(), + s.bindings.clone(), + ) + }; + + if let Some(((h, i), qty)) = active_query { + pc::(list, PC_END_QUERY)(list, h, qty, i); + } + if pred_in_state { + if let Some(ref pb) = pred_buf { + transition(list, pb.as_raw() as usize, D3D12_RESOURCE_STATE_PREDICATION, D3D12_RESOURCE_STATE_COMMON); + } + } + + let ext = *(list as *const usize); + let close_hr = pc:: i32>(list, PC_CLOSE)(list); + real::preserve_vtable(list, ext); + if close_hr < 0 { + static CLOSE_ERR: AtomicU64 = AtomicU64::new(0); + warn(&CLOSE_ERR, "Wait64 mid-list split", format_args!("Close failed ({close_hr:#x})")); + return None; + } + + let init_pso = if ty == D3D12_COMMAND_LIST_TYPE_COPY { + 0 + } else { + super::pso_async::resolve_for_bind(bound_pso) + }; + let dev = device_of(list)?; + let dev_raw = dev.as_raw() as usize; + + 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); + real::preserve_vtable(spare, ext_spare); + if reset_hr >= 0 { + next_pc = Some(spare); + } + } + let next_pc = match next_pc { + Some(p) => p, + None => match real::create_raw_pc_command_list(dev.as_raw(), ty, alloc, init_pso) { + Some(p) => p, + None => { + static CREATE_ERR: AtomicU64 = AtomicU64::new(0); + warn(&CREATE_ERR, "Wait64 mid-list split", format_args!("CreateCommandList failed")); + return None; + } + }, + }; + + let old_next = { + let mut g = LISTS.lock().unwrap(); + let m = g.get_or_insert_with(HashMap::new); + let old = m.remove(&(next_pc as usize)); + if let Some(ref o) = old { + if !o.pending_waits.is_empty() { + PENDING_WAIT_LISTS.fetch_sub(1, Ordering::AcqRel); + } + if !o.sparse_writes.is_empty() { + SPARSE_WRITE_LISTS.fetch_sub(1, Ordering::AcqRel); + } + if !o.write64_signals.is_empty() { + WRITE64_SIGNAL_LISTS.fetch_sub(1, Ordering::AcqRel); + } + } + m.insert( + next_pc as usize, + ListState { + allocator: alloc, + list_type: Some(ty), + last_queue, + bound_pso, + depth_bias, + native_bias: DepthBias::ZERO, + pso_dirty: false, + using_fallback_pso: false, + index_buffer, + depth_bounds, + occlusion: Occlusion { active: None, ended_early }, + written_ranges, + pred_buf: pred_buf.clone(), + pred_in_state: false, + predication, + bindings: bindings.clone(), + ..Default::default() + }, + ); + old + }; + drop(old_next); + super::title_textures::list_reset(next_pc as usize); + super::bind::inherit_for_split(list, next_pc, alloc); + restore_bindings(next_pc, &bindings, ty); + + if ty == D3D12_COMMAND_LIST_TYPE_DIRECT { + let info = if bound_pso != 0 { device_x::base_depth_bias_info(bound_pso) } else { None }; + let mut applied_native = false; + if let Some((true, static_bias)) = info { + let target = depth_bias.unwrap_or(static_bias); + if target.is_zero() { + applied_native = true; + } else if try_native_depth_bias(next_pc, target) { + if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(next_pc as usize))) { + s.native_bias = target; + } + applied_native = true; + } + } else if bound_pso == 0 { + if let Some(b) = depth_bias { + if device_x::dynamic_depth_bias_supported(dev_raw as *mut c_void) && try_native_depth_bias(next_pc, b) { + if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(next_pc as usize))) { + s.native_bias = b; + } + applied_native = true; + } + } + } + if depth_bias.is_some() && !applied_native { + if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(next_pc as usize))) { + s.pso_dirty = true; + } + DEPTH_BIAS_USED.store(true, Ordering::Release); + } + if let Some(ref view) = index_buffer { + set_index_buffer(next_pc, Some(view)); + } + if let Some((min, max)) = depth_bounds { + pc::(next_pc, PC_OM_SET_DEPTH_BOUNDS)(next_pc, min, max); + } + } + if ty != D3D12_COMMAND_LIST_TYPE_COPY { + if let (Some(op), Some(ref pb)) = (predication, pred_buf) { + let pb_raw = pb.as_raw() as usize; + transition(next_pc, pb_raw, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_PREDICATION); + pc::(next_pc, PC_SET_PREDICATION)(next_pc, pb_raw, 0, op); + if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(next_pc as usize))) { + s.pred_in_state = true; + } + } + } + + super::title_list::activate_segment(wrapper, list, next_pc); + static SPLITS: AtomicU64 = AtomicU64::new(0); + let n = SPLITS.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 4 || (n.is_power_of_two() && n <= 256) { + crate::xlog_info!("D3D12.X: split command list (type {}) around mid-list Wait after Write64 (#{n})", ty.0); + } + Some(next_pc) +} + /// Record a `Wait32BitValueX` or `Wait64BitValueX` memory wait on `list`. /// /// If an earlier write in the same open list already targeted an overlapping UMA range, the /// `COMMON -> COPY_DEST -> COMMON` barrier around that write already orders subsequent work /// on the GPU, so we do not stall before submission (which would deadlock waiting on our own -/// unsubmitted list). Otherwise the wait is evaluated on the CPU before `ExecuteCommandLists` -/// (or `KickoffX`) submits the list. +/// unsubmitted list). If this list already recorded a `Write64BitValue*` to a different cell, +/// we split into a new deferred PC segment so earlier `Write64` signals run BEFORE this wait. unsafe fn wait_memory(list: *mut c_void, va: u64, width: u8, comparison: u32, value: u64, mask: u64, what: &str) { static N: AtomicU64 = AtomicU64::new(0); let n = width as u64; @@ -1258,12 +2436,23 @@ unsafe fn wait_memory(list: *mut c_void, va: u64, width: u8, comparison: u32, va if comparison == D3D12_COMPARISON_FUNC_NEVER.0 as u32 { return warn(&N, what, format_args!("NEVER comparison at {va:#x} (skipped to avoid hang)")); } + let need_split = { + let mut g = LISTS.lock().unwrap(); + let s = g.get_or_insert_with(HashMap::new).entry(list as usize).or_default(); + if s.has_prior_write(va, n) { + return; + } + if s.write64_signals.is_empty() { + s.push_wait(PendingWait { va, width, comparison, value, mask, after_write64: false }); + return; + } + true + }; + let target = if need_split { try_split_for_wait(list).unwrap_or(list) } else { list }; let mut g = LISTS.lock().unwrap(); - let s = g.get_or_insert_with(HashMap::new).entry(list as usize).or_default(); - if s.has_prior_write(va, n) { - return; - } - s.push_wait(PendingWait { va, width, comparison, value, mask }); + let s = g.get_or_insert_with(HashMap::new).entry(target as usize).or_default(); + let after_write64 = !s.write64_signals.is_empty(); + s.push_wait(PendingWait { va, width, comparison, value, mask, after_write64 }); } /// command list #71 Wait32BitValueX(address, comparison, value, mask, flags) @@ -1281,21 +2470,25 @@ pub(super) unsafe extern "system" fn wait64_x(this: *mut c_void, va: u64, compar } /// command list #88 Write32BitValueTopOfPipeX(address, value, flags) -pub(super) unsafe extern "system" fn write32_top_x(this: *mut c_void, va: u64, value: u32, _flags: u32) { +pub(super) unsafe extern "system" fn write32_top_x(this: *mut c_void, va: u64, value: u32, flags: u32) { + record_write_trace(this, va, value as u64, flags, "W32T"); write(this, va, &[value], D3D12_WRITEBUFFERIMMEDIATE_MODE_MARKER_IN, "Write32BitValueTopOfPipeX"); } /// command list #89 Write64BitValueTopOfPipeX(address, value, flags) pub(super) unsafe extern "system" fn write64_top_x(this: *mut c_void, va: u64, value: u64, flags: u32) { const W: &str = "Write64BitValueTopOfPipeX"; + record_write_trace(this, va, value, flags, "W64T"); if flags & TOP_TIMESTAMPS != 0 { return timestamp(this, va, W); } + note_write64_recorded(this, va, value); write(this, va, &[value as u32, (value >> 32) as u32], D3D12_WRITEBUFFERIMMEDIATE_MODE_MARKER_IN, W); } /// command list #90 Write32BitValueBottomOfShaderX(address, value, stage) -pub(super) unsafe extern "system" fn write32_bottom_of_shader_x(this: *mut c_void, va: u64, value: u32, _stage: u32) { +pub(super) unsafe extern "system" fn write32_bottom_of_shader_x(this: *mut c_void, va: u64, value: u32, stage: u32) { + record_write_trace(this, va, value as u64, stage, "W32S"); write(this, va, &[value], D3D12_WRITEBUFFERIMMEDIATE_MODE_MARKER_OUT, "Write32BitValueBottomOfShaderX"); } @@ -1532,13 +2725,14 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { std::mem::take(&mut s.pending_waits) }; let sparse_writes = s.clear_sparse_writes(); + let write64_signals = s.clear_write64_signals(); s.written_ranges.clear(); 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, cpu_writes)) + (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)) }; - let (sparse_writes, cpu_writes) = sparse_writes; + let (sparse_writes, write64_signals, cpu_writes) = sparse_writes; // End any active occlusion query before Close (PC forbids closing with an open query). if let Some(((h, i), qty)) = active_query { @@ -1559,14 +2753,34 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { let q_raw = queue as *mut c_void; super::title_textures::refresh(q_raw); + 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`. + let kickoff_split = super::title_list::reclaim_for_kickoff(this); + if let Some((_, ref prior, _)) = kickoff_split { + if !prior.is_empty() { + execute_with_waits_on(q_raw, prior, |chunk| { + exec(q_raw, chunk.len() as u32, chunk.as_ptr()); + signal_write64_fences(q_raw, chunk); + readback_sparse_writes(q_raw, chunk); + cpu_writes_after(q_raw, chunk); + }); + super::title_textures::submitted(prior); + for &p in prior { + super::title_textures::list_reset(p as usize); + } + } + } + if !waits.is_empty() { - wait_all(&waits); + wait_all_on(q_raw, &waits, &write64_signals); } - 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)); let one = [this]; exec(q_raw, 1, one.as_ptr()); + 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); @@ -1577,62 +2791,100 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { } super::cpu_writes::after(q_raw, cpu_writes); - let ext_closed = *(this as *const usize); + let target = if let Some((primary, _, reclaimed)) = kickoff_split { + 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))) { + (std::mem::take(&mut s.occlusion.ended_early), s.pred_buf.clone(), s.bindings.clone()) + } else { + (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); + } + 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 = pc:: i32>(this, PC_RESET)(this, alloc, init_pso); - real::preserve_vtable(this, ext_closed); + let reset_hr = pc:: i32>(target, PC_RESET)(target, 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 bindings = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(this as usize))).map(|s| s.bindings.clone()); + let bindings = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(target as usize))).map(|s| s.bindings.clone()); if let Some(b) = bindings { - restore_bindings(this, &b); + restore_bindings(target, &b, ty); } // Reset() cleared the PC list's native RSSetDepthBias state to (0, 0, 0) and bound init_pso. - if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(this as usize))) { + if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(target as usize))) { s.native_bias = DepthBias::ZERO; s.using_fallback_pso = false; s.pso_dirty = false; } - let info = if bound_pso != 0 { device_x::base_depth_bias_info(bound_pso) } else { None }; - let mut applied_native = false; - if let Some((true, static_bias)) = info { - let target = depth_bias.unwrap_or(static_bias); - if target.is_zero() { - applied_native = true; - } else if try_native_depth_bias(this, target) { - if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(this as usize))) { - s.native_bias = target; - } - applied_native = true; - } - } else if bound_pso == 0 { - if let Some(b) = depth_bias { - if device_x::dynamic_depth_bias_supported(dev_raw as *mut c_void) && try_native_depth_bias(this, b) { - if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(this as usize))) { - s.native_bias = b; + if ty == D3D12_COMMAND_LIST_TYPE_DIRECT { + let info = if bound_pso != 0 { device_x::base_depth_bias_info(bound_pso) } else { None }; + let mut applied_native = false; + if let Some((true, static_bias)) = info { + let target_bias = depth_bias.unwrap_or(static_bias); + if target_bias.is_zero() { + applied_native = true; + } else if try_native_depth_bias(target, target_bias) { + if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(target as usize))) { + s.native_bias = target_bias; } applied_native = true; } + } else if bound_pso == 0 { + if let Some(b) = depth_bias { + if device_x::dynamic_depth_bias_supported(dev_raw as *mut c_void) && try_native_depth_bias(target, b) { + if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(target as usize))) { + s.native_bias = b; + } + applied_native = true; + } + } } - } - if depth_bias.is_some() && !applied_native { - if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(this as usize))) { - s.pso_dirty = true; + if depth_bias.is_some() && !applied_native { + if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(target as usize))) { + s.pso_dirty = true; + } + DEPTH_BIAS_USED.store(true, Ordering::Release); + } + if let Some(ref view) = index_buffer { + set_index_buffer(target, Some(view)); + } + if let Some((min, max)) = depth_bounds { + pc::(target, PC_OM_SET_DEPTH_BOUNDS)(target, min, max); } - DEPTH_BIAS_USED.store(true, Ordering::Release); - } - if let Some(ref view) = index_buffer { - set_index_buffer(this, Some(view)); - } - if let Some((min, max)) = depth_bounds { - pc::(this, PC_OM_SET_DEPTH_BOUNDS)(this, min, max); } if let (Some(op), Some(pb)) = (predication, pred_buf) { - transition(this, pb, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_PREDICATION); - pc::(this, PC_SET_PREDICATION)(this, pb, 0, op); - if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(this as usize))) { + 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; } } @@ -2135,6 +3387,7 @@ pub unsafe extern "system" fn reset_x(this: *mut c_void, alloc: usize, pso: usiz s.occlusion = Occlusion::default(); s.written_ranges.clear(); s.clear_sparse_writes(); + s.clear_write64_signals(); s.clear_waits(); s.cpu_writes.clear(); s.predication = None; @@ -2712,6 +3965,7 @@ mod tests { comparison: D3D12_COMPARISON_FUNC_EQUAL.0 as u32, value: 0x0000_005A, mask: 0x0000_00FF, + after_write64: false, }; unsafe { assert!(!w32.is_satisfied()); @@ -2731,6 +3985,7 @@ mod tests { comparison: D3D12_COMPARISON_FUNC_GREATER_EQUAL.0 as u32, value: 0x0000_0002_0000_0000, mask: u64::MAX, + after_write64: false, }; unsafe { assert!(!w64.is_satisfied()); @@ -2775,6 +4030,7 @@ mod tests { comparison: D3D12_COMPARISON_FUNC_EQUAL.0 as u32, value: 42, mask: u32::MAX as u64, + after_write64: false, }); } @@ -3343,7 +4599,7 @@ mod tests { let restore = || { let b = LISTS.lock().unwrap().as_ref().unwrap().get(&(list_ptr as usize)).unwrap().bindings.clone(); - unsafe { restore_bindings(list_ptr, &b) }; + unsafe { restore_bindings(list_ptr, &b, D3D12_COMMAND_LIST_TYPE_DIRECT) }; }; unsafe { @@ -3714,4 +4970,844 @@ mod tests { on_release(list_ptr as usize); } } + + #[test] + fn write_buffer_immediate_on_open_existing_heap_visible_to_cpu() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE}; + + const MEM_WRITE_WATCH: u32 = 0x20_0000; + + unsafe { + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + let Ok(factory) = CreateDXGIFactory1::() else { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + }; + let Ok(warp) = factory.EnumWarpAdapter::() else { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + }; + if D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + } + let dev = dev.unwrap(); + let dev3: ID3D12Device3 = dev.cast().unwrap(); + + let mem = VirtualAlloc(std::ptr::null(), 0x1_0000, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE); + assert!(!mem.is_null()); + let base = mem as usize; + + let heap: ID3D12Heap = dev3.OpenExistingHeapFromAddress(mem).expect("OpenExistingHeapFromAddress"); + let buf_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 0x1_0000, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER, + ..Default::default() + }; + let mut buf: Option = None; + dev.CreatePlacedResource(&heap, 0, &buf_desc, D3D12_RESOURCE_STATE_COMMON, None, &mut buf).unwrap(); + let buf = buf.unwrap(); + let gpu_va = buf.GetGPUVirtualAddress(); + + // Upload buffer holding known u64 for CopyBufferRegion comparison + let up_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 256, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut up: Option = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &up_desc, + D3D12_RESOURCE_STATE_GENERIC_READ, + None, + &mut up, + ) + .unwrap(); + let up = up.unwrap(); + let mut up_ptr = std::ptr::null_mut(); + up.Map(0, None, Some(&mut up_ptr)).unwrap(); + *(up_ptr as *mut u64) = 0xCAFE_BABE_DEAD_BEEFu64; + up.Unmap(0, None); + + // Readback buffer to inspect what the GPU itself sees at +0x100, +0x180, +0x200 + let mut rb: Option = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &up_desc, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut rb, + ) + .unwrap(); + let rb = rb.unwrap(); + + // 1. DIRECT queue: WriteBufferImmediate at +0x100 and CopyBufferRegion at +0x200 + let dq: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); + let da: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let dl: ID3D12GraphicsCommandList2 = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &da, None).unwrap(); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + + let make_barrier = |before, after| D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: ManuallyDrop::new(Some(buf.clone())), + Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: before, + StateAfter: after, + }), + }, + }; + + dl.ResourceBarrier(&[make_barrier(D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST)]); + let p_direct = [ + D3D12_WRITEBUFFERIMMEDIATE_PARAMETER { Dest: gpu_va + 0x100, Value: 0x0000_0677 }, + D3D12_WRITEBUFFERIMMEDIATE_PARAMETER { Dest: gpu_va + 0x104, Value: 0x0000_0000 }, + ]; + let m_direct = [D3D12_WRITEBUFFERIMMEDIATE_MODE_MARKER_OUT; 2]; + dl.WriteBufferImmediate(2, p_direct.as_ptr(), Some(m_direct.as_ptr())); + dl.CopyBufferRegion(&buf, 0x200, &up, 0, 8); + dl.ResourceBarrier(&[make_barrier(D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COMMON)]); + dl.Close().unwrap(); + let dcl: ID3D12CommandList = dl.cast().unwrap(); + dq.ExecuteCommandLists(&[Some(dcl)]); + dq.Signal(&fence, 1).unwrap(); + crate::gpu::fence::wait(&fence, 1, &dev, None, 2000).unwrap(); + + // 2. COMPUTE queue: WriteBufferImmediate at +0x180 + let cq: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_COMPUTE, ..Default::default() }).unwrap(); + let ca: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE).unwrap(); + let cl2: ID3D12GraphicsCommandList2 = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COMPUTE, &ca, None).unwrap(); + cl2.ResourceBarrier(&[make_barrier(D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST)]); + let p_comp = [ + D3D12_WRITEBUFFERIMMEDIATE_PARAMETER { Dest: gpu_va + 0x180, Value: 0x0000_0677 }, + D3D12_WRITEBUFFERIMMEDIATE_PARAMETER { Dest: gpu_va + 0x184, Value: 0x1122_3344 }, + ]; + let m_comp = [D3D12_WRITEBUFFERIMMEDIATE_MODE_MARKER_OUT; 2]; + cl2.WriteBufferImmediate(2, p_comp.as_ptr(), Some(m_comp.as_ptr())); + cl2.ResourceBarrier(&[make_barrier(D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COMMON)]); + cl2.Close().unwrap(); + let ccl: ID3D12CommandList = cl2.cast().unwrap(); + cq.ExecuteCommandLists(&[Some(ccl)]); + cq.Signal(&fence, 2).unwrap(); + crate::gpu::fence::wait(&fence, 2, &dev, None, 2000).unwrap(); + + // 3. GPU readback of +0x100, +0x180, +0x200 + let da2: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let dl2: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &da2, None).unwrap(); + dl2.CopyBufferRegion(&rb, 0, &buf, 0x100, 8); + dl2.CopyBufferRegion(&rb, 8, &buf, 0x180, 8); + dl2.CopyBufferRegion(&rb, 16, &buf, 0x200, 8); + dl2.Close().unwrap(); + let dcl2: ID3D12CommandList = dl2.cast().unwrap(); + dq.ExecuteCommandLists(&[Some(dcl2)]); + dq.Signal(&fence, 3).unwrap(); + crate::gpu::fence::wait(&fence, 3, &dev, None, 2000).unwrap(); + + let cpu_direct = *((base + 0x100) as *const u64); + let cpu_comp = *((base + 0x180) as *const u64); + let cpu_copy = *((base + 0x200) as *const u64); + let mut rb_ptr = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut rb_ptr)).unwrap(); + let gpu_direct = *(rb_ptr as *const u64); + let gpu_comp = *((rb_ptr as *const u64).add(1)); + let gpu_copy = *((rb_ptr as *const u64).add(2)); + rb.Unmap(0, None); + + drop(dl); + drop(dl2); + drop(cl2); + drop(buf); + drop(heap); + VirtualFree(mem, 0, MEM_RELEASE); + + assert_eq!(cpu_direct, 0x677, "DIRECT WriteBufferImmediate must be visible to CPU (gpu={gpu_direct:#x})"); + assert_eq!(cpu_comp, 0x1122_3344_0000_0677, "COMPUTE WriteBufferImmediate must be visible to CPU (gpu={gpu_comp:#x})"); + assert_eq!(cpu_copy, 0xCAFE_BABE_DEAD_BEEF, "DIRECT CopyBufferRegion must be visible to CPU (gpu={gpu_copy:#x})"); + } + } + + /// Submitting a DIRECT list with `Wait64BitValueX(va, >=, 0x677)` BEFORE submitting the + /// COMPUTE list that recorded `Write64BitValueBottomOfPipeX(va, 0x677)` must bridge via + /// GPU `queue.Wait`/`queue.Signal` without blocking the submitter thread for `WAIT_TIMEOUT`. + #[test] + fn cross_queue_wait64_before_signal_does_not_deadlock_submit_thread() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + + unsafe { + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + let Ok(factory) = CreateDXGIFactory1::() else { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + }; + let Ok(warp) = factory.EnumWarpAdapter::() else { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + }; + if D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + } + let dev = dev.unwrap(); + let dq: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); + let cq: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_COMPUTE, ..Default::default() }).unwrap(); + let da: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let ca: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE).unwrap(); + let dl: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &da, None).unwrap(); + let cl: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COMPUTE, &ca, None).unwrap(); + let done_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + + let cell = Box::new(AtomicU64::new(0)); + let va = &*cell as *const AtomicU64 as u64; + + let dl_ptr = dl.as_raw(); + let cl_ptr = cl.as_raw(); + on_create(dl_ptr, da.as_raw() as usize, 0, D3D12_COMMAND_LIST_TYPE_DIRECT); + on_create(cl_ptr, ca.as_raw() as usize, 0, D3D12_COMMAND_LIST_TYPE_COMPUTE); + + // Worker threads record both lists: COMPUTE writes `va = 0x677`, DIRECT waits `va >= 0x677`. + note_write64_recorded(cl_ptr, va, 0x677); + wait64_x(dl_ptr, va, D3D12_COMPARISON_FUNC_GREATER_EQUAL.0 as u32, 0x677, 1, 0); + dl.Close().unwrap(); + cl.Close().unwrap(); + + // Single submitter thread submits DIRECT (consumer) FIRST — before COMPUTE (producer)! + let t0 = Instant::now(); + let dcl: ID3D12CommandList = dl.cast().unwrap(); + execute_with_waits_on(dq.as_raw(), &[dl_ptr], |chunk| { + assert_eq!(chunk, &[dl_ptr]); + dq.ExecuteCommandLists(&[Some(dcl.clone())]); + signal_write64_fences(dq.as_raw(), chunk); + }); + let direct_submit_ms = t0.elapsed().as_millis(); + assert!( + direct_submit_ms < 500, + "wait-before-signal must bridge to GPU queue.Wait without blocking CPU (took {direct_submit_ms} ms)" + ); + dq.Signal(&done_fence, 1).unwrap(); + + // Now submit COMPUTE (producer) which signals the per-VA GPU fence. + let ccl: ID3D12CommandList = cl.cast().unwrap(); + execute_with_waits_on(cq.as_raw(), &[cl_ptr], |chunk| { + assert_eq!(chunk, &[cl_ptr]); + cq.ExecuteCommandLists(&[Some(ccl.clone())]); + signal_write64_fences(cq.as_raw(), chunk); + }); + + // DIRECT queue must now unblock and finish promptly on the GPU. + crate::gpu::fence::wait(&done_fence, 1, &dev, None, 2000).expect("DIRECT queue must complete after COMPUTE signals per-VA fence"); + + on_release(dl_ptr as usize); + on_release(cl_ptr as usize); + SYNC_GRAPH.lock().unwrap().as_mut().map(|gr| gr.cells.remove(&va)); + } + } + + /// Cross-queue cycle detection (`DIRECT` waits on `COMPUTE` while `COMPUTE` is already + /// blocked on an unsubmitted write from `DIRECT`) and same-queue FIFO bypass must both + /// complete immediately without stalling CPU or hanging GPU. + #[test] + fn cross_queue_cycle_and_same_queue_fifo_do_not_deadlock() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + + unsafe { + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + let Ok(factory) = CreateDXGIFactory1::() else { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + }; + let Ok(warp) = factory.EnumWarpAdapter::() else { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + }; + if D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + } + let dev = dev.unwrap(); + let dq: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); + let cq: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_COMPUTE, ..Default::default() }).unwrap(); + let da: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let ca1: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE).unwrap(); + let ca2: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE).unwrap(); + let dl: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &da, None).unwrap(); + let cl1: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COMPUTE, &ca1, None).unwrap(); + let cl2: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COMPUTE, &ca2, None).unwrap(); + let done_d: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let done_c: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + + let cell_a = Box::new(AtomicU64::new(0)); + let cell_b = Box::new(AtomicU64::new(0)); + let va_a = &*cell_a as *const AtomicU64 as u64; + let va_b = &*cell_b as *const AtomicU64 as u64; + + let (dl_ptr, cl1_ptr, cl2_ptr) = (dl.as_raw(), cl1.as_raw(), cl2.as_raw()); + on_create(dl_ptr, da.as_raw() as usize, 0, D3D12_COMMAND_LIST_TYPE_DIRECT); + on_create(cl1_ptr, ca1.as_raw() as usize, 0, D3D12_COMMAND_LIST_TYPE_COMPUTE); + on_create(cl2_ptr, ca2.as_raw() as usize, 0, D3D12_COMMAND_LIST_TYPE_COMPUTE); + + // Fork-join cycle: DIRECT writes A then waits on B; COMPUTE1 waits on A then writes B; + // COMPUTE2 waits on B (same-queue FIFO after COMPUTE1) after writing something else. + note_write64_recorded(dl_ptr, va_a, 0x702); + wait64_x(dl_ptr, va_b, D3D12_COMPARISON_FUNC_GREATER_EQUAL.0 as u32, 0x702, 1, 0); + wait64_x(cl1_ptr, va_a, D3D12_COMPARISON_FUNC_GREATER_EQUAL.0 as u32, 0x702, 1, 0); + note_write64_recorded(cl1_ptr, va_b, 0x702); + wait64_x(cl2_ptr, va_b, D3D12_COMPARISON_FUNC_GREATER_EQUAL.0 as u32, 0x702, 1, 0); + dl.Close().unwrap(); + cl1.Close().unwrap(); + cl2.Close().unwrap(); + + let t0 = Instant::now(); + let ccl1: ID3D12CommandList = cl1.cast().unwrap(); + execute_with_waits_on(cq.as_raw(), &[cl1_ptr], |chunk| { + cq.ExecuteCommandLists(&[Some(ccl1.clone())]); + signal_write64_fences(cq.as_raw(), chunk); + }); + // Same-queue FIFO bypass: cl2 waits on va_b already submitted on cq. + let ccl2: ID3D12CommandList = cl2.cast().unwrap(); + execute_with_waits_on(cq.as_raw(), &[cl2_ptr], |chunk| { + cq.ExecuteCommandLists(&[Some(ccl2.clone())]); + signal_write64_fences(cq.as_raw(), chunk); + }); + cq.Signal(&done_c, 1).unwrap(); + + // Cycle breaking: dl writes va_a (which cq is blocked on) and waits on va_b (from cq). + // Must detect the cycle, skip hoisting va_b ahead of dl, submit dl immediately, and unblock BOTH queues! + let dcl: ID3D12CommandList = dl.cast().unwrap(); + execute_with_waits_on(dq.as_raw(), &[dl_ptr], |chunk| { + dq.ExecuteCommandLists(&[Some(dcl.clone())]); + signal_write64_fences(dq.as_raw(), chunk); + }); + dq.Signal(&done_d, 1).unwrap(); + + assert!(t0.elapsed().as_millis() < 500, "submits must not stall CPU (took {} ms)", t0.elapsed().as_millis()); + crate::gpu::fence::wait(&done_d, 1, &dev, None, 2000).expect("DIRECT must finish without GPU deadlock"); + crate::gpu::fence::wait(&done_c, 1, &dev, None, 2000).expect("COMPUTE must finish once DIRECT signals A"); + + on_release(dl_ptr as usize); + on_release(cl1_ptr as usize); + on_release(cl2_ptr as usize); + if let Some(gr) = SYNC_GRAPH.lock().unwrap().as_mut() { + gr.cells.remove(&va_a); + gr.cells.remove(&va_b); + } + } + } + + /// Exact `(queue, seq)` cycle detection must catch k=1 self-deadlocks, k=2 and k=3 transitive + /// cycles (including mixed title-fence + Wait64 cycles) while NEVER false-positiving on + /// pipelined frame N/N+1 or back-to-back cross-queue handshakes (`wait_seq > prod_sig_seq`). + #[test] + fn pipelined_next_frame_write_is_not_false_cycle() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + + unsafe { + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + let Ok(factory) = CreateDXGIFactory1::() else { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + }; + let Ok(warp) = factory.EnumWarpAdapter::() else { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + }; + if D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + } + let dev = dev.unwrap(); + + // 1. Back-to-back handshake (NOT a cycle): + // q0 signals A=10 at seq=2, then waits on B=10 at seq=3. + // q1 waits on A=10 at seq=1, then wants to signal B=10 (seq=2). + // Since q0's wait on B (seq=3) is AFTER q0's signal of A (seq=2), NOT a cycle! + let f_a: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let f_b: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let mut g = SyncGraph::default(); + g.cells.insert( + 0x1000, + SyncCell { + fence: Some(f_a), + device: dev.as_raw() as usize, + recorded_max: 10, + submitted_max: 10, + submitted_queue: Some(0xC001), + armed_waits: vec![ArmedGpuWait { + val: 10, + waiting_queue: 0xD001, + waiting_queue_ty: D3D12_COMMAND_LIST_TYPE_DIRECT.0, + wait_seq: 1, + armed_at: Instant::now(), + after_write64: false, + }], + submitted_signals: vec![SubmittedSignal { val: 10, queue: 0xC001, seq: 2 }], + ..Default::default() + }, + ); + g.cells.insert( + 0x2000, + SyncCell { + fence: Some(f_b), + device: dev.as_raw() as usize, + recorded_max: 10, + armed_waits: vec![ArmedGpuWait { + val: 10, + waiting_queue: 0xC001, + waiting_queue_ty: D3D12_COMMAND_LIST_TYPE_COMPUTE.0, + wait_seq: 3, // AFTER q0's signal of A (seq=2)! + armed_at: Instant::now(), + after_write64: false, + }], + ..Default::default() + }, + ); + assert!( + !would_signal_close_cycle(&mut g, 0xD001, 0x2000, 10), + "back-to-back handshake (wait_seq=3 > sig_seq=2) must NOT be treated as a cycle" + ); + // Now invert q0's order: q0 waited on B at seq=1 BEFORE signaling A at seq=2 -> TRUE cycle! + g.cells.get_mut(&0x2000).unwrap().armed_waits[0].wait_seq = 1; + assert!( + would_signal_close_cycle(&mut g, 0xD001, 0x2000, 10), + "2-queue cycle (wait_seq=1 < sig_seq=2) MUST be detected at Signal time" + ); + // k = 1 self-deadlock: q0 signaling B when q0 itself is waiting on B. + assert!( + would_signal_close_cycle(&mut g, 0xC001, 0x2000, 10), + "same-queue self-deadlock MUST be detected at Signal time" + ); + + // 2. 3-queue transitive cycle: Direct -> C1 -> C2 -> Direct. + // C2 waits on D (0x3000, seq=1), then signals C2_out (0x2000, seq=2). + // C1 waits on C2_out (0x2000, seq=1), then signals C1_out (0x1000, seq=2). + // Direct waits on C1_out (0x1000, seq=1), then wants to signal D (0x3000). + let f1: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let f2: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let f3: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let mut g3 = SyncGraph::default(); + g3.cells.insert( + 0x1000, + SyncCell { + fence: Some(f1), + device: dev.as_raw() as usize, + recorded_max: 0x78d, + submitted_max: 0x78d, + submitted_queue: Some(0xC001), + armed_waits: vec![ArmedGpuWait { + val: 0x78d, + waiting_queue: 0xD001, + waiting_queue_ty: D3D12_COMMAND_LIST_TYPE_DIRECT.0, + wait_seq: 1, + armed_at: Instant::now(), + after_write64: false, + }], + submitted_signals: vec![SubmittedSignal { val: 0x78d, queue: 0xC001, seq: 2 }], + ..Default::default() + }, + ); + g3.cells.insert( + 0x2000, + SyncCell { + fence: Some(f2), + device: dev.as_raw() as usize, + recorded_max: 0x78d, + submitted_max: 0x78d, + submitted_queue: Some(0xC002), + armed_waits: vec![ArmedGpuWait { + val: 0x78d, + waiting_queue: 0xC001, + waiting_queue_ty: D3D12_COMMAND_LIST_TYPE_COMPUTE.0, + wait_seq: 1, + armed_at: Instant::now(), + after_write64: false, + }], + submitted_signals: vec![SubmittedSignal { val: 0x78d, queue: 0xC002, seq: 2 }], + ..Default::default() + }, + ); + g3.cells.insert( + 0x3000, + SyncCell { + fence: Some(f3), + device: dev.as_raw() as usize, + recorded_max: 0x78d, + armed_waits: vec![ArmedGpuWait { + val: 0x78d, + waiting_queue: 0xC002, + waiting_queue_ty: D3D12_COMMAND_LIST_TYPE_COMPUTE.0, + wait_seq: 1, + armed_at: Instant::now(), + after_write64: false, + }], + ..Default::default() + }, + ); + assert!( + would_signal_close_cycle(&mut g3, 0xD001, 0x3000, 0x78d), + "3-queue transitive cycle Direct -> C1 -> C2 -> Direct MUST be detected at Signal time" + ); + // If C2 waited on D AFTER signaling C2_out (wait_seq=3 > sig_seq=2), NOT a cycle. + g3.cells.get_mut(&0x3000).unwrap().armed_waits[0].wait_seq = 3; + assert!( + !would_signal_close_cycle(&mut g3, 0xD001, 0x3000, 0x78d), + "pipelined 3-queue chain with wait_seq > sig_seq must NOT be treated as a cycle" + ); + } + } + + /// Reproduces two real multi-queue hazards seen in retail titles: + /// 1. Rotating compute queues where cell `va` was previously written by `cq0` in frame N, + /// then in frame N+1 `cq1` waits on `va` before `cq1` itself submits the write to `va` + /// (same-queue self-deadlock despite stale `submitted_queue == cq0`). + /// 2. A Wait64 cell becoming non-monotonic (`value < submitted_max`) while another queue + /// already has an armed `queue.Wait` on it — must rescue the waiter instead of orphaning it. + #[test] + fn rotating_queue_self_deadlock_and_non_monotonic_rescue_do_not_hang() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + + unsafe { + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + let Ok(factory) = CreateDXGIFactory1::() else { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + }; + let Ok(warp) = factory.EnumWarpAdapter::() else { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + }; + if D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + } + let dev = dev.unwrap(); + let cq0: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_COMPUTE, ..Default::default() }).unwrap(); + let cq1: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_COMPUTE, ..Default::default() }).unwrap(); + let a0: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE).unwrap(); + let a1: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE).unwrap(); + let a2: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE).unwrap(); + let l0: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COMPUTE, &a0, None).unwrap(); + let l1: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COMPUTE, &a1, None).unwrap(); + let l2: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COMPUTE, &a2, None).unwrap(); + let done1: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + + let cell_rot = Box::new(AtomicU64::new(0)); + let va_rot = &*cell_rot as *const AtomicU64 as u64; + let (l0_ptr, l1_ptr, l2_ptr) = (l0.as_raw(), l1.as_raw(), l2.as_raw()); + on_create(l0_ptr, a0.as_raw() as usize, 0, D3D12_COMMAND_LIST_TYPE_COMPUTE); + on_create(l1_ptr, a1.as_raw() as usize, 0, D3D12_COMMAND_LIST_TYPE_COMPUTE); + on_create(l2_ptr, a2.as_raw() as usize, 0, D3D12_COMMAND_LIST_TYPE_COMPUTE); + + // Frame 0x69f: cq0 writes va_rot = 0x69f (sets stale submitted_queue = cq0). + note_write64_recorded(l0_ptr, va_rot, 0x69f); + l0.Close().unwrap(); + let cl0: ID3D12CommandList = l0.cast().unwrap(); + execute_with_waits_on(cq0.as_raw(), &[l0_ptr], |chunk| { + cq0.ExecuteCommandLists(&[Some(cl0.clone())]); + signal_write64_fences(cq0.as_raw(), chunk); + }); + + // Frame 0x6a0: l2 records write va_rot = 0x6a0, l1 waits on va_rot >= 0x6a0. + // Both l1 and l2 are submitted on cq1 (rotated from cq0 -> cq1)! + note_write64_recorded(l2_ptr, va_rot, 0x6a0); + wait64_x(l1_ptr, va_rot, D3D12_COMPARISON_FUNC_GREATER_EQUAL.0 as u32, 0x6a0, 1, 0); + l1.Close().unwrap(); + l2.Close().unwrap(); + + let t0 = Instant::now(); + let cl1: ID3D12CommandList = l1.cast().unwrap(); + let cl2: ID3D12CommandList = l2.cast().unwrap(); + execute_with_waits_on(cq1.as_raw(), &[l1_ptr], |chunk| { + cq1.ExecuteCommandLists(&[Some(cl1.clone())]); + signal_write64_fences(cq1.as_raw(), chunk); + }); + execute_with_waits_on(cq1.as_raw(), &[l2_ptr], |chunk| { + cq1.ExecuteCommandLists(&[Some(cl2.clone())]); + signal_write64_fences(cq1.as_raw(), chunk); + }); + cq1.Signal(&done1, 1).unwrap(); + + // Must break self-deadlock immediately on CPU at Signal time (not wait 5s for watchdog!). + crate::gpu::fence::wait(&done1, 1, &dev, None, 1500).expect("cq1 must complete immediately without self-deadlock"); + assert!(t0.elapsed().as_millis() < 1500, "took {} ms", t0.elapsed().as_millis()); + + // Part 2: Non-monotonic rescue while a GPU wait is armed. + let cell_nm = Box::new(AtomicU64::new(0)); + let va_nm = &*cell_nm as *const AtomicU64 as u64; + let a3: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE).unwrap(); + let a4: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE).unwrap(); + let a5: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE).unwrap(); + let l3: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COMPUTE, &a3, None).unwrap(); + let l4: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COMPUTE, &a4, None).unwrap(); + let l5: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COMPUTE, &a5, None).unwrap(); + let done2: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let (l3_ptr, l4_ptr, l5_ptr) = (l3.as_raw(), l4.as_raw(), l5.as_raw()); + on_create(l3_ptr, a3.as_raw() as usize, 0, D3D12_COMMAND_LIST_TYPE_COMPUTE); + on_create(l4_ptr, a4.as_raw() as usize, 0, D3D12_COMMAND_LIST_TYPE_COMPUTE); + on_create(l5_ptr, a5.as_raw() as usize, 0, D3D12_COMMAND_LIST_TYPE_COMPUTE); + + // Submit 10 first -> submitted_max = 10. + note_write64_recorded(l3_ptr, va_nm, 10); + l3.Close().unwrap(); + let cl3: ID3D12CommandList = l3.cast().unwrap(); + execute_with_waits_on(cq0.as_raw(), &[l3_ptr], |chunk| { + cq0.ExecuteCommandLists(&[Some(cl3.clone())]); + signal_write64_fences(cq0.as_raw(), chunk); + }); + // Record 20 (unsubmitted), then arm cq1 wait for >= 20. + note_write64_recorded(l4_ptr, va_nm, 20); + wait64_x(l5_ptr, va_nm, D3D12_COMPARISON_FUNC_GREATER_EQUAL.0 as u32, 20, 1, 0); + l5.Close().unwrap(); + let cl5: ID3D12CommandList = l5.cast().unwrap(); + execute_with_waits_on(cq1.as_raw(), &[l5_ptr], |chunk| { + cq1.ExecuteCommandLists(&[Some(cl5.clone())]); + signal_write64_fences(cq1.as_raw(), chunk); + }); + cq1.Signal(&done2, 1).unwrap(); + // Now record a strictly decreasing write (5 < submitted_max 10) -> non_monotonic! + // Must rescue cq1's armed wait on CPU before dropping the fence! + note_write64_recorded(l4_ptr, va_nm, 5); + crate::gpu::fence::wait(&done2, 1, &dev, None, 1500).expect("cq1 must be rescued when cell goes non-monotonic"); + + for p in [l0_ptr, l1_ptr, l2_ptr, l3_ptr, l4_ptr, l5_ptr] { + on_release(p as usize); + } + if let Some(gr) = SYNC_GRAPH.lock().unwrap().as_mut() { + gr.cells.remove(&va_rot); + gr.cells.remove(&va_nm); + } + } + } + + /// Verifies that CPU-signalling a fence while a GPU `queue.Signal` to the same value is + /// already in flight (watchdog release path) does not hang subsequent queue completions. + #[test] + fn cpu_watchdog_signal_with_inflight_gpu_signal_completes_cleanly() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + + unsafe { + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + let Ok(factory) = CreateDXGIFactory1::() else { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + }; + let Ok(warp) = factory.EnumWarpAdapter::() else { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + }; + if D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + } + let dev = dev.unwrap(); + let q1: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); + let q2: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_COMPUTE, ..Default::default() }).unwrap(); + let f_a: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let f_b: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let done1: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let done2: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + + // Deliberate 2-queue cycle with in-flight GPU signals to value 10 on both fences. + q1.Wait(&f_a, 10).unwrap(); + q1.Signal(&f_b, 10).unwrap(); + q1.Signal(&done1, 1).unwrap(); + q2.Wait(&f_b, 10).unwrap(); + q2.Signal(&f_a, 10).unwrap(); + q2.Signal(&done2, 1).unwrap(); + + // Simulate watchdog breaking the deadlock from CPU on both fences while GPU signals are in flight. + f_a.Signal(10).unwrap(); + f_b.Signal(10).unwrap(); + + crate::gpu::fence::wait(&done1, 1, &dev, None, 2000).expect("q1 must complete after watchdog CPU signal"); + crate::gpu::fence::wait(&done2, 1, &dev, None, 2000).expect("q2 must complete after watchdog CPU signal"); + } + } + + /// 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) + /// Without deferred mid-list splitting, hoisting Wait64(cell_B) ahead of Write64(cell_A) creates + /// a 2-queue deadlock cycle every frame. With deferred splitting, O_c expands into `[pc_c0, pc_c1]`, + /// completes on GPU with ZERO CPU cycle breaks, and reuses `pc_c1` from the spare pool on Reset. + #[test] + fn mid_list_write64_wait64_split_avoids_cycle_and_reuses_spares() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + + unsafe { + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + let Ok(factory) = CreateDXGIFactory1::() else { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + }; + let Ok(warp) = factory.EnumWarpAdapter::() else { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + }; + if D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + } + let dev = dev.unwrap(); + let q_comp: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_COMPUTE, ..Default::default() }).unwrap(); + let q_dir: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); + let a_comp: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE).unwrap(); + let a_dir: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let raw_c: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COMPUTE, &a_comp, None).unwrap(); + let raw_d: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &a_dir, None).unwrap(); + let done_c: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let done_d: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + + // Transfer raw_c into `title_list::wrap` (the wrapper owns the COM ref). + let pc_c0 = raw_c.into_raw(); + real::adopt(pc_c0, real::Kind::CommandList); + on_create(pc_c0, a_comp.as_raw() as usize, 0, D3D12_COMMAND_LIST_TYPE_COMPUTE); + super::super::bind::reset(pc_c0, a_comp.as_raw() as usize, 0); + let wrap_c = super::super::title_list::wrap(pc_c0); + + let pc_d0 = raw_d.as_raw(); + real::adopt(pc_d0, real::Kind::CommandList); + on_create(pc_d0, a_dir.as_raw() as usize, 0, D3D12_COMMAND_LIST_TYPE_DIRECT); + + let cell_a = Box::new(AtomicU64::new(0)); + let cell_b = Box::new(AtomicU64::new(0)); + let cell_c = Box::new(AtomicU64::new(0)); + let va_a = &*cell_a as *const AtomicU64 as u64; + let va_b = &*cell_b as *const AtomicU64 as u64; + let va_c = &*cell_c as *const AtomicU64 as u64; + + let mut first_seg1: *mut c_void = std::ptr::null_mut(); + for frame in 1u64..=2 { + if frame > 1 { + a_comp.Reset().unwrap(); + a_dir.Reset().unwrap(); + // Reset through `title_list` slot #10: must switch back to `pc_c0` and keep `seg1` as spare. + let reset_fn: unsafe extern "system" fn(*mut c_void, usize, usize) -> i32 = + std::mem::transmute(*(*(wrap_c as *const *const usize)).add(10)); + assert_eq!(reset_fn(wrap_c, a_comp.as_raw() as usize, 0), 0); + assert_eq!(reset_x(pc_d0, a_dir.as_raw() as usize, 0), 0); + } + + // Record O_d: Wait64(A >= frame) -> Write64(B, frame) -> Close (seed cell_B recorded + // first so O_c's Wait64(B) bridges to GPU even though O_c submits before O_d). + note_write64_recorded(pc_c0, va_a, frame); + let mut g = SYNC_GRAPH.lock().unwrap(); + let cell_b_entry = g.get_or_insert_with(SyncGraph::default).cells.entry(va_b).or_default(); + cell_b_entry.recorded_max = cell_b_entry.recorded_max.max(frame); + cell_b_entry.recorded_list_type = Some(D3D12_COMMAND_LIST_TYPE_DIRECT); + drop(g); + // Call wait64_x on the active PC segment (`pc_c0`); it looks up `wrap_c`, splits into + // `[pc_c0, seg1]`, and switches `wrap_c`'s `F_BACKING` to `seg1`. + wait64_x(pc_c0, va_b, D3D12_COMPARISON_FUNC_GREATER_EQUAL.0 as u32, frame, 0, 0); + + // Verify the split created/reused a second segment. + let mut segs_c = Vec::new(); + assert!(super::super::title_list::push_segments(wrap_c, &mut segs_c)); + assert_eq!(segs_c.len(), 2, "frame {frame}: mid-list Wait64 after Write64 must split into 2 segments"); + assert_eq!(segs_c[0], pc_c0); + assert_ne!(segs_c[1], pc_c0); + if frame == 1 { + first_seg1 = segs_c[1]; + } else { + assert_eq!(segs_c[1], first_seg1, "frame 2 split must reuse spare PC command list"); + } + + // Write64(C, frame) lands on the second segment. + note_write64_recorded(segs_c[1], va_c, frame); + + // Close O_c via title_list slot #9 (closes segs_c[1]; segs_c[0] was already closed on split). + let close_fn: unsafe extern "system" fn(*mut c_void) -> i32 = + std::mem::transmute(*(*(wrap_c as *const *const usize)).add(9)); + assert_eq!(close_fn(wrap_c), 0, "frame {frame}: Close on split title_list failed"); + + // Record O_d: Wait64(A >= frame) -> Write64(B, frame) -> Close. + wait64_x(pc_d0, va_a, D3D12_COMPARISON_FUNC_GREATER_EQUAL.0 as u32, frame, 0, 0); + note_write64_recorded(pc_d0, va_b, frame); + let cl_d_raw = ID3D12GraphicsCommandList::from_raw_borrowed(&pc_d0).unwrap(); + cl_d_raw.Close().unwrap(); + + // Execute O_c segments on q_comp FIRST (just like the real title!). + execute_with_waits_on(q_comp.as_raw(), &segs_c, |chunk| { + type ExecFn = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void); + let exec: ExecFn = std::mem::transmute(*(*(q_comp.as_raw() as *const *const usize)).add(PC_QUEUE_EXECUTE_COMMAND_LISTS)); + exec(q_comp.as_raw(), chunk.len() as u32, chunk.as_ptr()); + signal_write64_fences(q_comp.as_raw(), chunk); + if chunk.contains(&pc_c0) { + cell_a.store(frame, Ordering::Release); + } + }); + q_comp.Signal(&done_c, frame).unwrap(); + + // Execute O_d on q_dir SECOND. + let one_d = [pc_d0]; + execute_with_waits_on(q_dir.as_raw(), &one_d, |chunk| { + type ExecFn = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void); + let exec: ExecFn = std::mem::transmute(*(*(q_dir.as_raw() as *const *const usize)).add(PC_QUEUE_EXECUTE_COMMAND_LISTS)); + exec(q_dir.as_raw(), chunk.len() as u32, chunk.as_ptr()); + signal_write64_fences(q_dir.as_raw(), chunk); + cell_b.store(frame, Ordering::Release); + }); + q_dir.Signal(&done_d, frame).unwrap(); + + crate::gpu::fence::wait(&done_c, frame, &dev, None, 2000).expect("compute queue must complete without cycle"); + crate::gpu::fence::wait(&done_d, frame, &dev, None, 2000).expect("direct queue must complete without cycle"); + + // CRITICAL: verify ZERO CPU cycle breaks occurred on ANY of the 3 cells! + let g = SYNC_GRAPH.lock().unwrap(); + let gr = g.as_ref().unwrap(); + for (name, va) in [("cell_A", va_a), ("cell_B", va_b), ("cell_C", va_c)] { + let c = gr.cells.get(&va).unwrap(); + assert_eq!(c.cpu_signaled_max, 0, "frame {frame}: {name} must NOT trigger a CPU cycle break"); + assert_eq!(c.submitted_max, frame, "frame {frame}: {name} must reach frame {frame} on GPU"); + } + } + + // Release wrapped list (must release primary + spare segment cleanly). + let rel_fn: unsafe extern "system" fn(*mut c_void) -> u32 = + std::mem::transmute(*(*(wrap_c as *const *const usize)).add(2)); + assert_eq!(rel_fn(wrap_c), 0); + on_release(pc_d0 as usize); + if let Some(gr) = SYNC_GRAPH.lock().unwrap().as_mut() { + gr.cells.remove(&va_a); + gr.cells.remove(&va_b); + gr.cells.remove(&va_c); + } + } + } } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index aed907586..e6c38326b 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -2650,6 +2650,34 @@ creator!(dev_create_command_queue1, "CreateCommandQueue1", Kind::CommandQueue, [ creator!(dev_create_command_allocator, "CreateCommandAllocator", Kind::CommandAllocator, [a1]); creator!(dev_create_command_list, "CreateCommandList", Kind::CommandList, [a1, a2, a3, a4]); creator!(dev_create_command_list1, "CreateCommandList1", Kind::CommandList, [a1, a2, a3]); + +/// Create a raw adopted PC `ID3D12GraphicsCommandList` without wrapping it in `title_list` +/// (used for deferred mid-list split segments on the same allocator). +pub(super) unsafe fn create_raw_pc_command_list( + dev: *mut c_void, + ty: D3D12_COMMAND_LIST_TYPE, + alloc: usize, + init_pso: usize, +) -> Option<*mut c_void> { + if dev.is_null() || alloc == 0 { + return None; + } + let iid = layout::parse_guid(layout::find("ID3D12GraphicsCommandList")?.iid); + let mut out: *mut c_void = std::ptr::null_mut(); + let hr = if is_ext(vt(dev) as usize) { + dev_create_command_list(dev, 0, ty.0 as usize, alloc, init_pso, &iid, &mut out) + } else { + type F = unsafe extern "system" fn(*mut c_void, u32, D3D12_COMMAND_LIST_TYPE, usize, usize, *const GUID, *mut *mut c_void) -> HRESULT; + let slot = layout::slot(layout::find("ID3D12Device")?, "CreateCommandList")?; + let f: F = std::mem::transmute(*vt(dev).add(slot)); + let hr = f(dev, 0, ty, alloc, init_pso, &iid, &mut out); + if hr >= 0 && !out.is_null() { + adopt(out, Kind::CommandList); + } + hr + }; + (hr >= 0 && !out.is_null()).then_some(out) +} creator!(dev_create_descriptor_heap, "CreateDescriptorHeap", Kind::DescriptorHeap, [a1]); creator!(dev_create_committed_resource, "CreateCommittedResource", Kind::Resource, [a1, a2, a3, a4, a5]); creator!(dev_create_committed_resource1, "CreateCommittedResource1", Kind::Resource, [a1, a2, a3, a4, a5, a6]); @@ -4906,10 +4934,19 @@ unsafe fn queue_dispatch(slot: usize, this: *mut c_void, a1: usize, a2: usize, a match older { // Signal / Wait take a fence: anything else is not one of them 14 | 15 if is_fence(a1) => { + if older == 14 { + super::list_x::break_cycles_before_title_signal(this as usize, a1, a2 as u64); + } let f: unsafe extern "system" fn(*mut c_void, usize, usize) -> i32 = std::mem::transmute(pc(if older == 14 { PC_SIGNAL } else { PC_WAIT })); let hr = f(this, a1, a2); - if older == 14 && hr >= 0 { - super::fence_x::note_queue_signal(a1, a2 as u64); + if hr >= 0 { + if older == 14 { + super::fence_x::note_queue_signal(a1, a2 as u64); + super::list_x::note_title_queue_signal(this as usize, a1, a2 as u64); + } else { + super::fence_x::note_queue_wait(a1, a2 as u64); + super::list_x::note_title_queue_wait(this as usize, a1, a2 as u64); + } } hr as u32 as usize } @@ -4993,10 +5030,12 @@ queue_slots!(14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, /// never released, and the garbage collector ended the game after 10 s.) unsafe extern "system" fn q_signal_x(this: *mut c_void, fence: *mut c_void, value: u64, _flags: u32) -> HRESULT { const PC_SIGNAL: usize = 14; + super::list_x::break_cycles_before_title_signal(this as usize, fence as usize, value); let f: unsafe extern "system" fn(*mut c_void, *mut c_void, u64) -> HRESULT = std::mem::transmute(orig_fn(this, PC_SIGNAL)); let hr = f(this, fence, value); if hr >= 0 { super::fence_x::note_queue_signal(fence as usize, value); + super::list_x::note_title_queue_signal(this as usize, fence as usize, value); } hr } @@ -5019,14 +5058,20 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis } // textures in title memory the CPU wrote since: uploaded again first super::title_textures::refresh(this); - // console-shaped lists run as the PC lists they were translated into - let mapped: Vec<*mut c_void> = std::slice::from_raw_parts(lists, n as usize) - .iter() - .map(|&l| super::console_list::pc_list(l).or_else(|| super::title_list::backing(l)).unwrap_or(l)) - .collect(); + // console-shaped lists run as the PC lists they were translated into (split title lists expand + // into all of their recorded PC segments in exact chronological order) + let mut mapped: Vec<*mut c_void> = Vec::with_capacity(n as usize); + for &l in std::slice::from_raw_parts(lists, n as usize) { + if let Some(pc) = super::console_list::pc_list(l) { + mapped.push(pc); + } else if !super::title_list::push_segments(l, &mut mapped) { + mapped.push(l); + } + } super::list_x::note_queue_for_lists(this as usize, &mapped); - super::list_x::execute_with_waits(&mapped, |chunk| { + super::list_x::execute_with_waits_on(this, &mapped, |chunk| { f(this, chunk.len() as u32, chunk.as_ptr()); + super::list_x::signal_write64_fences(this, chunk); super::list_x::readback_sparse_writes(this, chunk); super::list_x::cpu_writes_after(this, chunk); }); diff --git a/crates/xcl/src/hle/d3d12x/title_list.rs b/crates/xcl/src/hle/d3d12x/title_list.rs index de3dc7526..05de94b66 100644 --- a/crates/xcl/src/hle/d3d12x/title_list.rs +++ b/crates/xcl/src/hle/d3d12x/title_list.rs @@ -14,8 +14,9 @@ //! hands out the console object again, Release frees it with the PC list, and //! ExecuteCommandLists runs the PC lists (`backing`). +use std::collections::HashMap; use std::ffi::c_void; -use std::sync::OnceLock; +use std::sync::{Mutex, OnceLock}; use windows_sys::core::GUID; @@ -23,9 +24,11 @@ use crate::util::HRESULT; const LIST_SLOTS: usize = 600; /// the object: console fields up to `ROOM`, no-room "buffer" at `ROOM` (with slack after it -/// for code that would write before checking), the PC list at `F_BACKING` +/// for code that would write before checking), primary PC list at `F_PRIMARY` (identity / +/// refcount), currently active recording PC list at `F_BACKING` (swapped on mid-list sync split). const OBJECT_BYTES: usize = 0x3000; const ROOM: usize = 0x1000; +const F_PRIMARY: usize = 0x2FF0; const F_BACKING: usize = 0x2FF8; const F_WRITE: usize = 0x18; const F_DISPATCH_END: usize = 0x28; @@ -34,11 +37,26 @@ const F_END: usize = 0x30; const F_RING: usize = 0x2000; const F_RING_AT: usize = 0x2100; const RING: usize = 64; +/// Maximum number of mid-list split segments per command list recording. +const MAX_EXTRA_SEGMENTS: usize = 32; + +#[derive(Default)] +struct SegmentBook { + /// Additional PC command lists recorded after `primary` in this recording (in order). + extra_active: Vec, + /// Closed extra PC command lists from earlier recordings, kept for reuse on future splits. + spares: Vec, +} + +/// Wrapper address -> split segment book (populated lazily only for lists that split). +static SEGMENTS: Mutex>> = Mutex::new(None); +/// Active recording PC command list address -> `title_list` wrapper address. +static WRAPPER_OF: Mutex>> = Mutex::new(None); struct Vtable(usize); -/// The console list vtable: QueryInterface / Release of their own, every other slot a thunk -/// to the PC list's entry. +/// The console list vtable: QueryInterface / AddRef / Release / Close / Reset of their own, +/// every other slot a thunk to the currently active PC list's entry (`F_BACKING`). fn vtable() -> usize { static V: OnceLock = OnceLock::new(); V.get_or_init(|| { @@ -48,8 +66,10 @@ fn vtable() -> usize { *e = if trace { forward_traced(slot) } else { forward(slot) }; } v[0] = qi as usize; + v[1] = add_ref as usize; v[2] = release as usize; v[9] = close as usize; + v[10] = reset as usize; Vtable(Box::leak(v.into_boxed_slice()).as_ptr() as usize) }) .0 @@ -103,7 +123,8 @@ unsafe extern "system" fn record(this: *mut c_void, slot: u32) { *at += 1; } -/// #9 Close: a failure is logged with the last methods called (`XCL_LIST_TRACE`) +/// #9 Close: closes the active recording segment (`F_BACKING`); a failure is logged with +/// the last methods called (`XCL_LIST_TRACE`). Prior split segments were closed on split. unsafe extern "system" fn close(this: *mut c_void) -> HRESULT { let pc = *((this as usize + F_BACKING) as *const *mut c_void); let f: unsafe extern "system" fn(*mut c_void) -> HRESULT = std::mem::transmute(pc_slot(pc, 9)); @@ -119,6 +140,50 @@ 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` +/// (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 { + 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) + } 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 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() + }; + if !moved.is_empty() { + 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); + } + drop(wg); + for seg in moved { + super::bind::reset(seg as *mut c_void, 0, 0); + super::list_x::clear_segment_state(seg); + } + } + *((this as usize + F_RING_AT) as *mut usize) = 0; + } + hr +} + /// The console object for the PC list `pc` (adopted; one reference moves to it). pub unsafe fn wrap(pc: *mut c_void) -> *mut c_void { if pc.is_null() { @@ -134,23 +199,116 @@ pub unsafe fn wrap(pc: *mut c_void) -> *mut c_void { for f in [F_WRITE, F_DISPATCH_END, F_END] { *(o.add(f) as *mut usize) = room; } + *(o.add(F_PRIMARY) as *mut usize) = pc as usize; *(o.add(F_BACKING) as *mut usize) = pc as usize; + WRAPPER_OF.lock().unwrap().get_or_insert_with(HashMap::new).insert(pc as usize, o as usize); o as *mut c_void } -/// The PC list behind a console list object (None: not one). +/// The primary PC list behind a console list object (None: not one). pub fn backing(list: *mut c_void) -> Option<*mut c_void> { if list.is_null() || !crate::gpu::shader::readable(list as usize, 8) { return None; } - unsafe { (*(list as *const usize) == vtable()).then(|| *((list as usize + F_BACKING) as *const *mut c_void)) } + unsafe { (*(list as *const usize) == vtable()).then(|| *((list as usize + F_PRIMARY) as *const *mut c_void)) } +} + +/// Expand a console list object into all of its recorded PC command list segments (in exact +/// recording order). Returns `false` if `list` is not a `title_list` wrapper. +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))) { + for &seg in &book.extra_active { + out.push(seg as *mut c_void); + } + } + true +} + +/// Look up the `title_list` wrapper currently recording into `pc`. +pub(super) fn wrapper_of(pc: *mut c_void) -> Option<*mut c_void> { + if pc.is_null() { + return None; + } + WRAPPER_OF.lock().unwrap().as_ref()?.get(&(pc as usize)).map(|&w| w as *mut c_void) +} + +/// Whether `wrapper` may allocate/activate another split segment for this recording. +pub(super) fn can_split(wrapper: *mut c_void) -> bool { + let sg = SEGMENTS.lock().unwrap(); + sg.as_ref() + .and_then(|m| m.get(&(wrapper as usize))) + .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. +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) +} + +/// Switch `wrapper` from closed segment `old_pc` to newly opened segment `new_pc`. +pub(super) unsafe fn activate_segment(wrapper: *mut c_void, old_pc: *mut c_void, new_pc: *mut c_void) { + *((wrapper as usize + F_BACKING) as *mut usize) = new_pc as usize; + { + let mut sg = SEGMENTS.lock().unwrap(); + sg.get_or_insert_with(HashMap::new) + .entry(wrapper as usize) + .or_default() + .extra_active + .push(new_pc as usize); + } + let mut wg = WRAPPER_OF.lock().unwrap(); + let m = wg.get_or_insert_with(HashMap::new); + m.remove(&(old_pc as usize)); + m.insert(new_pc as usize, wrapper as usize); +} + +/// 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`. +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); + 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); + for &seg in &extra { + if seg != active_pc as usize { + prior.push(seg as *mut c_void); + } + } + book.spares.extend(extra.iter().copied()); + (prior, extra) + }; + *((wrapper as usize + F_BACKING) as *mut usize) = primary as usize; + { + let mut wg = WRAPPER_OF.lock().unwrap(); + if let Some(m) = wg.as_mut() { + for &seg in &reclaimed { + m.remove(&seg); + } + m.insert(primary as usize, wrapper as usize); + } + } + Some((primary, prior, reclaimed)) } unsafe fn pc_slot(pc: *mut c_void, slot: usize) -> usize { *(*(pc as *const *const usize)).add(slot) } -/// QueryInterface: the PC list answers; where it hands out itself, the console object goes out. +/// QueryInterface: the primary PC list answers; where it hands out itself, the console object goes out. /// Command list interfaces of the console's headers that the PC does not know: the console's /// ID3D12GraphicsCommandList5 / 6 (the PC's data1–data3, another tail – titles ask for them /// and use the answer without a check). The console object has the console's whole vtable, @@ -161,13 +319,13 @@ const CONSOLE_LIST_IIDS: [(u32, u16, u16, [u8; 8]); 2] = [ ]; unsafe extern "system" fn qi(this: *mut c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { - let pc = *((this as usize + F_BACKING) as *const *mut c_void); + let pc = *((this as usize + F_PRIMARY) as *const *mut c_void); let f: unsafe extern "system" fn(*mut c_void, *const GUID, *mut *mut c_void) -> HRESULT = std::mem::transmute(pc_slot(pc, 0)); if !riid.is_null() && !ppv.is_null() { let g = &*riid; if CONSOLE_LIST_IIDS.contains(&(g.data1, g.data2, g.data3, g.data4)) { - let add_ref: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(pc_slot(pc, 1)); - add_ref(pc); + let add_ref_fn: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(pc_slot(pc, 1)); + add_ref_fn(pc); *ppv = this; return 0; } @@ -179,12 +337,40 @@ unsafe extern "system" fn qi(this: *mut c_void, riid: *const GUID, ppv: *mut *mu hr } -/// Release: the console object goes with the PC list's last reference. +/// AddRef: always references the primary PC list (`F_PRIMARY`). +unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 { + let pc = *((this as usize + F_PRIMARY) as *const *mut c_void); + let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(pc_slot(pc, 1)); + f(pc) +} + +/// Release: the console object (and any extra split segment PC lists) goes with the primary PC +/// list's last reference. unsafe extern "system" fn release(this: *mut c_void) -> u32 { - let pc = *((this as usize + F_BACKING) as *const *mut c_void); + let pc = *((this as usize + F_PRIMARY) as *const *mut c_void); let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(pc_slot(pc, 2)); let n = f(pc); if n == 0 { + let book = SEGMENTS.lock().unwrap().as_mut().and_then(|m| m.remove(&(this as usize))); + { + let mut wg = WRAPPER_OF.lock().unwrap(); + 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()) { + m.remove(&seg); + } + } + } + } + if let Some(b) = book { + for seg in b.extra_active.into_iter().chain(b.spares.into_iter()) { + 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)); + rel(raw); + } + } super::bind::forget(pc); std::alloc::dealloc(this as *mut u8, std::alloc::Layout::from_size_align(OBJECT_BYTES, 64).unwrap()); }