diff --git a/crates/xcl/src/gpu/uma.rs b/crates/xcl/src/gpu/uma.rs index 7592d044b0..800164da54 100644 --- a/crates/xcl/src/gpu/uma.rs +++ b/crates/xcl/src/gpu/uma.rs @@ -744,16 +744,58 @@ pub struct Arena { pub const ARENA_BLOCK: usize = 4 * GRAIN; impl Arena { + /// Bump-allocate `n` bytes at an `align`-aligned address from the active block, if it fits. + pub fn take_bump(&mut self, n: usize, align: usize) -> Option<*mut u8> { + if self.at == 0 { + return None; + } + let align = align.max(16).next_power_of_two(); + let n = n.max(1); + let at = self.at.checked_add(align - 1)? & !(align - 1); + let next = at.checked_add(n)?; + if next <= self.end { + self.at = next; + Some(at as *mut u8) + } else { + None + } + } + + /// Seed the arena with a caller-provided block `(block_ptr, block_len)`, push `block_ptr` + /// onto `blocks`, and allocate the first `align`-aligned `n` bytes from it. + pub fn seed_block( + &mut self, + block_ptr: usize, + block_len: usize, + n: usize, + align: usize, + blocks: &mut Vec, + ) -> Option<*mut u8> { + if block_ptr == 0 { + return None; + } + let align = align.max(16).next_power_of_two(); + let n = n.max(1); + let end = block_ptr.checked_add(block_len)?; + let at = block_ptr.checked_add(align - 1)? & !(align - 1); + let next = at.checked_add(n)?; + if next > end { + return None; + } + blocks.push(block_ptr); + self.at = next; + self.end = end; + Some(at as *mut u8) + } + /// `n` bytes at an `align`-aligned address in committed unified memory (not zeroed), or /// None when committed unified memory is full. pub fn take(&mut self, u: &Uma, n: usize, align: usize, blocks: &mut Vec) -> Option<*mut u8> { + if let Some(p) = self.take_bump(n, align) { + return Some(p); + } let align = align.max(16).next_power_of_two(); let n = n.max(1); - let at = (self.at + align - 1) & !(align - 1); - if self.at != 0 && at + n <= self.end { - self.at = at + n; - return Some(at as *mut u8); - } if n > ARENA_BLOCK / 2 { // a large piece: a block of its own (the current one stays in use) let p = u.alloc(n, align)?; @@ -1188,4 +1230,45 @@ mod tests { assert_eq!(u.window_of(b), Some(1)); assert!(u.free(a) && u.free(b)); } + + #[test] + fn arena_seed_block_bump_allocates_and_tracks_block_once() { + let u = Uma::new(GRAIN).unwrap(); + let base = u.base(); + // Exhaust committed window so `Arena::take` cannot grab from coherent UMA. + while u.alloc(GRAIN, GRAIN).is_some() {} + while u.pool_block().is_some() {} + + let mut arena = Arena::default(); + let mut blocks = Vec::new(); + assert!(arena.take_bump(64, 256).is_none()); + assert!(arena.take(&u, 64, 256, &mut blocks).is_none()); + + // Rejecting oversized, null, or overflowing requests must leave `arena` and `blocks` untouched. + assert!(arena.seed_block(0, ARENA_BLOCK, 64, 256, &mut blocks).is_none()); + let scratch = vec![0u8; ARENA_BLOCK + 512]; + let aligned_ptr = (scratch.as_ptr() as usize + 255) & !255; + let misalign = aligned_ptr + 16; + assert!(arena.seed_block(misalign, 256, 64, 256, &mut blocks).is_none()); + assert!(arena.seed_block(usize::MAX - 32, 64, 16, 16, &mut blocks).is_none()); + assert!(blocks.is_empty()); + assert!(arena.take_bump(16, 16).is_none()); + + // Valid seed pushes `block_ptr` once and services subsequent `take_bump` / `Arena::take` calls. + let first = arena.seed_block(aligned_ptr, ARENA_BLOCK, 32, 256, &mut blocks).unwrap() as usize; + assert_eq!(first, aligned_ptr); + assert_eq!(blocks, vec![aligned_ptr]); + + let second = arena.take_bump(48, 256).unwrap() as usize; + assert_eq!(second, aligned_ptr + 256); + let third = arena.take(&u, 64, 256, &mut blocks).unwrap() as usize; + assert_eq!(third, aligned_ptr + 512); + assert_eq!(blocks, vec![aligned_ptr]); + + // Once the seeded block runs out of room, `Arena::take` fails cleanly rather than spilling. + assert!(arena.take_bump(ARENA_BLOCK, 256).is_none()); + assert!(arena.take(&u, ARENA_BLOCK, 256, &mut blocks).is_none()); + assert!(arena.take(&u, 128, 256, &mut blocks).is_some()); + assert!(base != 0); + } } diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs index e821d60740..4be3d35189 100644 --- a/crates/xcl/src/hle/d3d12x/alloc_pool.rs +++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs @@ -28,6 +28,8 @@ struct Backing { users: HashSet, /// queue → (fence, value after the last submit of one of them) marks: HashMap, + /// whether this PC backing has held recordings or GPU submits since its last Reset + dirty: bool, } impl Backing { @@ -36,6 +38,20 @@ impl Backing { } } +struct OrphanedRetirement { + marks: Vec<(ID3D12Fence, u64)>, + uma: Vec, +} + +const MAX_IDLE_SPARES_PER_ALLOC: usize = 2; + +#[derive(Default)] +struct ReclaimBatch { + uma: Vec, + drop_spares: Vec, + count: usize, +} + #[derive(Default)] struct State { /// title allocator → the PC allocator in use (absent: itself) @@ -47,6 +63,10 @@ struct State { /// title allocator → the type of the lists on it types: HashMap, fences: HashMap, + /// owned spare PC allocators detached from released title allocators while still busy + orphaned_spares: Vec, + /// retired UMA blocks from busy title allocators awaiting GPU fence completion + orphaned_retirements: Vec, made: u64, swaps: u64, /// PC list → its last submit (queue, fence, value after it, recording number then) @@ -81,7 +101,9 @@ fn move_list(s: &mut State, list: usize, backing: usize) { } } } - s.backings.entry(backing).or_default().users.insert(list); + let entry = s.backings.entry(backing).or_default(); + entry.users.insert(list); + entry.dirty = true; } /// The PC list's final Release ended its recording. Submitted work still holds the backing @@ -98,12 +120,24 @@ pub(super) fn forget_list(list: usize) { } } -/// Reset `list` on the title's allocator `alloc`, committing its new recording association -/// only after native Reset succeeds. No pool lock is held across the driver call. -pub fn reset_list(list: usize, alloc: usize, ty: i32, reset: impl FnOnce(usize) -> HRESULT) -> HRESULT { +/// Reset `list` on the title's allocator `alloc`, running `on_ok()` after native Reset succeeds +/// while `list` still holds its previous backing in `users` (preventing concurrent `reclaim_idle` +/// from draining the old backing before UMA blocks are retired), then moving `list` onto `backing`. +/// No pool lock is held across `reset` or `on_ok`. +pub fn reset_list_with_retire( + list: usize, + alloc: usize, + ty: i32, + reset: impl FnOnce(usize) -> HRESULT, + on_ok: impl FnOnce(), +) -> HRESULT { let backing = current(alloc); let hr = reset(backing); - if hr < 0 || !enabled() || alloc == 0 { + if hr < 0 { + return hr; + } + on_ok(); + if !enabled() || alloc == 0 { return hr; } let mut g = STATE.lock().unwrap(); @@ -116,6 +150,12 @@ pub fn reset_list(list: usize, alloc: usize, ty: i32, reset: impl FnOnce(usize) hr } +/// Reset `list` on the title's allocator `alloc`, committing its new recording association +/// only after native Reset succeeds. No pool lock is held across the driver call. +pub fn reset_list(list: usize, alloc: usize, ty: i32, reset: impl FnOnce(usize) -> HRESULT) -> HRESULT { + reset_list_with_retire(list, alloc, ty, reset, || {}) +} + #[cfg(test)] pub(super) use recording_backing as recording_backing_for_test; @@ -211,7 +251,9 @@ pub unsafe fn executed(queue: *mut c_void, lists: &[*mut c_void]) { }; for &l in lists { if let Some(&b) = s.of_list.get(&(l as usize)) { - s.backings.entry(b).or_default().marks.insert(key, (fence.clone(), value)); + let entry = s.backings.entry(b).or_default(); + entry.marks.insert(key, (fence.clone(), value)); + entry.dirty = true; } let recording = s.recordings.get(&(l as usize)).copied().unwrap_or(0); s.last_submit.insert(l as usize, LastSubmit { queue: key, fence: fence.clone(), value, recording }); @@ -219,34 +261,84 @@ pub unsafe fn executed(queue: *mut c_void, lists: &[*mut c_void]) { } /// The title's allocator `alloc` is gone (its last Release): nothing of it stays here – a later -/// allocator may get its address, and must not go on with this one's PC allocators. The ones -/// made here go with it (those lists still record on are left alone: not freed, not tracked). +/// allocator may get its address, and must not go on with this one's PC allocators. Any busy +/// owned spares or retired UMA blocks stay tracked by GPU fences and are reclaimed once idle. pub unsafe fn forget(alloc: usize) { - let made: Vec = { + let (uma_to_free, made): (Vec, Vec) = { let mut g = STATE.lock().unwrap(); let Some(s) = g.as_mut() else { return }; s.types.remove(&alloc); let mut mine: Vec = s.aside.remove(&alloc).unwrap_or_default(); mine.extend(s.cur.remove(&alloc)); mine.push(alloc); + let mut uma_to_free = Vec::new(); let mut made = Vec::new(); + let mut any_busy = false; + let mut busy_marks = Vec::new(); for b in mine { let free = s.backings.get(&b).is_none_or(|x| x.free()); - if let Some(gone) = s.backings.remove(&b) { - for l in gone.users { - s.of_list.remove(&l); + if free { + if let Some(gone) = s.backings.remove(&b) { + for l in gone.users { + s.of_list.remove(&l); + } + } + if b != alloc { + made.push(b); + uma_to_free.extend(super::console_list::take_pending(b)); + } + } else { + any_busy = true; + if let Some(entry) = s.backings.get(&b) { + busy_marks.extend(entry.marks.values().cloned()); + } + if b != alloc { + if !s.orphaned_spares.contains(&b) { + s.orphaned_spares.push(b); + } + } else if let Some(gone) = s.backings.remove(&b) { + for l in gone.users { + s.of_list.remove(&l); + } } } - if b != alloc && free { - made.push(b); + } + let title_uma = super::console_list::take_pending(alloc); + if !title_uma.is_empty() { + if !any_busy { + uma_to_free.extend(title_uma); + } else { + let marks = if !busy_marks.is_empty() { + busy_marks + } else { + s.fences.values().cloned().collect() + }; + s.orphaned_retirements.push(OrphanedRetirement { marks, uma: title_uma }); } } - made + (uma_to_free, made) }; - // (outside the lock: their Release comes back here) + // (outside the lock: their Release and UMA free come back safely) + if !uma_to_free.is_empty() { + super::console_list::free_uma_blocks(&uma_to_free); + } for b in made { drop(ID3D12CommandAllocator::from_raw(b as *mut c_void)); } + maybe_reclaim_idle(); +} + +/// Fence-retire UMA blocks whose owning title allocator is already gone (`allocator == 0`). +pub(super) fn retire_orphan_uma(blocks: Vec) { + if blocks.is_empty() { + return; + } + let mut g = STATE.lock().unwrap(); + let s = g.get_or_insert_with(State::default); + s.orphaned_retirements.push(OrphanedRetirement { + marks: s.fences.values().cloned().collect(), + uma: blocks, + }); } /// The title resets its allocator `alloc`. `None`: reset it as it is (nothing holds a @@ -256,9 +348,13 @@ pub unsafe fn title_reset(alloc: *mut c_void) -> Option { if !enabled() { return None; } - let mut g = STATE.lock().unwrap(); - let s = g.get_or_insert_with(State::default); - title_reset_in(s, alloc, |raw| super::real::reset_pc_allocator(raw)) + let hr = { + let mut g = STATE.lock().unwrap(); + let s = g.get_or_insert_with(State::default); + title_reset_in(s, alloc, |raw| super::real::reset_pc_allocator(raw)) + }; + maybe_reclaim_idle(); + hr } /// The allocator transition, with the PC Reset supplied so failure/retry needs no GPU in tests. @@ -268,6 +364,7 @@ unsafe fn title_reset_in(s: &mut State, alloc: *mut c_void, mut reset: impl FnMu if s.backings.get(&c).is_none_or(|b| b.free()) { if let Some(b) = s.backings.get_mut(&c) { b.marks.clear(); + b.dirty = false; } if c == a { return None; @@ -287,6 +384,7 @@ unsafe fn title_reset_in(s: &mut State, alloc: *mut c_void, mut reset: impl FnMu s.aside.get_mut(&a).unwrap().retain(|&x| x != f); if let Some(b) = s.backings.get_mut(&f) { b.marks.clear(); + b.dirty = false; } f } @@ -318,6 +416,159 @@ unsafe fn title_reset_in(s: &mut State, alloc: *mut c_void, mut reset: impl FnMu Some(0) } +unsafe fn reclaim_idle_in( + s: &mut State, + mut reset: R, + mut take_uma: TU, +) -> ReclaimBatch +where + R: FnMut(*mut c_void) -> HRESULT, + TU: FnMut(usize) -> Vec, +{ + let mut batch = ReclaimBatch::default(); + + let aside_keys: Vec = s.aside.keys().copied().collect(); + for title_alloc in aside_keys { + let cur_free = s.cur.get(&title_alloc).is_none_or(|c| s.backings.get(c).is_none_or(|b| b.free())); + let Some(mut spares) = s.aside.remove(&title_alloc) else { + continue; + }; + let all_backings_free = cur_free && spares.iter().all(|f| s.backings.get(f).is_none_or(|b| b.free())); + for &f in &spares { + if !s.backings.get(&f).is_some_and(|b| b.dirty && b.free()) { + continue; + } + if f == title_alloc { + // Title owns `title_alloc`'s COM lifetime (`Release` runs before `forget`), and + // `PENDING[title_alloc]` stays keyed by the title allocator on this tree: only flush + // when every backing of `title_alloc` is idle, without dereferencing `title_alloc` off-thread. + if all_backings_free { + if let Some(b) = s.backings.get_mut(&f) { + b.marks.clear(); + b.dirty = false; + } + let u = take_uma(f); + if !u.is_empty() { + batch.uma.extend(u); + batch.count += 1; + } + } + } else if reset(f as *mut c_void) >= 0 { + if let Some(b) = s.backings.get_mut(&f) { + b.marks.clear(); + b.dirty = false; + } + batch.uma.extend(take_uma(f)); + batch.count += 1; + } + } + let mut clean_free_owned = spares + .iter() + .filter(|&&f| f != title_alloc && s.backings.get(&f).is_none_or(|b| !b.dirty && b.free())) + .count(); + while clean_free_owned > MAX_IDLE_SPARES_PER_ALLOC { + let Some(pos) = spares + .iter() + .position(|&f| f != title_alloc && s.backings.get(&f).is_none_or(|b| !b.dirty && b.free())) + else { + break; + }; + let f = spares.remove(pos); + if let Some(gone) = s.backings.remove(&f) { + for l in gone.users { + s.of_list.remove(&l); + } + } + batch.uma.extend(take_uma(f)); + batch.drop_spares.push(f); + batch.count += 1; + clean_free_owned -= 1; + } + if !spares.is_empty() { + s.aside.insert(title_alloc, spares); + } + } + + let orphaned = std::mem::take(&mut s.orphaned_spares); + for b in orphaned { + if s.backings.get(&b).is_none_or(|x| x.free()) { + if let Some(gone) = s.backings.remove(&b) { + for l in gone.users { + s.of_list.remove(&l); + } + } + batch.uma.extend(take_uma(b)); + batch.drop_spares.push(b); + batch.count += 1; + } else { + s.orphaned_spares.push(b); + } + } + + let retirements = std::mem::take(&mut s.orphaned_retirements); + for r in retirements { + if r.marks.iter().all(|(f, v)| f.GetCompletedValue() >= *v) { + batch.uma.extend(r.uma); + batch.count += 1; + } else { + s.orphaned_retirements.push(r); + } + } + + batch +} + +/// Proactively reset idle put-aside PC allocators, trim excess spares, and flush completed +/// orphaned retirements so command allocator memory and held UMA blocks return promptly. +pub(super) fn reclaim_idle() -> usize { + if !enabled() { + return 0; + } + let batch = { + let mut g = STATE.lock().unwrap(); + let Some(s) = g.as_mut() else { + return 0; + }; + unsafe { + reclaim_idle_in( + s, + |raw| { + if super::real::is_adopted(raw) { + super::real::reset_pc_allocator(raw) + } else { + crate::util::E_FAIL + } + }, + super::console_list::take_pending, + ) + } + }; + let count = batch.count; + if !batch.uma.is_empty() { + unsafe { super::console_list::free_uma_blocks(&batch.uma) }; + } + for b in batch.drop_spares { + unsafe { drop(ID3D12CommandAllocator::from_raw(b as *mut c_void)) }; + } + count +} + +const RECLAIM_PERIOD: std::time::Duration = std::time::Duration::from_millis(500); + +fn maybe_reclaim_idle() { + static LAST: Mutex> = Mutex::new(None); + let Ok(mut last) = LAST.try_lock() else { + return; + }; + let now = std::time::Instant::now(); + if last.is_some_and(|t| now.saturating_duration_since(t) < RECLAIM_PERIOD) { + return; + } + *last = Some(now); + drop(last); + let _ = reclaim_idle(); +} + #[cfg(test)] mod tests { use super::*; @@ -541,4 +792,313 @@ mod tests { assert_eq!(after_forget, 0, "a forgotten list has no previous submit"); } } + + #[test] + fn reclaim_idle_resets_dirty_free_aside_backings_and_trims_excess_spares() { + let mut ids = Box::new([0u8; 8]); + let base = ids.as_mut_ptr() as usize; + let (title, spare_busy, spare_dirty_free, spare_clean_1, spare_clean_2, list) = + (base, base + 1, base + 2, base + 3, base + 4, base + 5); + + let mut s = State::default(); + s.types.insert(title, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + // `spare_busy` holds a live recording so it cannot be reset or trimmed yet. + move_list(&mut s, list, spare_busy); + s.backings.insert(title, Backing { dirty: true, ..Default::default() }); + s.backings.insert(spare_dirty_free, Backing { dirty: true, ..Default::default() }); + // Two additional clean free spares push clean free owned spares to 3 (> MAX_IDLE_SPARES_PER_ALLOC = 2). + s.backings.insert(spare_clean_1, Backing { dirty: false, ..Default::default() }); + s.backings.insert(spare_clean_2, Backing { dirty: false, ..Default::default() }); + s.aside.insert(title, vec![title, spare_busy, spare_dirty_free, spare_clean_1, spare_clean_2]); + + let mut resets = Vec::new(); + let mut uma_taken = Vec::new(); + let batch = unsafe { + reclaim_idle_in( + &mut s, + |raw| { + resets.push(raw as usize); + 0 + }, + |b| { + uma_taken.push(b); + vec![b + 0x1000] + }, + ) + }; + + assert_eq!( + resets, + vec![spare_dirty_free], + "only dirty free owned spares are natively reset; title-owned allocator is never dereferenced on background reclaim" + ); + assert!( + s.backings[&title].dirty, + "title backing keeps pending UMA while spare_busy is still active" + ); + assert!(s.backings[&spare_busy].dirty, "busy spare stays dirty and aside"); + assert!(!s.backings.contains_key(&spare_dirty_free), "oldest excess clean owned spare is removed"); + assert_eq!(batch.drop_spares, vec![spare_dirty_free], "excess owned spare above limit is queued for drop"); + assert!(!batch.drop_spares.contains(&title), "title's own allocator is never dropped by trim"); + assert_eq!(s.aside.get(&title), Some(&vec![title, spare_busy, spare_clean_1, spare_clean_2])); + assert_eq!(uma_taken, vec![spare_dirty_free, spare_dirty_free]); + assert_eq!(batch.uma, vec![spare_dirty_free + 0x1000, spare_dirty_free + 0x1000]); + assert_eq!(batch.count, 2); + + // Once `spare_busy` finishes, all backings of `title` are free -> `title` and `spare_busy` flush cleanly. + s.of_list.remove(&list); + s.backings.get_mut(&spare_busy).unwrap().users.remove(&list); + uma_taken.clear(); + let batch2 = unsafe { + reclaim_idle_in( + &mut s, + |raw| { + resets.push(raw as usize); + 0 + }, + |b| { + uma_taken.push(b); + vec![b + 0x2000] + }, + ) + }; + assert!(!s.backings[&title].dirty, "title backing flushes once all backings are idle"); + assert!(!s.backings.contains_key(&spare_busy), "newly free excess spare is trimmed"); + assert_eq!(uma_taken, vec![title, spare_busy, spare_busy]); + assert_eq!(batch2.drop_spares, vec![spare_busy]); + assert_eq!(batch2.count, 3); + drop(ids); + } + + #[test] + fn forget_retires_busy_owned_spares_and_title_alloc_pending_after_gpu_fence() { + use std::cell::Cell; + use std::mem::{offset_of, size_of}; + + #[repr(C)] + struct FakeFence { + vtable: *const usize, + value: Cell, + refs: Cell, + } + unsafe extern "system" fn fence_add_ref(this: *mut c_void) -> u32 { + let f = &*this.cast::(); + let next = f.refs.get() + 1; + f.refs.set(next); + next + } + unsafe extern "system" fn fence_completed(this: *mut c_void) -> u64 { + (*this.cast::()).value.get() + } + unsafe extern "system" fn fence_release(this: *mut c_void) -> u32 { + let f = &*this.cast::(); + let next = f.refs.get().saturating_sub(1); + f.refs.set(next); + next + } + extern "system" fn unexpected_call() { + std::process::abort(); + } + #[repr(C)] + struct FakeAlloc { + vtable: *const usize, + releases: Cell, + } + unsafe extern "system" fn alloc_fake_release(this: *mut c_void) -> u32 { + let a = &*this.cast::(); + a.releases.set(a.releases.get() + 1); + 0 + } + + const SLOT: usize = size_of::(); + let mut fence_vtable = [unexpected_call as usize; size_of::() / SLOT]; + fence_vtable[1] = fence_add_ref as usize; + fence_vtable[offset_of!(ID3D12Fence_Vtbl, GetCompletedValue) / SLOT] = fence_completed as usize; + fence_vtable[offset_of!(ID3D12Fence_Vtbl, base__.base__.base__.base__.Release) / SLOT] = fence_release as usize; + let alloc_vtable = [0usize, 0usize, alloc_fake_release as usize]; + + let mut fence_title = Box::new(FakeFence { vtable: fence_vtable.as_ptr(), value: Cell::new(0), refs: Cell::new(1) }); + let mut fence_spare = Box::new(FakeFence { vtable: fence_vtable.as_ptr(), value: Cell::new(0), refs: Cell::new(1) }); + let mut fake_spare = Box::new(FakeAlloc { vtable: alloc_vtable.as_ptr(), releases: Cell::new(0) }); + let mut ids = Box::new([0u8; 4]); + let title = ids.as_mut_ptr() as usize; + let list = title + 1; + let spare_busy = std::ptr::from_mut(&mut *fake_spare) as usize; + + { + let mut g = STATE.lock().unwrap(); + let st = g.get_or_insert_with(State::default); + st.cur.insert(title, title); + st.aside.insert(title, vec![spare_busy]); + let mut b_title = Backing { dirty: true, ..Default::default() }; + let ft = unsafe { ID3D12Fence::from_raw(std::ptr::from_mut(&mut *fence_title).cast()) }; + b_title.marks.insert(1, (ft, 5)); + st.backings.insert(title, b_title); + + move_list(st, list, spare_busy); + let fs = unsafe { ID3D12Fence::from_raw(std::ptr::from_mut(&mut *fence_spare).cast()) }; + st.backings.get_mut(&spare_busy).unwrap().marks.insert(2, (fs, 9)); + } + + super::super::console_list::hold_until_reset(title, vec![0x7E57_1000]); + super::super::console_list::hold_until_reset(spare_busy, vec![0x7E57_2000]); + + unsafe { forget(title) }; + assert_eq!(fake_spare.releases.get(), 0, "busy owned spare must not be COM-released early"); + assert_eq!(super::super::console_list::pending_len_for_test(title), 0, "busy title UMA captured into orphaned_retirements"); + assert_eq!(super::super::console_list::pending_len_for_test(spare_busy), 1, "busy spare UMA remains under spare_busy until free"); + + // While GPU fences are unsatisfied, reclaim_idle_in holds both intact. + let batch_busy = { + let mut g = STATE.lock().unwrap(); + let st = g.as_mut().unwrap(); + assert!(!st.backings.contains_key(&title), "title removed from backings to prevent ABA aliasing"); + assert!(st.orphaned_spares.contains(&spare_busy)); + assert_eq!(st.orphaned_retirements.len(), 1); + unsafe { reclaim_idle_in(st, |_| 0, super::super::console_list::take_pending) } + }; + assert_eq!(batch_busy.count, 0); + + // Complete fences and finish list -> both retire cleanly. + fence_title.value.set(5); + forget_list(list); + fence_spare.value.set(9); + let batch_done = { + let mut g = STATE.lock().unwrap(); + let st = g.as_mut().unwrap(); + unsafe { reclaim_idle_in(st, |_| 0, super::super::console_list::take_pending) } + }; + assert_eq!(batch_done.count, 2); + assert_eq!(batch_done.uma, vec![0x7E57_2000, 0x7E57_1000]); + assert_eq!(batch_done.drop_spares, vec![spare_busy]); + assert_eq!(fence_title.refs.get(), 0); + assert_eq!(fence_spare.refs.get(), 0); + for b in batch_done.drop_spares { + unsafe { drop(ID3D12CommandAllocator::from_raw(b as *mut c_void)) }; + } + assert_eq!(fake_spare.releases.get(), 1); + drop(ids); + } + + #[test] + fn forget_busy_title_alloc_without_marks_and_reset_retire_ordering() { + use std::cell::Cell; + use std::mem::{offset_of, size_of}; + + #[repr(C)] + struct FakeFence { + vtable: *const usize, + value: Cell, + refs: Cell, + } + unsafe extern "system" fn fence_add_ref(this: *mut c_void) -> u32 { + let f = &*this.cast::(); + let next = f.refs.get() + 1; + f.refs.set(next); + next + } + unsafe extern "system" fn fence_completed(this: *mut c_void) -> u64 { + (*this.cast::()).value.get() + } + unsafe extern "system" fn fence_release(this: *mut c_void) -> u32 { + let f = &*this.cast::(); + let next = f.refs.get().saturating_sub(1); + f.refs.set(next); + next + } + extern "system" fn unexpected_call() { + std::process::abort(); + } + const SLOT: usize = size_of::(); + let mut fence_vtable = [unexpected_call as usize; size_of::() / SLOT]; + fence_vtable[1] = fence_add_ref as usize; + fence_vtable[offset_of!(ID3D12Fence_Vtbl, GetCompletedValue) / SLOT] = fence_completed as usize; + fence_vtable[offset_of!(ID3D12Fence_Vtbl, base__.base__.base__.base__.Release) / SLOT] = fence_release as usize; + + let mut fake_fence = Box::new(FakeFence { vtable: fence_vtable.as_ptr(), value: Cell::new(0), refs: Cell::new(1) }); + let mut ids = Box::new([0u8; 8]); + let base = ids.as_mut_ptr() as usize; + let (title_a, list_a, queue_key, title_b, spare_b, list_b) = (base, base + 1, base + 2, base + 3, base + 4, base + 5); + + // Part 1: busy title_a via live `list_a` ONLY (marks empty) captures PENDING[title_a] into orphaned_retirements. + { + let mut g = STATE.lock().unwrap(); + let st = g.get_or_insert_with(State::default); + let f = unsafe { ID3D12Fence::from_raw(std::ptr::from_mut(&mut *fake_fence).cast()) }; + st.fences.insert(queue_key, (f, 5)); + move_list(st, list_a, title_a); + } + super::super::console_list::hold_until_reset(title_a, vec![0x7E57_3000]); + + unsafe { forget(title_a) }; + assert_eq!(fake_fence.refs.get(), 2, "orphaned retirement cloned the queue fence ref"); + assert_eq!(super::super::console_list::pending_len_for_test(title_a), 0, "busy title UMA decoupled from dead address"); + let busy = { + let mut g = STATE.lock().unwrap(); + let st = g.as_mut().unwrap(); + st.fences.remove(&queue_key); + unsafe { reclaim_idle_in(st, |_| 0, super::super::console_list::take_pending) } + }; + assert_eq!(busy.count, 0, "unsignaled queue fence must hold orphaned retirement"); + assert_eq!(fake_fence.refs.get(), 1); + fake_fence.value.set(5); + let done = { + let mut g = STATE.lock().unwrap(); + let st = g.as_mut().unwrap(); + unsafe { reclaim_idle_in(st, |_| 0, super::super::console_list::take_pending) } + }; + assert_eq!(done.count, 1); + assert_eq!(done.uma, vec![0x7E57_3000]); + assert_eq!(fake_fence.refs.get(), 0); + + // Part 2: reset_list_with_retire runs `on_ok` while `list_b` still holds `title_b` in users. + { + let mut g = STATE.lock().unwrap(); + let st = g.get_or_insert_with(State::default); + st.types.insert(title_b, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + st.aside.insert(title_b, vec![title_b]); + st.cur.insert(title_b, spare_b); + move_list(st, list_b, title_b); + } + let mut mid_reclaim_count = usize::MAX; + let hr = reset_list_with_retire( + list_b, + title_b, + D3D12_COMMAND_LIST_TYPE_DIRECT.0, + |_| 0, + || { + // `list_b` still holds `title_b` while `on_ok` retires `0x7E57_4000` onto `title_b`. + super::super::console_list::hold_until_reset(title_b, vec![0x7E57_4000]); + let mut g = STATE.lock().unwrap(); + let st = g.as_mut().unwrap(); + let mid = unsafe { reclaim_idle_in(st, |_| 0, super::super::console_list::take_pending) }; + mid_reclaim_count = mid.count; + }, + ); + assert_eq!((hr, mid_reclaim_count), (0, 0), "concurrent reclaim must not fire while on_ok retires UMA onto old backing"); + + // While `list_b` still records on `spare_b`, `PENDING[title_b]` stays deferred until every backing is idle. + let while_recording = { + let mut g = STATE.lock().unwrap(); + let st = g.as_mut().unwrap(); + unsafe { reclaim_idle_in(st, |_| 0, super::super::console_list::take_pending) } + }; + assert_eq!(while_recording.count, 0, "busy cur spare must defer title_b pending UMA flush"); + + forget_list(list_b); + let after = { + let mut g = STATE.lock().unwrap(); + let st = g.as_mut().unwrap(); + let after = unsafe { reclaim_idle_in(st, |_| 0, super::super::console_list::take_pending) }; + st.backings.clear(); + st.of_list.clear(); + st.cur.clear(); + st.aside.clear(); + st.types.clear(); + after + }; + assert_eq!(after.uma, vec![0x7E57_4000]); + assert_eq!(after.count, 1); + drop(ids); + } } diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index fad934addc..3d95ec0015 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -69,6 +69,17 @@ fn with(list: *mut c_void, f: impl FnOnce(&mut State) -> R) -> R { f(STATES.lock().unwrap().get_or_insert_with(HashMap::new).entry(list as usize).or_default()) } +fn retire_uma_blocks(allocator: usize, blocks: Vec) { + if blocks.is_empty() { + return; + } + if allocator == 0 { + super::alloc_pool::retire_orphan_uma(blocks); + } else { + console_list::hold_until_reset(allocator, blocks); + } +} + /// The list was created or reset onto `allocator` with `initial_pso`: the previous /// recording's memory is the previous allocator's until that one is reset, and pipeline /// and root signature state reset per D3D12 `CreateCommandList` / `Reset` semantics. @@ -84,7 +95,7 @@ pub(super) fn reset(list: *mut c_void, allocator: usize, initial_pso: usize) { s.rs_gfx = 0; (old, std::mem::take(&mut s.uma)) }); - console_list::hold_until_reset(old, blocks); + retire_uma_blocks(old, blocks); } /// `ClearState(pso)`: resets pipeline and root-argument state back to creation defaults @@ -118,13 +129,26 @@ pub(super) fn inherit_for_split(from: *mut c_void, to: *mut c_void, allocator: u s.pso = pso; (old, std::mem::take(&mut s.uma)) }); - console_list::hold_until_reset(old, blocks); + retire_uma_blocks(old, blocks); +} + +/// Clear references to a released title allocator so future UMA retirements route through +/// fence-gated orphan cleanup instead of re-keying under a dead pointer. +pub(super) fn on_title_allocator_release(dead_alloc: usize) { + if let Some(m) = STATES.lock().unwrap().as_mut() { + for s in m.values_mut() { + if s.allocator == dead_alloc { + s.allocator = 0; + } + } + } } /// 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))) { - console_list::hold_until_reset(s.allocator, s.uma); + let state = STATES.lock().unwrap().as_mut().and_then(|m| m.remove(&(list as usize))); + if let Some(s) = state { + retire_uma_blocks(s.allocator, s.uma); } } @@ -947,33 +971,103 @@ unsafe fn trace_fullscreen(this: *mut c_void, pso: usize, groups: [u32; 3]) { crate::xlog_info!("frame trace: … its indices name: {}", if res.is_empty() { "nothing".to_string() } else { res.join("; ") }); } -/// #148 AllocateUploadMemory(size, alignment) → CPU/GPU pointer in unified memory (used by -/// `XboxBvhBuilder.dll` and other console middleware on default title command lists). -/// Freed automatically when the list's command allocator is reset. -pub(super) unsafe extern "system" fn allocate_upload_memory(this: *mut c_void, size: usize, align: usize) -> *mut u8 { - let Some(u) = crate::gpu::uma::get() else { - return std::ptr::null_mut(); +const RECLAIM_COOLDOWN: std::time::Duration = std::time::Duration::from_millis(50); + +/// Opportunistically reclaim idle put-aside PC allocators at most once per cooldown window +/// when coherent UMA fills up, keeping concurrent recording threads lock-free on the cooldown. +fn maybe_reclaim_alloc_pool() -> usize { + static LAST_RECLAIM: Mutex> = Mutex::new(None); + let Ok(mut last) = LAST_RECLAIM.try_lock() else { + return 0; }; - let size = size.max(16); - let align = align.max(16); - if size <= crate::gpu::uma::ARENA_BLOCK / 2 { - if let Some(p) = with(this, |s| s.arena.take(u, size, align, &mut s.uma)) { - return p; + let now = std::time::Instant::now(); + if last.is_some_and(|t| now.saturating_duration_since(t) < RECLAIM_COOLDOWN) { + return 0; + } + *last = Some(now); + drop(last); + super::alloc_pool::reclaim_idle() +} + +unsafe fn alloc_recording_uma_with( + this: *mut c_void, + size: usize, + align: usize, + has_sparse: bool, + mut try_coherent_small: impl FnMut(&mut State, usize, usize) -> Option<*mut u8>, + mut try_reclaim: impl FnMut() -> usize, + mut try_sparse_alloc: impl FnMut(usize, usize) -> Option<(usize, usize)>, + mut free_sparse: impl FnMut(usize) -> bool, + mut try_coherent_large: impl FnMut(usize, usize) -> Option<*mut u8>, +) -> Option<*mut u8> { + let sz = size.max(16); + let al = align.max(16).next_power_of_two(); + if sz <= crate::gpu::uma::ARENA_BLOCK / 2 { + if let Some(p) = with(this, |s| try_coherent_small(s, sz, al)) { + return Some(p); } + if try_reclaim() > 0 { + if let Some(p) = with(this, |s| try_coherent_small(s, sz, al)) { + return Some(p); + } + } + if has_sparse { + if let Some((ptr, rounded)) = try_sparse_alloc(crate::gpu::uma::ARENA_BLOCK, crate::gpu::uma::GRAIN) { + let (res, unused) = with(this, |s| { + if let Some(p) = s.arena.take_bump(sz, al) { + (Some(p), Some(ptr)) + } else { + let p = s.arena.seed_block(ptr, rounded, sz, al, &mut s.uma); + (p, p.is_none().then_some(ptr)) + } + }); + if let Some(extra) = unused { + free_sparse(extra); + } + return res; + } + } + return None; } - if u.has_sparse() { - if let Some((p, _)) = super::sparse::alloc(size, align) { - with(this, |s| s.uma.push(p)); - return p as *mut u8; + if has_sparse { + if let Some((ptr, _)) = try_sparse_alloc(sz, al) { + with(this, |s| s.uma.push(ptr)); + return Some(ptr as *mut u8); } } - match u.alloc(size, align) { - Some(p) => { + if let Some(p) = try_coherent_large(sz, al) { + with(this, |s| s.uma.push(p as usize)); + return Some(p); + } + if try_reclaim() > 0 { + if let Some(p) = try_coherent_large(sz, al) { with(this, |s| s.uma.push(p as usize)); - p + return Some(p); } - None => std::ptr::null_mut(), } + None +} + +unsafe fn alloc_recording_uma(this: *mut c_void, size: usize, align: usize) -> Option<*mut u8> { + let u = crate::gpu::uma::get()?; + alloc_recording_uma_with( + this, + size, + align, + u.has_sparse(), + |s, sz, al| s.arena.take(u, sz, al, &mut s.uma), + maybe_reclaim_alloc_pool, + |sz, al| super::sparse::alloc(sz, al), + |ptr| super::sparse::free(ptr), + |sz, al| u.alloc(sz, al), + ) +} + +/// #148 AllocateUploadMemory(size, alignment) → CPU/GPU pointer in unified memory (used by +/// `XboxBvhBuilder.dll` and other console middleware on default title command lists). +/// Freed automatically when the list's command allocator is reset. +pub(super) unsafe extern "system" fn allocate_upload_memory(this: *mut c_void, size: usize, align: usize) -> *mut u8 { + alloc_recording_uma(this, size, align).unwrap_or(std::ptr::null_mut()) } unsafe fn translated_dispatch(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usize, x: u32, y: u32, z: u32) -> Result<(), String> { @@ -995,8 +1089,10 @@ unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usi let (layout, args) = with(this, |s| if gfx { (s.layout_gfx.clone(), s.args_gfx.clone()) } else { (s.layout.clone(), s.args.clone()) }); // 32-bit console addresses: window 0; pieces of the list's arena (not a 64 KiB grain each) let copy = |bytes: &[u8]| -> Result { - let p = with(this, |s| s.arena.take(u, bytes.len().max(16), 256, &mut s.uma)).ok_or("unified memory is full")?; - std::ptr::copy_nonoverlapping(bytes.as_ptr(), p, bytes.len()); + let p = alloc_recording_uma(this, bytes.len().max(16), 256).ok_or("unified memory is full")?; + if !bytes.is_empty() { + std::ptr::copy_nonoverlapping(bytes.as_ptr(), p, bytes.len()); + } Ok(p as usize) }; // a pipeline still being built in the background is waited for @@ -1671,4 +1767,230 @@ void main(uint t : SV_GroupIndex) { let _ = pso_async::released(standin); } } + + #[test] + fn alloc_recording_uma_falls_back_to_sparse_arena_block_without_per_copy_churn() { + let mut backing = vec![0u8; crate::gpu::uma::ARENA_BLOCK * 3]; + let base_ptr = (backing.as_mut_ptr() as usize + 255) & !255; + let spare_ptr = base_ptr + crate::gpu::uma::ARENA_BLOCK; + let large_ptr = spare_ptr + crate::gpu::uma::ARENA_BLOCK; + + let mut ids = Box::new([0u8; 4]); + let list = ids.as_mut_ptr() as *mut c_void; + let alloc = ids.as_mut_ptr() as usize + 1; + reset(list, alloc, 0); + + unsafe { + // 1. Reclaim retry path: coherent miss triggers reclaim, then coherent succeeds without sparse fallback. + let reclaim_calls = std::cell::Cell::new(0usize); + let mut sparse_calls = 0usize; + let mut freed = Vec::new(); + let p_reclaim = alloc_recording_uma_with( + list, + 64, + 256, + true, + |_, _, _| if reclaim_calls.get() > 0 { Some(spare_ptr as *mut u8) } else { None }, + || { + reclaim_calls.set(reclaim_calls.get() + 1); + 1 + }, + |_, _| { + sparse_calls += 1; + None + }, + |ptr| { + freed.push(ptr); + true + }, + |_, _| None, + ); + assert_eq!(p_reclaim.map(|p| p as usize), Some(spare_ptr)); + assert_eq!((reclaim_calls.get(), sparse_calls), (1, 0)); + assert!(freed.is_empty()); + + // 2. Sparse Arena seed: 100 consecutive small copies allocate ONE sparse Arena block and bump-carve it. + let mut sparse_allocs = 0usize; + let mut addrs = Vec::new(); + for _ in 0..100 { + let p = alloc_recording_uma_with( + list, + 256, + 256, + true, + |s, sz, al| s.arena.take_bump(sz, al), + || 0, + |sz, al| { + sparse_allocs += 1; + assert_eq!(sz, crate::gpu::uma::ARENA_BLOCK); + assert_eq!(al, crate::gpu::uma::GRAIN); + Some((base_ptr, sz)) + }, + |ptr| { + freed.push(ptr); + true + }, + |_, _| None, + ) + .unwrap() as usize; + addrs.push(p); + } + assert_eq!(sparse_allocs, 1, "100 small copies must share one seeded sparse Arena block"); + assert_eq!(addrs[0], base_ptr); + assert_eq!(addrs[99], base_ptr + 99 * 256); + assert_eq!(with(list, |s| s.uma.len()), 1, "block list must hold only the single seeded block"); + assert!(freed.is_empty()); + + // 3. Double-seed race: if `take_bump` succeeds inside `STATES`, redundant sparse block is freed outside `STATES`. + let race_p = alloc_recording_uma_with( + list, + 256, + 256, + true, + |_, _, _| None, + || 0, + |sz, _| Some((spare_ptr, sz)), + |ptr| { + assert!(STATES.try_lock().is_ok(), "free_sparse must run outside bind::STATES lock"); + freed.push(ptr); + true + }, + |_, _| None, + ); + assert_eq!(race_p.map(|p| p as usize), Some(base_ptr + 100 * 256)); + assert_eq!(freed, vec![spare_ptr], "redundant sparse block must be freed outside lock"); + + // 4. Large allocation uses direct sparse fallback (outside STATES). + let big = crate::gpu::uma::ARENA_BLOCK; + let p_large = alloc_recording_uma_with( + list, + big, + 256, + true, + |_, _, _| None, + || 0, + |sz, al| { + assert!(STATES.try_lock().is_ok(), "large sparse alloc must run outside STATES"); + assert_eq!((sz, al), (big, 256)); + Some((large_ptr, sz)) + }, + |_| true, + |_, _| None, + ); + assert_eq!(p_large.map(|p| p as usize), Some(large_ptr)); + assert_eq!(with(list, |s| s.uma.clone()), vec![base_ptr, large_ptr]); + + forget(list); + assert_eq!(console_list::take_pending_for_test(alloc), vec![base_ptr, large_ptr]); + } + drop(ids); + } + + #[test] + fn gpu_sparse_arena_fallback_maps_va_uploads_to_gpu_and_frees_on_reset() { + use crate::gpu::{fence, recomp::runner::skip_test}; + use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + + let _vram_guard = super::super::vram::VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + unsafe { + if std::env::var_os("XCL_UMA_MB").is_none() { + std::env::set_var("XCL_UMA_MB", "64"); + } + if super::super::backend() != super::super::Backend::Real { + return skip_test("no GPU"); + } + let Some(u) = crate::gpu::uma::get() else { + return skip_test("no UMA"); + }; + if !u.has_sparse() { + return skip_test("no sparse UMA windows"); + } + let raw_dev = super::super::real::device_raw(); + let Some(dev) = ID3D12Device::from_raw_borrowed(&raw_dev).cloned() else { + return skip_test("no backend device"); + }; + + let mut ids = Box::new([0u8; 4]); + let list_key = ids.as_mut_ptr() as *mut c_void; + let alloc_key = ids.as_mut_ptr() as usize + 1; + reset(list_key, alloc_key, 0); + + let mut sparse_allocs = 0usize; + let mut ptrs = Vec::new(); + for _ in 0..4 { + let p = alloc_recording_uma_with( + list_key, + 256, + 256, + true, + |s, sz, al| s.arena.take_bump(sz, al), + || 0, + |sz, al| { + sparse_allocs += 1; + super::super::sparse::alloc(sz, al) + }, + |ptr| super::super::sparse::free(ptr), + |_, _| None, + ) + .expect("sparse arena allocation"); + ptrs.push(p as usize); + } + assert_eq!(sparse_allocs, 1); + let block_base = with(list_key, |s| s.uma[0]); + assert!(u.is_sparse(block_base) && u.sparse_reservation(block_base).is_some()); + + let va0 = super::super::real::uma_va_of(ptrs[0]).expect("sparse arena VA 0"); + let va3 = super::super::real::uma_va_of(ptrs[3]).expect("sparse arena VA 3"); + assert_eq!(va3 - va0, (ptrs[3] - ptrs[0]) as u64); + + let (win_raw, off0) = super::super::real::uma_window_buffer(ptrs[0], 1024).expect("sparse window buffer"); + let src = ID3D12Resource::from_raw_borrowed(&(win_raw as *mut c_void)).unwrap().clone(); + + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); + let ca: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let cl: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &ca, None).unwrap(); + let done: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + + let rb_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 1024, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut rb: Option = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &rb_desc, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut rb).unwrap(); + let rb = rb.unwrap(); + + // Flush initial tile mappings/zeroing before writing CPU test payloads. + super::super::sparse::before_execute(&queue, &[], 0x1000); + std::ptr::write_volatile(ptrs[0] as *mut u32, 0xCAFE_1234); + std::ptr::write_volatile(ptrs[3] as *mut u32, 0xBEEF_5678); + let mut dirty = vec![ptrs[0] & !0xFFF, ptrs[3] & !0xFFF]; + dirty.sort_unstable(); + dirty.dedup(); + super::super::sparse::before_execute(&queue, &dirty, 0x1000); + cl.CopyBufferRegion(&rb, 0, &src, off0, 1024); + cl.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(cl.cast().unwrap())]); + queue.Signal(&done, 1).unwrap(); + fence::wait(&done, 1, &dev, None, 10_000).unwrap(); + assert!(dev.GetDeviceRemovedReason().is_ok()); + + let mut map_ptr = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut map_ptr)).unwrap(); + let w0 = std::ptr::read_volatile(map_ptr as *const u32); + let w3 = std::ptr::read_volatile((map_ptr as usize + (ptrs[3] - ptrs[0])) as *const u32); + rb.Unmap(0, None); + assert_eq!((w0, w3), (0xCAFE_1234, 0xBEEF_5678), "GPU must read writes from sparse Arena block"); + + forget(list_key); + console_list::allocator_reset(alloc_key as *mut c_void); + assert!(u.sparse_reservation(block_base).is_none(), "allocator reset must free seeded sparse Arena block"); + drop(ids); + } + } } diff --git a/crates/xcl/src/hle/d3d12x/console_list.rs b/crates/xcl/src/hle/d3d12x/console_list.rs index 71206c010a..f2ac9c1bc5 100644 --- a/crates/xcl/src/hle/d3d12x/console_list.rs +++ b/crates/xcl/src/hle/d3d12x/console_list.rs @@ -325,11 +325,26 @@ pub(crate) fn take_pending_for_test(allocator: usize) -> Vec { PENDING.lock().unwrap().as_mut().and_then(|m| m.remove(&allocator)).unwrap_or_default() } +#[cfg(test)] +pub(crate) fn pending_len_for_test(allocator: usize) -> usize { + PENDING.lock().unwrap().as_ref().and_then(|m| m.get(&allocator)).map_or(0, Vec::len) +} + +/// Take queued unified-memory blocks for `allocator` without freeing them (leaf lock). +pub(super) fn take_pending(allocator: usize) -> Vec { + PENDING.lock().unwrap().as_mut().and_then(|m| m.remove(&allocator)).unwrap_or_default() +} + +/// Return queued unified-memory blocks to coherent or sparse UMA outside any allocator lock. +pub(super) unsafe fn free_uma_blocks(blocks: &[usize]) { + free_uma(blocks); +} + /// An allocator was reset: the GPU no longer uses what its recordings put in unified memory. pub fn allocator_reset(allocator: *mut c_void) { - let blocks = PENDING.lock().unwrap().as_mut().and_then(|m| m.remove(&(allocator as usize))); - if let Some(b) = blocks { - unsafe { free_uma(&b) }; + let blocks = take_pending(allocator as usize); + if !blocks.is_empty() { + unsafe { free_uma(&blocks) }; } } @@ -535,11 +550,30 @@ unsafe extern "system" fn cl_barrier(this: *mut c_void, _n: u32, _barriers: *con unsafe extern "system" fn cl_allocate_upload_memory(this: *mut c_void, size: usize, align: usize) -> *mut u8 { let Some(u) = crate::gpu::uma::get() else { return std::ptr::null_mut() }; let size = size.max(16); - let align = align.max(16); + let align = align.max(16).next_power_of_two(); if size <= crate::gpu::uma::ARENA_BLOCK / 2 { if let Some(p) = with_list(this as usize, |st| st.arena.take(u, size, align, &mut st.uma)).flatten() { return p; } + if u.has_sparse() { + if let Some((ptr, rounded)) = super::sparse::alloc(crate::gpu::uma::ARENA_BLOCK, crate::gpu::uma::GRAIN) { + let res = with_list(this as usize, |st| { + st.arena + .take_bump(size, align) + .map(|p| (Some(p), Some(ptr))) + .unwrap_or_else(|| { + let p = st.arena.seed_block(ptr, rounded, size, align, &mut st.uma); + (p, p.is_none().then_some(ptr)) + }) + }); + let (out, unused) = res.unwrap_or((None, Some(ptr))); + if let Some(extra) = unused { + super::sparse::free(extra); + } + return out.unwrap_or(std::ptr::null_mut()); + } + } + return std::ptr::null_mut(); } if u.has_sparse() { if let Some((p, _)) = super::sparse::alloc(size, align) { @@ -642,9 +676,31 @@ unsafe fn free_uma(blocks: &[usize]) { unsafe fn uma_copy(st: &mut ListState, bytes: &[u8]) -> Option { let u = crate::gpu::uma::get()?; + let n = bytes.len().max(16); // 32-bit console addresses: window 0; a piece of the list's arena - let p = st.arena.take(u, bytes.len().max(16), 256, &mut st.uma)?; - std::ptr::copy_nonoverlapping(bytes.as_ptr(), p, bytes.len()); + let p = if let Some(p) = st.arena.take(u, n, 256, &mut st.uma) { + Some(p) + } else if u.has_sparse() { + if n <= crate::gpu::uma::ARENA_BLOCK / 2 { + let (ptr, rounded) = super::sparse::alloc(crate::gpu::uma::ARENA_BLOCK, crate::gpu::uma::GRAIN)?; + match st.arena.seed_block(ptr, rounded, n, 256, &mut st.uma) { + Some(p) => Some(p), + None => { + super::sparse::free(ptr); + None + } + } + } else { + let (ptr, _) = super::sparse::alloc(n, 256)?; + st.uma.push(ptr); + Some(ptr as *mut u8) + } + } else { + None + }?; + if !bytes.is_empty() { + std::ptr::copy_nonoverlapping(bytes.as_ptr(), p, bytes.len()); + } Some(p as usize) } diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index ef98c131b7..573f6401e7 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -835,7 +835,6 @@ pub unsafe fn on_create(list: *mut c_void, alloc: usize, pso: usize, ty: D3D12_C /// Clean up all tracked state when a command list is released for good. pub(super) fn on_release(list: usize) { - super::alloc_pool::forget_list(list); release_copy_scratch(list); super::title_textures::list_reset(list); let old = LISTS.lock().unwrap().as_mut().and_then(|m| m.remove(&list)); @@ -850,6 +849,7 @@ pub(super) fn on_release(list: usize) { WRITE64_SIGNAL_LISTS.fetch_sub(1, Ordering::AcqRel); } } + super::alloc_pool::forget_list(list); } /// Clear per-recording sync/write tracking on a split segment moved into `title_list`'s spare pool. @@ -3877,49 +3877,52 @@ pub(super) unsafe fn reset_pc(this: *mut c_void, alloc: usize, pso: usize) -> i3 let resolved = super::pso_async::resolve_for_bind(pso); // (the PC allocator the title's allocator stands for now: `alloc_pool`) let ty = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(this as usize))).and_then(|s| s.list_type).map_or(-1, |t| t.0); - let hr = super::alloc_pool::reset_list(this as usize, alloc, ty, |pc_alloc| { - pc:: i32>(this, PC_RESET)(this, pc_alloc, resolved) - }); - real::preserve_vtable(this, ext); - if hr < 0 { - return hr; - } - - reset_copy_scratch(this); - let is_bundle = { - let mut g = LISTS.lock().unwrap(); - let s = g.get_or_insert_with(HashMap::new).entry(this as usize).or_default(); - s.allocator = alloc; - s.bound_pso = pso; - s.depth_bias = None; - s.native_bias = DepthBias::ZERO; - s.pso_dirty = false; - s.using_fallback_pso = false; - s.index_buffer = None; - s.depth_bounds = None; - 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(); - s.list_type == Some(D3D12_COMMAND_LIST_TYPE_BUNDLE) - }; - super::title_textures::list_reset(this as usize); - super::bind::reset(this, alloc, pso); - if !is_bundle && pso != 0 { - if let Some((true, static_bias)) = device_x::base_depth_bias_info(pso) { - if !static_bias.is_zero() && try_native_depth_bias(this, static_bias) { - if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(this as usize))) { - s.native_bias = static_bias; + super::alloc_pool::reset_list_with_retire( + this as usize, + alloc, + ty, + |pc_alloc| { + let hr = pc:: i32>(this, PC_RESET)(this, pc_alloc, resolved); + real::preserve_vtable(this, ext); + hr + }, + || { + reset_copy_scratch(this); + let is_bundle = { + let mut g = LISTS.lock().unwrap(); + let s = g.get_or_insert_with(HashMap::new).entry(this as usize).or_default(); + s.allocator = alloc; + s.bound_pso = pso; + s.depth_bias = None; + s.native_bias = DepthBias::ZERO; + s.pso_dirty = false; + s.using_fallback_pso = false; + s.index_buffer = None; + s.depth_bounds = None; + 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(); + s.list_type == Some(D3D12_COMMAND_LIST_TYPE_BUNDLE) + }; + super::title_textures::list_reset(this as usize); + super::bind::reset(this, alloc, pso); + if !is_bundle && pso != 0 { + if let Some((true, static_bias)) = device_x::base_depth_bias_info(pso) { + if !static_bias.is_zero() && try_native_depth_bias(this, static_bias) { + if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(this as usize))) { + s.native_bias = static_bias; + } + } } } - } - } - hr + }, + ) } /// the D3D12_RESOURCE_STATES bits the PC knows diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 4ea6374885..4e0b1cb015 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -2972,16 +2972,26 @@ unsafe extern "system" fn cl_reset(this: *mut c_void, allocator: *mut c_void, in let f: unsafe extern "system" fn(*mut c_void, *mut c_void, *mut c_void) -> HRESULT = std::mem::transmute(orig_fn(this, slot_of(this, "Reset"))); let resolved = super::pso_async::resolve_for_bind(initial_state as usize) as *mut c_void; - let hr = f(this, allocator, resolved); - preserve_vtable(this, ext); - if hr >= 0 { - super::list_x::on_pc_reset(this); - super::dred::reset(this); - if !initial_state.is_null() { - super::dred::mark_pipeline(this, initial_state as usize, resolved as usize); - } - } - hr + let ty_fn: unsafe extern "system" fn(*mut c_void) -> D3D12_COMMAND_LIST_TYPE = + std::mem::transmute(orig_fn(this, slot_of(this, "GetType"))); + let ty = ty_fn(this).0; + super::alloc_pool::reset_list_with_retire( + this as usize, + allocator as usize, + ty, + |pc_alloc| { + let hr = f(this, pc_alloc as *mut c_void, resolved); + preserve_vtable(this, ext); + hr + }, + || { + super::list_x::on_pc_reset(this); + super::dred::reset(this); + if !initial_state.is_null() { + super::dred::mark_pipeline(this, initial_state as usize, resolved as usize); + } + }, + ) } /// The PC size of a CheckFeatureSupport structure. @@ -6822,9 +6832,9 @@ unsafe extern "system" fn cl_release(this: *mut c_void) -> u32 { let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2)); let n = f(this); if n == 0 { - super::list_x::on_release(this as usize); super::bind::forget(this); super::dred::forget_list(this); + super::list_x::on_release(this as usize); } n } @@ -6845,6 +6855,7 @@ unsafe extern "system" fn alloc_release(this: *mut c_void) -> u32 { dispatch_chain::allocator_reset(this as usize); super::alloc_pool::forget(this as usize); super::list_x::on_allocator_release(this as usize); + super::bind::on_title_allocator_release(this as usize); } n }