diff --git a/crates/xcl/src/hle/d3d12x/console_list.rs b/crates/xcl/src/hle/d3d12x/console_list.rs index b623dd876c..9ac93e82e5 100644 --- a/crates/xcl/src/hle/d3d12x/console_list.rs +++ b/crates/xcl/src/hle/d3d12x/console_list.rs @@ -441,6 +441,7 @@ unsafe extern "system" fn cl_release(this: *mut c_void) -> u32 { }) .unwrap_or(0); if left == 0 { + super::title_textures::forget_list_closed(obj); if let Some(st) = LISTS.lock().unwrap().as_mut().and_then(|m| m.remove(&obj)) { free_uma(&st.uma); let release: unsafe extern "system" fn(usize) -> u32 = std::mem::transmute(pc_vtable_call(st.pc, 2)); @@ -481,6 +482,7 @@ unsafe extern "system" fn cl_reset(this: *mut c_void, allocator: *mut c_void, ps }) else { return crate::util::E_FAIL; }; + super::title_textures::forget_list_closed(obj); // what the previous recording left in unified memory lives until its allocator resets if !blocks.is_empty() { PENDING.lock().unwrap().get_or_insert_with(HashMap::new).entry(old_alloc).or_default().extend(blocks); @@ -672,6 +674,15 @@ pub fn pc_list(obj: *mut c_void) -> Option<*mut c_void> { with_list(obj as usize, |st| st.pc as *mut c_void) } +/// Whether `pc` is the internal PC command list behind an active `console_list` wrapper. +pub(super) fn is_backing(pc: *mut c_void) -> bool { + if !enabled() || pc.is_null() { + return false; + } + let p = pc as usize; + LISTS.lock().unwrap().as_ref().is_some_and(|m| m.values().any(|st| st.pc == p)) +} + /// The PC pipeline state behind a console-shaped one (others unchanged). pub fn pc_pso(pso: *mut c_void) -> *mut c_void { if pso.is_null() || unsafe { *(pso as *const usize) } != pso_vtable() { @@ -785,7 +796,6 @@ unsafe fn ensure_dispatch_heaps(list: &ID3D12GraphicsCommandList, bound: &mut Ve /// Turn the recorded console commands into commands on the PC list and close it. pub unsafe fn close(obj: *mut c_void) -> Result { let obj = obj as usize; - super::title_textures::note_list_closed(obj); let mut guard = LISTS.lock().unwrap(); let st = guard.as_mut().and_then(|m| m.get_mut(&obj)).ok_or("not an XCL console list")?; if let Some(last) = st.chunks.last_mut() { @@ -1059,6 +1069,7 @@ pub unsafe fn close(obj: *mut c_void) -> Result { crate::xlog_warn!("console list: unknown record {w:#010x} (word {at}) – rest skipped"); } list.Close().map_err(|e| format!("Close: {e}"))?; + super::title_textures::note_list_closed(obj); Ok(out) } diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index b5e0e98a97..1f421bf3cf 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -3838,7 +3838,8 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { if close_hr < 0 { return warn(&ERR, "KickoffX", format_args!("Close failed ({close_hr:#x})")); } - if let Some(wrapper) = super::title_list::wrapper_of(this) { + let kickoff_wrapper = super::title_list::wrapper_of(this); + if let Some(wrapper) = kickoff_wrapper { record_deferred(wrapper); } super::capture::kickoff(this, queue); @@ -3884,6 +3885,9 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { // what ran is in the textures' states; the list records anew after its Reset below super::title_textures::submitted(&one); super::title_textures::list_reset(this as usize); + if let Some(w) = kickoff_wrapper { + super::title_textures::forget_list_closed(w as usize); + } if !sparse_writes.0.is_empty() || !sparse_writes.1.is_empty() { if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&q_raw) { super::sparse::readback_after_execute(q, &sparse_writes.0, &sparse_writes.1); @@ -4866,6 +4870,14 @@ pub(super) unsafe extern "system" fn dma_close_x(this: *mut c_void) -> i32 { let ext = *(this as *const usize); let hr = pc:: i32>(this, 9)(this); real::preserve_vtable(this, ext); + if hr >= 0 + && !super::title_textures::is_own_work() + && !super::present::presenting() + && super::title_list::wrapper_of(this).is_none() + && !super::console_list::is_backing(this) + { + super::title_textures::note_list_closed(this as usize); + } if hr < 0 { let ty = pc:: i32>(this, PC_GET_TYPE)(this); crate::xlog_warn!("D3D12.X: DMA list Close → {:#x} (PC list type {ty})", hr as u32); diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 4fc883bf4e..6a4c26d9b7 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -3416,6 +3416,14 @@ unsafe extern "system" fn cl_close(this: *mut c_void) -> HRESULT { let f: RefFn = std::mem::transmute(orig_fn(this, pc_slot!("ID3D12GraphicsCommandList", "Close"))); let hr = f(this) as HRESULT; preserve_vtable(this, ext); + if hr >= 0 + && !super::title_textures::is_own_work() + && !super::present::presenting() + && super::title_list::wrapper_of(this).is_none() + && !super::console_list::is_backing(this) + { + super::title_textures::note_list_closed(this as usize); + } if hr < 0 { let ty: RefFn = std::mem::transmute(orig_fn(this, pc_slot!("ID3D12GraphicsCommandList", "GetType"))); crate::xlog_warn!("D3D12.X: command list {this:p} (type {}) Close → {:#x}", ty(this), hr as u32); @@ -3432,6 +3440,9 @@ unsafe extern "system" fn cl_reset(this: *mut c_void, allocator: *mut c_void, in let hr = f(this, allocator, resolved); preserve_vtable(this, ext); if hr >= 0 { + if !super::title_textures::is_own_work() && !super::present::presenting() { + super::title_textures::forget_list_closed(this as usize); + } super::list_x::on_pc_reset(this); super::dred::reset(this); if !initial_state.is_null() { diff --git a/crates/xcl/src/hle/d3d12x/title_list.rs b/crates/xcl/src/hle/d3d12x/title_list.rs index 2eef4403a4..64e3b7aa3b 100644 --- a/crates/xcl/src/hle/d3d12x/title_list.rs +++ b/crates/xcl/src/hle/d3d12x/title_list.rs @@ -135,7 +135,9 @@ unsafe extern "system" fn close(this: *mut c_void) -> HRESULT { let f: unsafe extern "system" fn(*mut c_void) -> HRESULT = std::mem::transmute(pc_slot(pc, 9)); let hr = f(pc); super::capture::list_end(this as usize); - super::title_textures::note_list_closed(this as usize); + if hr >= 0 { + super::title_textures::note_list_closed(this as usize); + } let n = *((this as usize + F_RING_AT) as *const usize); if hr < 0 && n > 0 { let first = n.saturating_sub(RING); @@ -170,6 +172,7 @@ pub(super) unsafe extern "system" fn reset(this: *mut c_void, alloc: usize, pso: f(primary, alloc, pso) }; if hr >= 0 { + super::title_textures::forget_list_closed(this as usize); let active = stand_in.unwrap_or(primary as usize); *((this as usize + F_BACKING) as *mut usize) = active; let moved = { @@ -420,6 +423,7 @@ unsafe extern "system" fn release(this: *mut c_void) -> u32 { let n = f(pc); if n == 0 { super::capture::forget(this as usize); + super::title_textures::forget_list_closed(this as usize); let book = SEGMENTS.lock().unwrap().as_mut().and_then(|m| m.remove(&(this as usize))); { let mut wg = WRAPPER_OF.lock().unwrap(); @@ -740,4 +744,68 @@ mod tests { drop(Box::from_raw(seg1)); } } + + /// End-to-end `title_list` lifecycle for `title_textures::CLOSED`: + /// failed Close does not record, successful Close records the wrapper pointer, failed Reset + /// keeps it, successful Reset clears it, non-final Release keeps it, and final Release clears + /// it before freeing the wrapper address. + #[test] + fn title_list_close_reset_and_release_maintain_closed_tracking() { + #[repr(C)] + struct LifecycleFake { + vt: *const usize, + refs: u32, + close_hr: HRESULT, + reset_hr: HRESULT, + } + unsafe extern "system" fn lf_add_ref(this: *mut c_void) -> u32 { + let f = &mut *(this as *mut LifecycleFake); + f.refs += 1; + f.refs + } + unsafe extern "system" fn lf_release(this: *mut c_void) -> u32 { + let f = &mut *(this as *mut LifecycleFake); + f.refs -= 1; + f.refs + } + unsafe extern "system" fn lf_close(this: *mut c_void) -> HRESULT { + (*(this as *mut LifecycleFake)).close_hr + } + unsafe extern "system" fn lf_reset(this: *mut c_void, _alloc: usize, _pso: usize) -> HRESULT { + (*(this as *mut LifecycleFake)).reset_hr + } + let mut vt = vec![0usize; LIST_SLOTS]; + vt[1] = lf_add_ref as usize; + vt[2] = lf_release as usize; + vt[9] = lf_close as usize; + vt[10] = lf_reset as usize; + let fake = Box::into_raw(Box::new(LifecycleFake { vt: vt.as_ptr(), refs: 1, close_hr: -1, reset_hr: -1 })); + unsafe { + let w = wrap(fake as *mut c_void); + assert!(!super::super::title_textures::is_list_closed_for_test(w as usize)); + // Failed Close must not mark the list closed. + assert_eq!(close(w), -1); + assert!(!super::super::title_textures::is_list_closed_for_test(w as usize)); + // Successful Close marks the wrapper pointer closed. + (*fake).close_hr = 0; + assert_eq!(close(w), 0); + assert!(super::super::title_textures::is_list_closed_for_test(w as usize)); + // Failed Reset leaves the old closed recording intact. + assert_eq!(reset(w, 0, 0), -1); + assert!(super::super::title_textures::is_list_closed_for_test(w as usize)); + // Successful Reset clears CLOSED so the reopened list does not keep a stale timestamp. + (*fake).reset_hr = 0; + assert_eq!(reset(w, 0, 0), 0); + assert!(!super::super::title_textures::is_list_closed_for_test(w as usize)); + // Re-close, AddRef, non-final Release keeps CLOSED; final Release clears it. + assert_eq!(close(w), 0); + assert!(super::super::title_textures::is_list_closed_for_test(w as usize)); + assert_eq!(add_ref(w), 2); + assert_eq!(release(w), 1); + assert!(super::super::title_textures::is_list_closed_for_test(w as usize)); + assert_eq!(release(w), 0); + assert!(!super::super::title_textures::is_list_closed_for_test(w as usize)); + drop(Box::from_raw(fake)); + } + } } diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index fd04827aaf..831a4eb029 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -913,6 +913,7 @@ pub fn note_transitions(list: usize, transitions: &[Transition]) { /// writes go. pub fn list_reset(list: usize) { super::lut3d::list_reset(list); + forget_list_closed(list); { let mut g = LIST_NOTES.lock().unwrap(); if !g.is_empty() { @@ -1067,19 +1068,57 @@ fn now_us() -> u64 { T0.get_or_init(std::time::Instant::now).elapsed().as_micros() as u64 + 1 } -/// when the last look for CPU writes began (`now_us`; 0: none yet) -static LOOK_BEGAN: AtomicU64 = AtomicU64::new(0); +/// `(began_us, frame)` of the last look for CPU writes (`began_us == 0`: none yet; `frame` is +/// `present::activity().0` when the look began so every new frame takes at least one fresh look). +static LAST_LOOK: Mutex<(u64, u64)> = Mutex::new((0, u64::MAX)); /// title list -> when the title closed it (`now_us`) static CLOSED: Mutex>> = Mutex::new(None); +fn last_look() -> (u64, u64) { + *LAST_LOOK.lock().unwrap() +} + +fn advance_look(state: &mut (u64, u64), began: u64, frame: u64) { + if state.0 == 0 || frame > state.1 { + state.0 = began; + state.1 = frame; + } else if frame == state.1 { + state.0 = state.0.max(began); + } +} + +/// Record that a write-watch look began at `began` (`now_us`) during `frame`. +/// Monotonic in `(frame, began)` so an older `XCL_LOOK_AHEAD` round never rewinds a newer frame. +fn note_look_began(began: u64, frame: u64) { + let mut g = LAST_LOOK.lock().unwrap(); + advance_look(&mut g, began, frame); +} + /// The title closed `list` (its own pointer): what the list's GPU work reads was written by now. pub(super) fn note_list_closed(list: usize) { CLOSED.lock().unwrap().get_or_insert_with(Default::default).insert(list, now_us()); } -/// `XCL_LOOK_SKIP=1`: a submit all of whose lists were closed before the last look for CPU writes -/// began goes without a look of its own (that look took what the lists read). Off unless set: -/// a title may write what a closed list reads until it submits the list. +/// Clear any recorded close time for `list` (reset, reopened via `KickoffX`, or released) so a +/// reopened or pointer-reused list never retains a stale `t < LOOK_BEGAN` timestamp. +pub(super) fn forget_list_closed(list: usize) { + let mut g = CLOSED.lock().unwrap(); + if let Some(m) = g.as_mut() { + if !m.is_empty() { + m.remove(&list); + } + } +} + +#[cfg(test)] +pub(super) fn is_list_closed_for_test(list: usize) -> bool { + CLOSED.lock().unwrap().as_ref().is_some_and(|m| m.contains_key(&list)) +} + +/// `XCL_LOOK_SKIP=1`: a submit in the same frame as the last look whose lists were all closed +/// before that look began goes without a look of its own (that look took what the lists read). +/// Every new frame still guarantees at least one fresh look. Off unless set: a title may write +/// what a closed list reads until it submits the list. fn look_skip() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); *ON.get_or_init(|| std::env::var("XCL_LOOK_SKIP").is_ok_and(|v| v.trim() == "1")) @@ -1088,13 +1127,16 @@ fn look_skip() -> bool { /// when the walk last made a block hot (`now_us`): no look before that took the block static WALK_FOUND: AtomicU64 = AtomicU64::new(0); -fn closed_before_last_look(lists: &[*mut c_void]) -> bool { - let began = LOOK_BEGAN.load(Ordering::Acquire); +fn closed_before_last_look_in(lists: &[*mut c_void], began: u64, look_frame: u64, current_frame: u64, walk_found: u64) -> bool { if began == 0 || lists.is_empty() { return false; } + // Every new frame guarantees at least one fresh write-watch look. + if look_frame != current_frame { + return false; + } // (a block the walk found written since: the look that began then did not take it) - if WALK_FOUND.load(Ordering::Acquire) >= began { + if walk_found >= began { return false; } let g = CLOSED.lock().unwrap(); @@ -1102,6 +1144,18 @@ fn closed_before_last_look(lists: &[*mut c_void]) -> bool { lists.iter().all(|&l| m.get(&(l as usize)).is_some_and(|&t| t < began)) } +fn closed_before_last_look(lists: &[*mut c_void]) -> bool { + let (began, look_frame) = last_look(); + let current_frame = super::present::activity().0; + let walk_found = WALK_FOUND.load(Ordering::Acquire); + closed_before_last_look_in(lists, began, look_frame, current_frame, walk_found) +} + +#[inline] +fn should_look(all_closed_before_last_look: bool, skip_enabled: bool, presenting: bool) -> bool { + !(all_closed_before_last_look && skip_enabled) && !presenting +} + /// When the youngest of `lists` was closed (None: one was not seen closing). fn youngest_closed(lists: &[*mut c_void]) -> Option { let g = CLOSED.lock().unwrap(); @@ -1135,7 +1189,7 @@ pub(super) unsafe fn refresh_for(queue: *mut c_void, lists: &[*mut c_void]) { } let t1 = std::time::Instant::now(); // (XCL's copy of the frame to its window reads no memory of the title) - let look = !(old && look_skip()) && !super::present::presenting(); + let look = should_look(old, look_skip(), super::present::presenting()); if look && super::look_stats::on() { CLOSED_AGO.with(|c| c.set(youngest_closed(lists).map(|t| now_us().saturating_sub(t)))); } @@ -1317,7 +1371,9 @@ unsafe fn take_piece(at: usize, len: usize, buf: &mut [*mut c_void], ahead: &Mut /// The written pages of all hot blocks, in pieces (a submit's look waits for one at most). unsafe fn take_round(buf: &mut [*mut c_void]) -> usize { const PIECE: usize = 64 << 20; - // (before the ranges and the blocks are asked for: what is new after that is not in the round) + // (frame before `began`: guarantees `began` is never earlier than `frame`'s start, + // and both precede asking for ranges so memory new after that is not in the round) + let frame = super::present::activity().0; let began = now_us(); let Some((ranges, all)) = last_watch_ranges() else { return 0 }; let mut n = 0; @@ -1329,7 +1385,7 @@ unsafe fn take_round(buf: &mut [*mut c_void]) -> usize { // (memory new since the last look: that one's ranges are made again by the next submit's, and // it does not stand for this round) if all { - LOOK_BEGAN.fetch_max(began, Ordering::AcqRel); + note_look_began(began, frame); } n } @@ -1622,7 +1678,8 @@ unsafe fn refresh_parts(queue: *mut c_void, look: bool) { let mut page = 0x1000u32; let t_ranges = std::time::Instant::now(); LAST_SUBMIT.store(now_us(), Ordering::Relaxed); - // (before the ranges are asked for: memory that is new after that is not in this look) + // (frame before `began`, and both before ranges: memory new after that is not in this look) + let frame = super::present::activity().0; let began = now_us(); let ranges = cached_watch_ranges(u); // (also of a submit without a look: memory that is new is walked from now on) @@ -1652,11 +1709,11 @@ unsafe fn refresh_parts(queue: *mut c_void, look: bool) { if super::look_stats::deep() { // (the walk made a block hot since the look before began: written up to a walk pass // ago, and only this look takes it) - let before = LOOK_BEGAN.load(Ordering::Acquire); + let before = last_look().0; super::look_stats::walk_stale(before != 0 && WALK_FOUND.load(Ordering::Acquire) >= before); super::sparse::note_look(); } - LOOK_BEGAN.fetch_max(began, Ordering::AcqRel); + note_look_began(began, frame); WATCH_BUF.with(|wcell| { let mut buf = wcell.borrow_mut(); if buf.len() < 16384 { @@ -3481,15 +3538,107 @@ pub(super) mod tests { note_list_closed(list as usize); std::thread::sleep(std::time::Duration::from_millis(2)); // (other tests' submits only raise the time of the last look) - LOOK_BEGAN.fetch_max(now_us(), Ordering::AcqRel); - if WALK_FOUND.load(Ordering::Acquire) < LOOK_BEGAN.load(Ordering::Acquire) { + let frame = super::super::present::activity().0; + note_look_began(now_us(), frame); + let (began, _) = last_look(); + if WALK_FOUND.load(Ordering::Acquire) < began { assert!(closed_before_last_look(&[list])); } WALK_FOUND.store(u64::MAX, Ordering::Release); assert!(!closed_before_last_look(&[list]), "the look before did not take the block the walk found"); // (the next submit of the process looks for itself: nothing is lost by this) WALK_FOUND.store(now_us(), Ordering::Release); - CLOSED.lock().unwrap().as_mut().map(|m| m.remove(&(list as usize))); + forget_list_closed(list as usize); + } + + #[test] + fn closed_timestamp_cleared_on_list_reset() { + let list = 0x7E57_2001usize as *mut c_void; + note_list_closed(list as usize); + let began = now_us() + 1000; + assert!(closed_before_last_look_in(&[list], began, 5, 5, 0)); + list_reset(list as usize); + assert!(!is_list_closed_for_test(list as usize), "list_reset must clear CLOSED"); + assert!(!closed_before_last_look_in(&[list], began, 5, 5, 0), "reset list must not keep a stale CLOSED timestamp"); + } + + #[test] + fn closed_timestamp_cleared_on_release_and_pointer_reuse() { + let list = 0x7E57_2002usize as *mut c_void; + note_list_closed(list as usize); + let began = now_us() + 1000; + assert!(closed_before_last_look_in(&[list], began, 7, 7, 0)); + // Release removes CLOSED before deallocation so a newly allocated list at the same + // address does not inherit the old object's pre-look close timestamp. + forget_list_closed(list as usize); + assert!(!is_list_closed_for_test(list as usize)); + assert!(!closed_before_last_look_in(&[list], began, 7, 7, 0), "reused list pointer must not skip before closing"); + } + + #[test] + fn new_frame_forces_look_even_for_pre_closed_list() { + let list = 0x7E57_2003usize as *mut c_void; + note_list_closed(list as usize); + let began = now_us() + 1000; + assert!(closed_before_last_look_in(&[list], began, 10, 10, 0), "same frame skips pre-closed list"); + assert!(!closed_before_last_look_in(&[list], began, 10, 11, 0), "new frame must force at least one fresh look"); + assert!(should_look(closed_before_last_look_in(&[list], began, 10, 11, 0), true, false)); + // `advance_look` advances monotonically across frames and never rewinds on a late round. + let mut st = (0u64, u64::MAX); + advance_look(&mut st, 100, 0); + assert_eq!(st, (100, 0)); + advance_look(&mut st, 200, 0); + assert_eq!(st, (200, 0)); + advance_look(&mut st, 150, 0); + assert_eq!(st, (200, 0)); + advance_look(&mut st, 250, 1); + assert_eq!(st, (250, 1)); + advance_look(&mut st, 300, 0); + assert_eq!(st, (250, 1)); + forget_list_closed(list as usize); + } + + #[test] + fn same_frame_pre_closed_lists_skip_look_when_enabled() { + let l1 = 0x7E57_2004usize as *mut c_void; + let l2 = 0x7E57_2005usize as *mut c_void; + note_list_closed(l1 as usize); + note_list_closed(l2 as usize); + let began = now_us() + 1000; + let old = closed_before_last_look_in(&[l1, l2], began, 12, 12, began - 1); + assert!(old); + assert!(!should_look(old, true, false), "XCL_LOOK_SKIP=1 skips look for same-frame pre-closed lists"); + assert!(should_look(old, false, false), "default off still runs look"); + forget_list_closed(l1 as usize); + forget_list_closed(l2 as usize); + } + + #[test] + fn list_closed_after_look_began_runs_look() { + let l1 = 0x7E57_2006usize as *mut c_void; + let l2 = 0x7E57_2007usize as *mut c_void; + note_list_closed(l1 as usize); + std::thread::sleep(std::time::Duration::from_millis(2)); + let began = now_us(); + std::thread::sleep(std::time::Duration::from_millis(2)); + note_list_closed(l2 as usize); + let old = closed_before_last_look_in(&[l1, l2], began, 15, 15, 0); + assert!(!old, "list closed after LOOK_BEGAN must force a look even in the same frame"); + assert!(should_look(old, true, false)); + forget_list_closed(l1 as usize); + forget_list_closed(l2 as usize); + } + + #[test] + fn walk_found_at_or_after_look_began_runs_look() { + let list = 0x7E57_2008usize as *mut c_void; + note_list_closed(list as usize); + let began = now_us() + 1000; + assert!(closed_before_last_look_in(&[list], began, 20, 20, began - 1)); + assert!(!closed_before_last_look_in(&[list], began, 20, 20, began), "WALK_FOUND == LOOK_BEGAN must run look"); + assert!(!closed_before_last_look_in(&[list], began, 20, 20, began + 1), "WALK_FOUND > LOOK_BEGAN must run look"); + assert!(should_look(closed_before_last_look_in(&[list], began, 20, 20, began), true, false)); + forget_list_closed(list as usize); } /// Pages found ahead of a submit are kept until one takes them, are not reported again, and a