diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index ee544dec22..536e9e8b21 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -17,7 +17,7 @@ //! go to that window's buffer (`real::uma_window_buffer`), which is in COMMON between them. //! An index buffer at such an address is given to the PC as the window buffer's GPU address. -use std::collections::HashMap; +use std::collections::{BTreeMap, HashMap}; use std::ffi::c_void; use std::mem::{transmute_copy, ManuallyDrop}; use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, AtomicUsize, Ordering}; @@ -62,9 +62,6 @@ const WAIT_TIMEOUT: Duration = Duration::from_secs(2); /// cleanly without prematurely breaking synchronization. Overridable via `XCL_GPU_WAIT_TIMEOUT_MS` /// for diagnostics. 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(|| { @@ -607,6 +604,69 @@ unsafe fn restore_bindings(this: *mut c_void, b: &Bindings, ty: D3D12_COMMAND_LI } } +/// Canonical half-open UMA ranges written by one command-list recording. +/// +/// Keys are starts and values are exclusive ends. Overlapping and adjacent ranges are merged, +/// so lookup examines at most the predecessor and successor around the requested address. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +struct RecordedWrites { + ranges: BTreeMap, +} + +impl RecordedWrites { + fn insert(&mut self, va: u64, size: u64) { + if size == 0 { + return; + } + let mut start = va; + let mut end = va.saturating_add(size); + if end <= start { + return; + } + + if let Some((&previous_start, &previous_end)) = self.ranges.range(..=start).next_back() { + if previous_end >= start { + start = previous_start; + end = end.max(previous_end); + self.ranges.remove(&previous_start); + } + } + loop { + let next = self.ranges.range(start..).next().map(|(&s, &e)| (s, e)); + match next { + Some((next_start, next_end)) if next_start <= end => { + end = end.max(next_end); + self.ranges.remove(&next_start); + } + _ => break, + } + } + self.ranges.insert(start, end); + } + + fn overlaps(&self, va: u64, size: u64) -> bool { + if size == 0 { + return false; + } + let end = va.saturating_add(size); + if end <= va { + return false; + } + if self.ranges.range(..=va).next_back().is_some_and(|(_, &range_end)| range_end > va) { + return true; + } + self.ranges.range(va..).next().is_some_and(|(&range_start, _)| range_start < end) + } + + fn clear(&mut self) { + self.ranges.clear(); + } + + fn is_empty(&self) -> bool { + self.ranges.is_empty() + } +} + #[derive(Default)] struct ListState { allocator: usize, @@ -629,7 +689,7 @@ struct ListState { depth_bounds: Option<(f32, f32)>, occlusion: Occlusion, /// UMA address ranges written by this list since last Reset/KickoffX - written_ranges: Vec<(u64, u64)>, + written_ranges: RecordedWrites, /// 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)>, @@ -661,18 +721,27 @@ pub(super) enum Deferred { Indirect(usize, u32, usize, u64, usize, u64), } +/// Why a recording needs a physical command-list boundary. +pub(super) enum SegmentReason { + WaitAfterWrite64, + DeferredDispatch(Deferred), +} + +impl SegmentReason { + fn extra_segments(&self) -> usize { + match self { + Self::WaitAfterWrite64 => 1, + Self::DeferredDispatch(_) => 2, + } + } +} + impl ListState { fn note_write(&mut self, va: u64, size: u64) { if size == 0 { return; } - let end = va.saturating_add(size); - if self.written_ranges.len() < MAX_WRITTEN_RANGES { - self.written_ranges.push((va, end)); - } else if let Some(last) = self.written_ranges.last_mut() { - last.0 = last.0.min(va); - last.1 = last.1.max(end); - } + self.written_ranges.insert(va, size); if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(va as usize)) { if self.sparse_writes.is_empty() { SPARSE_WRITE_LISTS.fetch_add(1, Ordering::AcqRel); @@ -705,25 +774,81 @@ impl ListState { } 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) + self.written_ranges.overlaps(va, size) } fn clear_waits(&mut self) { - if !self.pending_waits.is_empty() { - self.pending_waits.clear(); - PENDING_WAIT_LISTS.fetch_sub(1, Ordering::AcqRel); - } + self.pending_waits.clear(); } fn push_wait(&mut self, w: PendingWait) { - if self.pending_waits.is_empty() { - PENDING_WAIT_LISTS.fetch_add(1, Ordering::AcqRel); - } self.pending_waits.push(w); } } +/// Recording state that a PC Reset loses and the continuation segment must inherit. +struct SplitCarry { + allocator: usize, + last_queue: Option, + bound_pso: usize, + depth_bias: Option, + index_buffer: Option, + depth_bounds: Option<(f32, f32)>, + predication: Option, + pred_buf: Option, + pred_in_state: bool, + active_query: Option<(Query, D3D12_QUERY_TYPE)>, + ended_early: Vec, + written_ranges: RecordedWrites, + bindings: Bindings, +} + +impl SplitCarry { + fn take(state: &mut ListState) -> Option { + if state.allocator == 0 { + return None; + } + let active_query = state.occlusion.end_active_early(); + Some(Self { + allocator: state.allocator, + last_queue: state.last_queue, + bound_pso: state.bound_pso, + depth_bias: state.depth_bias, + index_buffer: state.index_buffer, + depth_bounds: state.depth_bounds, + predication: state.predication, + pred_buf: state.pred_buf.clone(), + pred_in_state: std::mem::replace(&mut state.pred_in_state, false), + active_query, + ended_early: std::mem::take(&mut state.occlusion.ended_early), + written_ranges: state.written_ranges.clone(), + bindings: state.bindings.clone(), + }) + } + + fn continuation_state(&self, ty: D3D12_COMMAND_LIST_TYPE) -> ListState { + ListState { + allocator: self.allocator, + list_type: Some(ty), + last_queue: self.last_queue, + bound_pso: self.bound_pso, + depth_bias: self.depth_bias, + native_bias: DepthBias::ZERO, + pso_dirty: false, + using_fallback_pso: false, + index_buffer: self.index_buffer, + depth_bounds: self.depth_bounds, + occlusion: Occlusion { active: None, ended_early: self.ended_early.clone() }, + written_ranges: self.written_ranges.clone(), + pred_buf: self.pred_buf.clone(), + pred_in_state: false, + predication: self.predication, + bindings: self.bindings.clone(), + ..Default::default() + } + } +} + #[derive(Clone, Copy)] struct QueueInfo { queue: usize, @@ -733,8 +858,6 @@ struct QueueInfo { static LISTS: Mutex>> = Mutex::new(None); static LIVE_QUEUES: Mutex> = Mutex::new(Vec::new()); -/// Number of lists with at least one pending `Wait32/64BitValueX` (fast-path guard for ExecuteCommandLists). -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). @@ -744,6 +867,63 @@ static DEPTH_BIAS_USED: AtomicBool = AtomicBool::new(false); /// Set once any list uses `SetPredicationBufferX` (fast-path guard for Close/Reset hooks). static PREDICATION_USED: AtomicBool = AtomicBool::new(false); +/// Immutable effects recorded by one physical command-list segment at submission planning time. +#[derive(Clone, Default)] +pub(super) struct SegmentEffects { + waits: Vec, + write64_signals: Vec<(u64, u64)>, + sparse_writes: Vec<(usize, usize)>, + cpu_writes: Vec, +} + +/// One queue submission's physical lists and their effects, kept in matching chronological order. +pub(super) struct SubmissionPlan { + lists: Vec<*mut c_void>, + effects: Vec, + has_waits: bool, +} + +impl SubmissionPlan { + fn capture(lists: &[*mut c_void]) -> Self { + if lists.is_empty() { + return Self { lists: Vec::new(), effects: Vec::new(), has_waits: false }; + } + let g = LISTS.lock().unwrap(); + let effects: Vec = lists + .iter() + .map(|&list| { + g.as_ref() + .and_then(|m| m.get(&(list as usize))) + .map(|s| SegmentEffects { + waits: s.pending_waits.clone(), + write64_signals: s.write64_signals.clone(), + sparse_writes: s.sparse_writes.clone(), + cpu_writes: s.cpu_writes.clone(), + }) + .unwrap_or_default() + }) + .collect(); + let has_waits = effects.iter().any(|e| !e.waits.is_empty()); + Self { lists: lists.to_vec(), effects, has_waits } + } +} + +#[derive(Clone, Copy)] +pub(super) struct SubmissionChunk<'a> { + lists: &'a [*mut c_void], + effects: &'a [SegmentEffects], +} + +impl<'a> SubmissionChunk<'a> { + pub(super) fn lists(self) -> &'a [*mut c_void] { + self.lists + } + + pub(super) unsafe fn submit_effects(self, queue: *mut c_void) { + submit_segment_effects(queue, self.effects); + } +} + /// Record a newly created title command queue so `KickoffX` can find a compatible queue. pub fn on_queue_create(queue: usize, device: usize, ty: D3D12_COMMAND_LIST_TYPE) { if queue == 0 { @@ -814,9 +994,6 @@ pub unsafe fn on_create(list: *mut c_void, alloc: usize, pso: usize, ty: D3D12_C let m = g.get_or_insert_with(HashMap::new); let old = m.remove(&key); if let Some(ref old) = old { - if !old.pending_waits.is_empty() { - PENDING_WAIT_LISTS.fetch_sub(1, Ordering::AcqRel); - } if !old.sparse_writes.is_empty() { SPARSE_WRITE_LISTS.fetch_sub(1, Ordering::AcqRel); } @@ -850,9 +1027,6 @@ pub(super) fn on_release(list: usize) { super::title_textures::list_reset(list); let old = LISTS.lock().unwrap().as_mut().and_then(|m| m.remove(&list)); if let Some(old) = old { - if !old.pending_waits.is_empty() { - PENDING_WAIT_LISTS.fetch_sub(1, Ordering::AcqRel); - } if !old.sparse_writes.is_empty() { SPARSE_WRITE_LISTS.fetch_sub(1, Ordering::AcqRel); } @@ -2089,43 +2263,60 @@ pub(super) unsafe fn cpu_writes_after(queue: *mut c_void, lists: &[*mut c_void]) super::cpu_writes::after(queue, writes); } -/// 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. -/// 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); +/// Capture every mutable per-list effect once, before any part of this submission reaches the +/// driver. Resetting or re-recording a list after this point cannot change the returned plan. +pub(super) fn submission_plan(lists: &[*mut c_void]) -> SubmissionPlan { + SubmissionPlan::capture(lists) +} + +/// Publish the effects of an already-submitted chunk in the same order as the legacy consumers. +unsafe fn submit_segment_effects(queue: *mut c_void, effects: &[SegmentEffects]) { + let write64_signals: Vec<(u64, u64)> = effects.iter().flat_map(|e| e.write64_signals.iter().copied()).collect(); + signal_write64_pairs(queue, &write64_signals); + + let sparse_writes: Vec<(usize, usize)> = effects.iter().flat_map(|e| e.sparse_writes.iter().copied()).collect(); + if !sparse_writes.is_empty() { + if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) { + super::sparse::readback_after_execute(q, &sparse_writes); + } + } + + let cpu_writes: Vec = effects.iter().flat_map(|e| e.cpu_writes.iter().cloned()).collect(); + super::cpu_writes::after(queue, cpu_writes); +} + +/// Execute an immutable submission plan, splitting before an unsatisfied memory wait. +pub(super) unsafe fn execute_submission_plan_on(queue: *mut c_void, plan: &SubmissionPlan, mut submit: impl FnMut(SubmissionChunk<'_>)) { + let chunk = |start, end| SubmissionChunk { lists: &plan.lists[start..end], effects: &plan.effects[start..end] }; + if !plan.has_waits { + submit(chunk(0, plan.lists.len())); return; } - 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(), s.write64_signals.clone())) - .unwrap_or_default() - }) - .collect() - }; let mut start = 0usize; - for (i, (waits, list_writes)) in per_list.iter().enumerate() { - if waits.is_empty() || waits.iter().all(|w| w.is_satisfied()) { + for (i, effects) in plan.effects.iter().enumerate() { + if effects.waits.is_empty() || effects.waits.iter().all(|w| w.is_satisfied()) { continue; } if i > start { - submit(&lists[start..i]); + submit(chunk(start, i)); } - wait_all_on(queue, waits, list_writes); + wait_all_on(queue, &effects.waits, &effects.write64_signals); start = i; } - if start < lists.len() { - submit(&lists[start..]); + if start < plan.lists.len() { + submit(chunk(start, plan.lists.len())); } } +/// 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. +/// 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])) { + let plan = submission_plan(lists); + execute_submission_plan_on(queue, &plan, |chunk| submit(chunk.lists())); +} + #[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); @@ -2639,7 +2830,7 @@ unsafe fn try_split_for_wait(list: *mut c_void) -> Option<*mut c_void> { if !*ENABLED.get_or_init(|| std::env::var("XCL_SPLIT_MIDLIST_WAIT").map_or(true, |v| v.trim() != "0")) { return None; } - let next_pc = split(list, None)?; + let next_pc = split_recording(list, SegmentReason::WaitAfterWrite64)?; 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) { @@ -2650,7 +2841,7 @@ unsafe fn try_split_for_wait(list: *mut c_void) -> Option<*mut c_void> { /// Gives a dispatch whose pipeline is still being built a segment of its own, recorded at the submit. pub(super) unsafe fn defer(list: *mut c_void, what: Deferred) -> bool { - if split(list, Some(what)).is_none() { + if split_recording(list, SegmentReason::DeferredDispatch(what)).is_none() { return false; } static N: AtomicU64 = AtomicU64::new(0); @@ -2729,18 +2920,18 @@ unsafe fn reset_own_alloc(list: *mut c_void) { } } -/// Ends `list`'s segment and opens the next; with `dispatch`, a closed segment for it comes between. -unsafe fn split(list: *mut c_void, dispatch: Option) -> Option<*mut c_void> { +/// Ends `list`'s segment and opens the next, carrying its recording state across the boundary. +pub(super) unsafe fn split_recording(list: *mut c_void, reason: SegmentReason) -> Option<*mut c_void> { let wrapper = super::title_list::wrapper_of(list)?; - if !super::title_list::can_split(wrapper, 1 + dispatch.is_some() as usize) { + if !super::title_list::can_split(wrapper, reason.extra_segments()) { return None; } let ty = list_type(list); if ty == D3D12_COMMAND_LIST_TYPE_BUNDLE { return None; } - let deferred = match dispatch { - Some(what) => { + let deferred = match reason { + SegmentReason::DeferredDispatch(what) => { // (a predicated call stays in its list) let plain = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(list as usize))).is_some_and(|s| s.allocator != 0 && s.predication.is_none()); if !plain { @@ -2748,39 +2939,27 @@ unsafe fn split(list: *mut c_void, dispatch: Option) -> Option<*mut c_ } Some((what, deferred_segment(wrapper, list, ty)?)) } - None => None, + SegmentReason::WaitAfterWrite64 => 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 carry = { 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(), - ) + SplitCarry::take(s)? }; - - if let Some(((h, i), qty)) = active_query { + let alloc = carry.allocator; + let bound_pso = carry.bound_pso; + let depth_bias = carry.depth_bias; + let index_buffer = carry.index_buffer; + let depth_bounds = carry.depth_bounds; + let predication = carry.predication; + let pred_buf = &carry.pred_buf; + let bindings = &carry.bindings; + + if let Some(((h, i), qty)) = carry.active_query { pc::(list, PC_END_QUERY)(list, h, qty, i); } - if pred_in_state { - if let Some(ref pb) = pred_buf { + if carry.pred_in_state { + if let Some(pb) = pred_buf { transition(list, pb.as_raw() as usize, D3D12_RESOURCE_STATE_PREDICATION, D3D12_RESOURCE_STATE_COMMON); } } @@ -2837,9 +3016,6 @@ unsafe fn split(list: *mut c_void, dispatch: Option) -> Option<*mut c_ 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); } @@ -2849,32 +3025,14 @@ unsafe fn split(list: *mut c_void, dispatch: Option) -> Option<*mut c_ } 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() - }, + carry.continuation_state(ty), ); 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); + 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 }; @@ -2913,7 +3071,7 @@ unsafe fn split(list: *mut c_void, dispatch: Option) -> Option<*mut c_ } } if ty != D3D12_COMMAND_LIST_TYPE_COPY { - if let (Some(op), Some(ref pb)) = (predication, pred_buf) { + if let (Some(op), Some(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); @@ -3284,12 +3442,7 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { return; }; let active_query = s.occlusion.end_active_early(); - let waits = if s.pending_waits.is_empty() { - Vec::new() - } else { - PENDING_WAIT_LISTS.fetch_sub(1, Ordering::AcqRel); - std::mem::take(&mut s.pending_waits) - }; + let waits = 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(); @@ -4764,7 +4917,7 @@ mod tests { Format: DXGI_FORMAT_R32_UINT, }); s.depth_bounds = Some((0.25, 0.75)); - s.written_ranges.push((0x6000, 0x6010)); + s.written_ranges.insert(0x6000, 0x10); } super::super::bind::seed_reset_state_for_test(list, 0x111, 0x222, vec![0x4444]); RESET_TEST_REPLACEMENT_VT.store(replacement as u64, Ordering::SeqCst); @@ -4782,7 +4935,7 @@ mod tests { assert!(s.pso_dirty && s.using_fallback_pso); assert_eq!(s.index_buffer.as_ref().unwrap().BufferLocation, 0x5000); assert_eq!(s.depth_bounds, Some((0.25, 0.75))); - assert_eq!(s.written_ranges, vec![(0x6000, 0x6010)]); + assert_eq!(s.written_ranges.ranges, BTreeMap::from([(0x6000, 0x6010)])); } assert_eq!( super::super::bind::reset_state_for_test(list), @@ -4947,6 +5100,237 @@ mod tests { assert!(!s.has_prior_write(0x0FF8, 8)); } + #[test] + fn recorded_writes_merge_ascending_ranges() { + let mut writes = RecordedWrites::default(); + writes.insert(0x1000, 8); + writes.insert(0x1008, 8); + writes.insert(0x1010, 8); + assert_eq!(writes.ranges, BTreeMap::from([(0x1000, 0x1018)])); + } + + #[test] + fn recorded_writes_merge_descending_ranges() { + let mut writes = RecordedWrites::default(); + writes.insert(0x1010, 8); + writes.insert(0x1008, 8); + writes.insert(0x1000, 8); + assert_eq!(writes.ranges, BTreeMap::from([(0x1000, 0x1018)])); + } + + #[test] + fn recorded_writes_merge_adjacent_ranges() { + let mut writes = RecordedWrites::default(); + writes.insert(0x1000, 4); + writes.insert(0x1008, 4); + writes.insert(0x1004, 4); + assert_eq!(writes.ranges, BTreeMap::from([(0x1000, 0x100c)])); + } + + #[test] + fn recorded_writes_merge_overlapping_ranges() { + let mut writes = RecordedWrites::default(); + writes.insert(0x1008, 0x10); + writes.insert(0x1000, 0x10); + writes.insert(0x1004, 0x20); + assert_eq!(writes.ranges, BTreeMap::from([(0x1000, 0x1024)])); + } + + #[test] + fn recorded_writes_keep_disjoint_ranges() { + let mut writes = RecordedWrites::default(); + writes.insert(0x1000, 8); + writes.insert(0x1020, 8); + writes.insert(0x1040, 8); + assert_eq!(writes.ranges, BTreeMap::from([(0x1000, 0x1008), (0x1020, 0x1028), (0x1040, 0x1048)])); + } + + #[test] + fn recorded_writes_handle_thousands_in_reverse_order() { + let mut writes = RecordedWrites::default(); + for i in (0..4096u64).rev() { + writes.insert(0x1000 + i * 16, 8); + } + assert_eq!(writes.ranges.len(), 4096); + for i in 0..4096u64 { + let va = 0x1000 + i * 16; + assert!(writes.overlaps(va, 8)); + assert!(!writes.overlaps(va + 8, 8)); + } + } + + #[test] + fn recorded_writes_preserve_gaps_when_bridging_neighbors() { + let mut writes = RecordedWrites::default(); + writes.insert(0x1000, 8); + writes.insert(0x1010, 8); + writes.insert(0x1020, 8); + assert!(!writes.overlaps(0x1008, 8)); + assert!(!writes.overlaps(0x1018, 8)); + + writes.insert(0x1008, 8); + assert!(writes.overlaps(0x1008, 8)); + assert!(!writes.overlaps(0x1018, 8)); + assert_eq!(writes.ranges, BTreeMap::from([(0x1000, 0x1018), (0x1020, 0x1028)])); + } + + #[test] + fn submission_plan_preserves_segment_and_effect_order() { + let lists = [0x7ffe_1001usize as *mut c_void, 0x7ffe_1002usize as *mut c_void, 0x7ffe_1003usize as *mut c_void]; + { + let mut g = LISTS.lock().unwrap(); + let m = g.get_or_insert_with(HashMap::new); + for (i, &list) in lists.iter().enumerate() { + m.insert( + list as usize, + ListState { + write64_signals: vec![(0x1000 + i as u64, 10 + i as u64)], + sparse_writes: vec![(0x2000 + i, 4 + i)], + cpu_writes: vec![super::super::cpu_writes::Write::Immediate(0x3000 + i, vec![i as u32])], + ..Default::default() + }, + ); + } + } + + let plan = SubmissionPlan::capture(&lists); + { + let mut g = LISTS.lock().unwrap(); + let m = g.as_mut().unwrap(); + for &list in &lists { + m.remove(&(list as usize)); + } + } + + assert_eq!(plan.lists, lists); + for (i, effects) in plan.effects.iter().enumerate() { + assert_eq!(effects.write64_signals, vec![(0x1000 + i as u64, 10 + i as u64)]); + assert_eq!(effects.sparse_writes, vec![(0x2000 + i, 4 + i)]); + match effects.cpu_writes.as_slice() { + [super::super::cpu_writes::Write::Immediate(va, words)] => assert_eq!((*va, words.as_slice()), (0x3000 + i, &[i as u32][..])), + _ => panic!("unexpected CPU write snapshot"), + } + } + } + + #[test] + fn submission_plan_is_isolated_from_reset_and_rerecord() { + let list = 0x7ffe_2001usize as *mut c_void; + let old_wait = PendingWait { va: 0x4000, width: 8, comparison: 7, value: 4, mask: u64::MAX, after_write64: true }; + { + let mut g = LISTS.lock().unwrap(); + g.get_or_insert_with(HashMap::new).insert( + list as usize, + ListState { + pending_waits: vec![old_wait], + write64_signals: vec![(0x4000, 4)], + sparse_writes: vec![(0x5000, 8)], + cpu_writes: vec![super::super::cpu_writes::Write::Immediate(0x6000, vec![4])], + ..Default::default() + }, + ); + } + let plan = SubmissionPlan::capture(&[list]); + + { + let mut g = LISTS.lock().unwrap(); + let state = g.as_mut().unwrap().get_mut(&(list as usize)).unwrap(); + state.pending_waits = vec![PendingWait { value: 9, ..old_wait }]; + state.write64_signals = vec![(0x4000, 9)]; + state.sparse_writes = vec![(0x7000, 16)]; + state.cpu_writes = vec![super::super::cpu_writes::Write::Immediate(0x8000, vec![9])]; + } + + let effects = &plan.effects[0]; + assert_eq!(effects.waits, vec![old_wait]); + assert_eq!(effects.write64_signals, vec![(0x4000, 4)]); + assert_eq!(effects.sparse_writes, vec![(0x5000, 8)]); + match effects.cpu_writes.as_slice() { + [super::super::cpu_writes::Write::Immediate(va, words)] => assert_eq!((*va, words.as_slice()), (0x6000, &[4][..])), + _ => panic!("unexpected CPU write snapshot"), + } + LISTS.lock().unwrap().as_mut().unwrap().remove(&(list as usize)); + } + + #[test] + fn empty_submission_plan_uses_the_lock_free_fast_path() { + let lists_guard = LISTS.lock().unwrap(); + let plan = SubmissionPlan::capture(&[]); + drop(lists_guard); + assert!(plan.lists.is_empty() && plan.effects.is_empty() && !plan.has_waits); + + let mut submitted = 0; + unsafe { + execute_submission_plan_on(std::ptr::null_mut(), &plan, |chunk| { + assert!(chunk.lists().is_empty()); + submitted += 1; + }); + } + assert_eq!(submitted, 1); + } + + #[test] + fn segment_reasons_keep_the_existing_segment_costs() { + assert_eq!(SegmentReason::WaitAfterWrite64.extra_segments(), 1); + assert_eq!(SegmentReason::DeferredDispatch(Deferred::Dispatch(1, 2, 3)).extra_segments(), 2); + } + + #[test] + fn split_carry_recreates_the_continuation_state() { + let query = (0x7100, 3); + let earlier_query = (0x7000, 2); + let mut state = ListState { + allocator: 0xa110, + list_type: Some(D3D12_COMMAND_LIST_TYPE_DIRECT), + last_queue: Some(0x9000), + bound_pso: 0xb220, + depth_bias: Some(DepthBias::new(-2.5, 0.25, 4.0)), + native_bias: DepthBias::new(-1.0, 1.0, 1.0), + pso_dirty: true, + using_fallback_pso: true, + index_buffer: Some(D3D12_INDEX_BUFFER_VIEW { BufferLocation: 0xc330, SizeInBytes: 24, Format: DXGI_FORMAT_R32_UINT }), + depth_bounds: Some((0.2, 0.8)), + pred_in_state: true, + predication: Some(D3D12_PREDICATION_OP_NOT_EQUAL_ZERO), + pending_waits: vec![PendingWait { va: 0xd440, width: 8, comparison: 7, value: 5, mask: u64::MAX, after_write64: false }], + write64_signals: vec![(0xe550, 6)], + sparse_writes: vec![(0xf660, 8)], + bindings: Bindings { heaps: vec![0x1010, 0x2020], topology: Some(4), stencil: Some(9), ..Default::default() }, + ..Default::default() + }; + state.written_ranges.insert(0x3000, 0x20); + state.occlusion.ended_early.push(earlier_query); + assert!(state.occlusion.begin(query, D3D12_QUERY_TYPE_OCCLUSION).is_none()); + + let carry = SplitCarry::take(&mut state).unwrap(); + state.bindings.heaps.clear(); + state.written_ranges.clear(); + let continued = carry.continuation_state(D3D12_COMMAND_LIST_TYPE_DIRECT); + + assert_eq!(carry.active_query, Some((query, D3D12_QUERY_TYPE_OCCLUSION))); + assert!(!state.pred_in_state && state.occlusion.active.is_none() && state.occlusion.ended_early.is_empty()); + assert_eq!(continued.allocator, 0xa110); + assert_eq!(continued.last_queue, Some(0x9000)); + assert_eq!(continued.bound_pso, 0xb220); + assert_eq!(continued.depth_bias, Some(DepthBias::new(-2.5, 0.25, 4.0))); + assert_eq!(continued.native_bias, DepthBias::ZERO); + assert!(!continued.pso_dirty && !continued.using_fallback_pso); + assert_eq!(continued.index_buffer.as_ref().unwrap().BufferLocation, 0xc330); + assert_eq!(continued.depth_bounds, Some((0.2, 0.8))); + assert_eq!(continued.predication, Some(D3D12_PREDICATION_OP_NOT_EQUAL_ZERO)); + assert!(!continued.pred_in_state); + assert_eq!(continued.occlusion.ended_early, vec![earlier_query, query]); + assert_eq!(continued.bindings.heaps, vec![0x1010, 0x2020]); + assert_eq!(continued.bindings.topology, Some(4)); + assert_eq!(continued.bindings.stencil, Some(9)); + assert!(continued.written_ranges.overlaps(0x3010, 4)); + assert!(continued.pending_waits.is_empty() && continued.write64_signals.is_empty() && continued.sparse_writes.is_empty()); + assert!(continued.cpu_writes.is_empty() && continued.deferred.is_none() && continued.own_alloc.is_none()); + assert_eq!(state.pending_waits.len(), 1, "effects remain on the closed segment"); + assert_eq!(state.write64_signals, vec![(0xe550, 6)]); + assert_eq!(state.sparse_writes, vec![(0xf660, 8)]); + } + #[test] fn execute_with_waits_splits_batches_before_unsatisfied_list() { // Use synthetic non-zero list pointers distinct from real COM objects. diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 9692cc4c59..3e2d9129e7 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -7407,14 +7407,14 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis } } super::list_x::note_queue_for_lists(this as usize, &mapped); - super::list_x::execute_with_waits_on(this, &mapped, |chunk| { - let _ = super::alloc_pool::note_resubmits(this, chunk); - f(this, chunk.len() as u32, chunk.as_ptr()); - super::list_x::copy_scratch_submitted(this, chunk); - super::alloc_pool::executed(this, chunk); - super::list_x::signal_write64_fences(this, chunk); - super::list_x::readback_sparse_writes(this, chunk); - super::list_x::cpu_writes_after(this, chunk); + let plan = super::list_x::submission_plan(&mapped); + super::list_x::execute_submission_plan_on(this, &plan, |chunk| { + let lists = chunk.lists(); + let _ = super::alloc_pool::note_resubmits(this, lists); + f(this, lists.len() as u32, lists.as_ptr()); + super::list_x::copy_scratch_submitted(this, lists); + super::alloc_pool::executed(this, lists); + chunk.submit_effects(this); }); // the next uploads into textures kept in step start from the states these lists leave super::title_textures::submitted(&mapped); diff --git a/crates/xcl/src/hle/d3d12x/title_list.rs b/crates/xcl/src/hle/d3d12x/title_list.rs index a41e5643fc..10d6ba52f2 100644 --- a/crates/xcl/src/hle/d3d12x/title_list.rs +++ b/crates/xcl/src/hle/d3d12x/title_list.rs @@ -453,6 +453,24 @@ mod tests { this as u64 + a + 10 * b + 100 * c + 1000 * d } + #[test] + fn split_limit_counts_every_physical_extra_segment() { + let wrapper = 0x7ffe_3001usize as *mut c_void; + { + let mut sg = SEGMENTS.lock().unwrap(); + sg.get_or_insert_with(HashMap::new).insert( + wrapper as usize, + SegmentBook { extra_active: (0..MAX_EXTRA_SEGMENTS - 1).map(|i| 0x8000 + i).collect(), ..Default::default() }, + ); + } + assert!(can_split(wrapper, 1)); + assert!(!can_split(wrapper, 2), "a deferred dispatch needs two physical segments"); + push_segment(wrapper, 0x9000usize as *mut c_void); + assert!(!can_split(wrapper, 1)); + assert!(can_split(wrapper, 0)); + SEGMENTS.lock().unwrap().as_mut().unwrap().remove(&(wrapper as usize)); + } + /// The SDK's inline writers check `write < end` (or `write + n <= end`): never room here. #[test] fn console_list_objects_have_no_room_and_forward_to_the_pc_list() {