From 73a197aa1813b8b813e9bcd8a1fc786b8715ef14 Mon Sep 17 00:00:00 2001 From: ArtuArtaza <71021164+ArtuArtaza@users.noreply.github.com> Date: Tue, 1 Dec 2026 15:52:02 -0300 Subject: [PATCH 1/2] D3D12.X: an idle allocator's pool state goes before its last Release alloc_release dropped what XCL keeps by a command allocator's address (the pool's namespace and type, the dispatch chain's and list_x's state) after the Release that frees the object. In between, the driver can give that address to an allocator another thread creates, and the cleanup then ran on the new one: alloc_pool::forget took its type and stand-ins, and marked one that already held a recording for release by the pool. For an allocator nothing uses, the cleanup now runs while the hook still holds its probe reference, before the Release that frees it. One the pool keeps for the GPU, and a Release that did not see the last reference, are cleaned up after it as before. sage-sage's #2701 proposed this order for heaps, queues and allocators; the allocator part is not on main. Measured on main b2b1f109 (RX 6700 XT, driver 32.0.21045.29003) with a GPU test that creates allocators between the Release and the cleanup until one comes back at the freed address: it failed 5 of 5 runs there and passed 5 of 5 with this order. That test needs a hook in alloc_release and is not part of this commit. Assisted-by: Claude Code (Claude Fable 5.2) --- crates/xcl/src/hle/d3d12x/alloc_pool.rs | 40 ++++++++++++++++++++++++- crates/xcl/src/hle/d3d12x/real.rs | 19 +++++++++--- 2 files changed, 54 insertions(+), 5 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs index bbb56bdc3f..56c33288bf 100644 --- a/crates/xcl/src/hle/d3d12x/alloc_pool.rs +++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs @@ -250,14 +250,24 @@ pub(super) fn forget_queue(id: super::present::QueueId) { drop(gone); } +/// Release through a temporary reference. When the caller's was the last one, a busy allocator's +/// probe reference is handed to the pool (`retain_probe`), and an idle one's books are dropped +/// (`before_last`) before the last Release: the address is still this object's then. pub(super) fn release_with_probe( add_ref: impl FnOnce(), mut release: impl FnMut() -> u32, retain_probe: impl FnOnce() -> bool, + before_last: impl FnOnce(), ) -> (u32, bool) { add_ref(); let after_caller = release(); - if after_caller == 1 && retain_probe() { (0, true) } else { (release(), false) } + if after_caller == 1 { + if retain_probe() { + return (0, true); + } + before_last(); + } + (release(), false) } /// Transfer the caller's temporary AddRef probe into pool ownership when releasing `raw` would @@ -1624,6 +1634,7 @@ mod tests { retained.set(retained.get() + 1); true }, + || panic!("a busy allocator keeps its books: the pool holds it"), ); assert_eq!((remaining, transferred, refs.get(), retained.get()), (0, true, 1, 1)); refs.set(refs.get() - 1); // the out-of-lock sweep releases the transferred probe @@ -1641,10 +1652,37 @@ mod tests { retained.set(retained.get() + 1); true }, + || panic!("another reference is left: nothing ends"), ); assert_eq!((remaining, transferred, refs.get(), retained.get()), (1, false, 1, 0)); } + /// The last Release of an allocator nothing uses: its books go while the object is still + /// there, so that a new allocator the driver makes at its address keeps its own. (After the + /// Release, `forget` took the new one's type and stand-ins, and marked one with a recording + /// for release by the pool.) + #[test] + fn an_idle_allocators_books_go_before_its_last_release() { + use std::cell::{Cell, RefCell}; + let refs = Cell::new(1u32); + let events = RefCell::new(Vec::new()); + let (remaining, transferred) = release_with_probe( + || refs.set(refs.get() + 1), + || { + refs.set(refs.get() - 1); + events.borrow_mut().push(if refs.get() == 0 { "freed" } else { "probe released" }); + refs.get() + }, + || { + events.borrow_mut().push("asked the pool"); + false + }, + || events.borrow_mut().push("books dropped"), + ); + assert_eq!((remaining, transferred), (0, false)); + assert_eq!(*events.borrow(), ["probe released", "asked the pool", "books dropped", "freed"]); + } + #[test] fn release_probe_retries_a_same_address_backing_replacement() { use std::mem::{offset_of, size_of}; diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index a9dad2dd11..f860ed3413 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -11549,15 +11549,26 @@ unsafe extern "system" fn alloc_release(this: *mut c_void) -> u32 { return f(this); } let add_ref: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 1)); + // What XCL keeps by the allocator's address goes while this call still holds its last + // reference: once the driver has freed it, another thread can be given a new allocator at + // that address, and these would then be that one's books. + let ended = std::cell::Cell::new(false); + let end = || { + ended.set(true); + dispatch_chain::allocator_reset(this as usize); + super::alloc_pool::forget(this as usize); + super::list_x::on_allocator_release(this as usize); + }; let (n, _) = super::alloc_pool::release_with_probe( || { add_ref(this); }, || f(this), || super::alloc_pool::retain_release_probe(this), + end, ); - if n == 0 { - dispatch_chain::allocator_reset(this as usize); - super::alloc_pool::forget(this as usize); - super::list_x::on_allocator_release(this as usize); + // (one the pool keeps for the GPU, or two Releases at once that both missed the last + // reference: after the Release, as before) + if n == 0 && !ended.get() { + end(); } n } From ffc43a27997e06b2bfe1f3db530ab9e6010233c2 Mon Sep 17 00:00:00 2001 From: ArtuArtaza <71021164+ArtuArtaza@users.noreply.github.com> Date: Tue, 1 Dec 2026 16:32:44 -0300 Subject: [PATCH 2/2] D3D12.X: XCL_ALLOC_TRIM_MB releases grown PC command allocators amdxc64 keeps a command allocator's memory over its Reset: on an RX 6700 XT (driver 32.0.21045.29003) 20 allocators with 100,000 copies each held 60.6 MB of non-local memory, as much after their Reset, and 0.6 MB a few seconds after their Release. The pool resets and keeps its PC allocators, so each stays as large as the largest recording it ever held. In a retail title's world that memory grew by about 60 MB a frame until the device was removed at 5.6-5.8 GB. With XCL_ALLOC_TRIM_MB=, once the process holds more than n MB of non-local memory besides the coherent windows, the idle PC allocators put aside are released instead of kept, and the title's Reset of an allocator nothing uses goes on with a new PC allocator when the one in use was recorded on. Off by default: the first recording on a new allocator took 1.1 ms on that driver, a recording after a Reset about 1 us, and the title's world went through about 75 new ones a frame. Measured with the limit at 1024 MB on main d0832e61 + #3455 + #3473 (this card needs both to reach the world), 3 runs each, 60 s into the world: commit 29.1 -> 26.7 GB, working set 20.3 -> 17.9 GB, shared GPU memory 8.8 -> 6.5 GB, growth 59-63 -> 19-25 MB a frame. The device was removed in 7 of 9 world runs without it and in none of 20 with it. iggyvilla found the leak (#3110: amdxc64 keeps memory per command list and per allocator), and Simon-CR's #2138 releases idle put-aside allocators. This builds on the reset of idle ones that is in main (31930d85, bmjask; Saksukella's #2707 proposed the same). Assisted-by: Claude Code (Claude Fable 5.2) --- README.md | 4 + crates/xcl/src/hle/d3d12x/alloc_pool.rs | 212 ++++++++++++++++++++++-- 2 files changed, 204 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 62d4178157..b876211de7 100644 --- a/README.md +++ b/README.md @@ -408,6 +408,10 @@ Fill the reusable DXIL cache ahead of a run with the read-only package wrapper. those on which the GPU completed at least one operation. For each, it names the translated pipeline bound at the last operation DRED saw complete and those bound after it, by their console shaders' hashes (`cs`, `vs` / `ps`, `ms` / `ps`, `vs` / `gs` / `ps`). +- `XCL_ALLOC_TRIM_MB=`: once the process holds more than `n` MB of non-local video memory besides + the coherent windows, idle command allocators are released and a `Reset` goes on with a new one + (AMD's driver keeps an allocator's memory over its `Reset`). Off by default: the first recording + on a new allocator is slow (about 1 ms on an RX 6700 XT). - `XCL_TEXTURE_LEVEL_PAGES=1` gives sampled title textures backing as their mip levels stream in. Zero-filled mip uploads in a batch share one staging span and still clear any mapped tiles. - `XCL_DSTORAGE_PARALLEL_DECOMPRESS=1` enables parallel CPU decompression for file-backed zlib diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs index 56c33288bf..18d910738d 100644 --- a/crates/xcl/src/hle/d3d12x/alloc_pool.rs +++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs @@ -13,6 +13,11 @@ //! put aside earlier whose lists have all been reset since and whose submits are done, or a new //! one. A list reset on the title's allocator records on the PC allocator in use. A list holds //! one recording, so no more allocators are put aside than there are lists. +//! +//! A driver may keep an allocator's memory over its Reset, for the next recording (AMD's does: +//! `trim_limit`), so each PC allocator stays as large as the largest recording it ever held. With +//! `XCL_ALLOC_TRIM_MB`, past that much memory the idle ones are released instead of kept, and a +//! Reset goes on with a new one. use std::collections::{hash_map::Entry, HashMap, HashSet}; use std::ffi::c_void; use std::ops::{Deref, DerefMut}; @@ -59,6 +64,8 @@ struct State { fences: HashMap>, made: u64, swaps: u64, + /// Resets that went on with a new PC allocator in place of one nothing used (`trimming`) + replaced: u64, /// PC list → its last submit (queue, fence, value after it, recording number then) last_submit: HashMap, /// PC list → recordings so far (a Reset or creation starts the next one) @@ -73,7 +80,7 @@ struct State { enum ResetWork { Reset { owner: ID3D12CommandAllocator, swap: bool, needed: bool }, - Create { owner: ID3D12CommandAllocator, ty: i32 }, + Create { owner: ID3D12CommandAllocator, ty: i32, replace: bool }, } struct ResetClaim { @@ -913,6 +920,105 @@ pub fn enabled() -> bool { *ON.get_or_init(|| !std::env::var("XCL_ALLOC_SWAP").is_ok_and(|v| v.trim() == "0")) } +#[cfg(test)] +std::thread_local! { + /// `trimming` for a test on its thread (off in the others) + static TRIM_IN_TEST: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// `XCL_ALLOC_TRIM_MB`: the non-local memory besides the coherent windows (bytes) past which idle +/// PC allocators are released and a Reset goes on with a new one (unset or 0: never). On an +/// RX 6700 XT (driver 32.0.21045) 20 allocators with 100,000 copies each held 60.6 MB of it, as +/// much after their Reset, and 0.6 MB a few seconds after their Release; in a retail title's +/// world that memory grew by ~60 MB a frame. Not on by default: the first recording on a new +/// allocator took 1.1 ms there, a recording after a Reset 1 µs. +fn trim_limit(v: Option<&str>) -> Option { + let mb = v.and_then(|v| v.trim().parse::().ok()).unwrap_or(0); + (mb > 0).then(|| mb.saturating_mul(1 << 20)) +} + +/// Whether the process holds more than `trim_limit` (asked at most every 250 ms), and whether +/// this call asked. +fn trimming() -> (bool, bool) { + #[cfg(test)] + return (TRIM_IN_TEST.with(|c| c.get()), false); + #[cfg(not(test))] + { + static LIMIT: std::sync::OnceLock> = std::sync::OnceLock::new(); + let Some(limit) = *LIMIT.get_or_init(|| trim_limit(std::env::var("XCL_ALLOC_TRIM_MB").ok().as_deref())) else { + return (false, false); + }; + static LAST: Mutex> = Mutex::new(None); + let now = std::time::Instant::now(); + { + let mut last = LAST.lock().unwrap(); + if let Some((at, over)) = *last { + if now.saturating_duration_since(at) < std::time::Duration::from_millis(250) { + return (over, false); + } + } + // (the others go on with the last answer while this call asks) + let over = last.is_some_and(|(_, over)| over); + *last = Some((now, over)); + } + let uma = super::real::uma_dxgi_bytes_for(super::real::device_raw() as usize).0; + let over = super::real::video_memory().is_some_and(|(_, non_local, _)| non_local.saturating_sub(uma) > limit); + *LAST.lock().unwrap() = Some((now, over)); + (over, true) + } +} + +/// The PC allocators of `alloc` put aside that nothing uses (`free`, as `probes` saw them), out of +/// `s`: not the title's own, which is the title's to release, nor the one in use. +fn take_idle_spares(s: &mut State, alloc: usize, probes: &[BackingProbe], free: &HashSet) -> Vec<(usize, Option)> { + if s.resetting.contains_key(&alloc) { + return Vec::new(); + } + let current = s.cur.get(&alloc).copied().unwrap_or(alloc); + let idle: Vec = s.aside.get(&alloc).into_iter().flatten().copied().filter(|raw| { + *raw != alloc && *raw != current + && match (s.backings.get(raw), probes.iter().find(|probe| probe.raw == *raw)) { + (None, None) => true, + (Some(backing), Some(probe)) => free.contains(raw) && probe.matches(backing) && backing.release_owner.is_none(), + _ => false, + } + }).collect(); + if let Some(aside) = s.aside.get_mut(&alloc) { + aside.retain(|raw| !idle.contains(raw)); + } + idle.into_iter().map(|raw| (raw, s.backings.remove(&raw))).collect() +} + +/// Release the PC allocators put aside that nothing uses: those of `alloc`, or of every title +/// allocator (None). +unsafe fn release_idle_spares(alloc: Option) { + let probes: Vec<(usize, Vec)> = { + let g = STATE.lock().unwrap(); + let Some(s) = g.as_ref() else { return }; + s.aside.iter().filter(|(owner, aside)| alloc.is_none_or(|a| a == **owner) && !aside.is_empty()) + .map(|(&owner, _)| (owner, namespace_probes(s, owner).1)).collect() + }; + let mut gone = Vec::new(); + for (owner, probes) in &probes { + let free: HashSet = probes.iter().filter(|probe| unsafe { probe.free() }).map(|probe| probe.raw).collect(); + let mut g = STATE.lock().unwrap(); + let Some(s) = g.as_mut() else { return }; + gone.extend(take_idle_spares(s, *owner, probes, &free)); + } + // (outside the lock: their Release comes back here) + static RELEASED: AtomicU64 = AtomicU64::new(0); + for (raw, backing) in gone { + drop(backing); + super::console_list::allocator_reset(raw as *mut c_void); + drop(ID3D12CommandAllocator::from_raw(raw as *mut c_void)); + let n = RELEASED.fetch_add(1, Ordering::Relaxed) + 1; + if n.is_power_of_two() { + let replaced = STATE.lock().unwrap().as_ref().map_or(0, |s| s.replaced); + crate::xlog_info!("D3D12.X: {n} idle PC command allocators released so far, {replaced} resets went on with a new one (XCL_ALLOC_TRIM_MB)"); + } + } +} + fn move_list(s: &mut State, list: usize, backing: usize) { if let Some(old) = s.of_list.insert(list, backing) { if old != backing { @@ -1301,6 +1407,9 @@ pub unsafe fn forget(alloc: usize) { /// callback, final Release, or newly recorded list invalidate the whole unlocked batch. unsafe fn reclaim_idle_aside(alloc: *mut c_void) { let a = alloc as usize; + if trimming().0 { + release_idle_spares(Some(a)); + } let claim = loop { let (mine, probes, free) = { let g = STATE.lock().unwrap(); @@ -1426,6 +1535,11 @@ pub unsafe fn title_reset(alloc: *mut c_void) -> Option { return None; } let a = alloc as usize; + let (trim, asked) = trimming(); + if trim { + // (before one of them is taken for this Reset: it keeps the size it once grew to) + release_idle_spares((!asked).then_some(a)); + } let claim = loop { let (mine, probes, shared) = { let mut g = STATE.lock().unwrap(); @@ -1451,6 +1565,12 @@ pub unsafe fn title_reset(alloc: *mut c_void) -> Option { } let current = s.cur.get(&a).copied().unwrap_or(a); if !s.backings.contains_key(¤t) || free.contains(¤t) { + let grown = s.backings.get(¤t).is_some_and(|backing| !backing.already_reset); + if let Some(&ty) = s.types.get(&a).filter(|_| trim && grown) { + let Some(owner) = ID3D12CommandAllocator::from_raw_borrowed(&alloc).cloned() else { return Some(crate::util::E_FAIL) }; + let token = reserve_reset(s, a).unwrap(); + break ResetClaim { alloc: a, current, token, mine, probes, work: ResetWork::Create { owner, ty, replace: true } }; + } if current == a { let retired = s.backings.get_mut(¤t) .map(|backing| backing.marks.drain().map(|(_, (fence, _))| fence).collect::>()) @@ -1468,21 +1588,21 @@ pub unsafe fn title_reset(alloc: *mut c_void) -> Option { break ResetClaim { alloc: a, current, token, mine, probes, work: ResetWork::Reset { owner, swap: false, needed } }; } let Some(&ty) = s.types.get(&a) else { return Some(crate::util::E_FAIL) }; - if let Some(candidate) = s.aside.get(&a).and_then(|values| values.iter().copied().find(|raw| !s.backings.contains_key(raw) || free.contains(raw))) { + if let Some(candidate) = s.aside.get(&a).filter(|_| !trim).and_then(|values| values.iter().copied().find(|raw| !s.backings.contains_key(raw) || free.contains(raw))) { let raw = candidate as *mut c_void; let Some(owner) = ID3D12CommandAllocator::from_raw_borrowed(&raw).cloned() else { return Some(crate::util::E_FAIL) }; let token = reserve_reset(s, a).unwrap(); let needed = s.backings.get(&candidate).is_none_or(|backing| !backing.already_reset); break ResetClaim { alloc: a, current, token, mine, probes, work: ResetWork::Reset { owner, swap: true, needed } }; } - if take_shared_aside(s, a, ty, &shared, &free) { + if !trim && take_shared_aside(s, a, ty, &shared, &free) { // Restart so the transferred candidate participates in this namespace's snapshot and // reset token exactly like a spare it had always owned. continue; } let Some(owner) = ID3D12CommandAllocator::from_raw_borrowed(&alloc).cloned() else { return Some(crate::util::E_FAIL) }; let token = reserve_reset(s, a).unwrap(); - break ResetClaim { alloc: a, current, token, mine, probes, work: ResetWork::Create { owner, ty } }; + break ResetClaim { alloc: a, current, token, mine, probes, work: ResetWork::Create { owner, ty, replace: false } }; }; let ResetClaim { alloc, current, token, mine, probes, work } = claim; @@ -1494,7 +1614,7 @@ pub unsafe fn title_reset(alloc: *mut c_void) -> Option { let result = { let mut g = STATE.lock().unwrap(); let Some(s) = g.as_mut() else { return Some(crate::util::E_FAIL) }; - if hr >= 0 && commit_reset(s, alloc, current, candidate, token, &mine, &probes, swap, false, &mut retired) { + if hr >= 0 && commit_reset(s, alloc, current, candidate, token, &mine, &probes, swap, false, false, &mut retired) { hr } else { cancel_reset(s, alloc, token); @@ -1508,7 +1628,7 @@ pub unsafe fn title_reset(alloc: *mut c_void) -> Option { } Some(result) } - ResetWork::Create { owner, ty } => { + ResetWork::Create { owner, ty, replace } => { let mut dev: Option = None; let made: Result = match owner.GetDevice(&mut dev) { Err(error) => Err(error.code().0), @@ -1532,7 +1652,7 @@ pub unsafe fn title_reset(alloc: *mut c_void) -> Option { let mut retired = Vec::new(); let committed = { let mut g = STATE.lock().unwrap(); - g.as_mut().is_some_and(|s| commit_reset(s, alloc, current, raw as usize, token, &mine, &probes, true, true, &mut retired)) + g.as_mut().is_some_and(|s| commit_reset(s, alloc, current, raw as usize, token, &mine, &probes, true, true, replace, &mut retired)) }; drop(retired); drop(owner); @@ -1557,6 +1677,7 @@ fn commit_reset( probes: &[BackingProbe], swap: bool, created: bool, + replace: bool, retired: &mut Vec, ) -> bool { if s.resetting.get(&alloc) != Some(&token) || !namespace_matches(s, alloc, mine, probes) { @@ -1581,8 +1702,12 @@ fn commit_reset( s.aside.entry(alloc).or_default().push(current); s.cur.insert(alloc, candidate); if created { s.made += 1; } - s.swaps += 1; cancel_reset(s, alloc, token); + if replace { + s.replaced += 1; + return true; + } + s.swaps += 1; if s.swaps.is_power_of_two() { let aside: usize = s.aside.values().map(|v| v.len()).sum(); crate::xlog_info!( @@ -2293,7 +2418,7 @@ mod tests { let (mine, probes) = namespace_probes(s, alloc); let token = reserve_reset(s, alloc).unwrap(); let mut retired = Vec::new(); - commit_reset(s, alloc, alloc, next, token, &mine, &probes, true, false, &mut retired) + commit_reset(s, alloc, alloc, next, token, &mine, &probes, true, false, false, &mut retired) }) .join() .unwrap(); @@ -2416,7 +2541,7 @@ mod tests { let token = reserve_reset(&mut s, alloc).unwrap(); let mut retired = Vec::new(); - assert!(commit_reset(&mut s, alloc, alloc, spare, token, &mine, &probes, true, false, &mut retired)); + assert!(commit_reset(&mut s, alloc, alloc, spare, token, &mine, &probes, true, false, false, &mut retired)); assert_eq!(s.cur.get(&alloc), Some(&spare)); assert_eq!(s.aside.get(&alloc), Some(&vec![alloc]), "only the successful reset switches backings"); assert_eq!(s.of_list.get(&list), Some(&alloc), "the earlier recording stays on its original backing"); @@ -2576,7 +2701,7 @@ mod tests { let (committed, token_released) = { let mut g = STATE.lock().unwrap(); let s = g.as_mut().unwrap(); - let committed = commit_reset(s, alloc, alloc, spare, token, &mine, &probes, true, false, &mut Vec::new()); + let committed = commit_reset(s, alloc, alloc, spare, token, &mine, &probes, true, false, false, &mut Vec::new()); let token_released = !s.resetting.contains_key(&alloc); s.of_list.remove(&list); s.backings.remove(&alloc); @@ -2605,7 +2730,7 @@ mod tests { s.aside.insert(alloc, vec![spare]); let new_token = reserve_reset(&mut s, alloc).unwrap(); assert_ne!(old_token, new_token); - assert!(!commit_reset(&mut s, alloc, alloc, spare, old_token, &mine, &probes, true, false, &mut Vec::new())); + assert!(!commit_reset(&mut s, alloc, alloc, spare, old_token, &mine, &probes, true, false, false, &mut Vec::new())); assert_eq!(s.resetting.get(&alloc), Some(&new_token), "a stale completion cannot cancel the replacement's claim"); } @@ -2693,6 +2818,69 @@ mod tests { ); } + #[test] + fn allocators_are_trimmed_only_where_asked() { + assert_eq!(trim_limit(None), None, "unset: as before"); + assert_eq!(trim_limit(Some("0")), None); + assert_eq!(trim_limit(Some(" 256 ")), Some(256 << 20)); + assert_eq!(trim_limit(Some("x")), None, "not a number: off"); + } + + /// Of the allocators put aside only those nothing uses go: not the title's own, the one in + /// use, one a list still holds a recording on, one whose state changed since it was looked at. + #[test] + fn only_idle_spares_made_here_are_taken_out() { + let (alloc, cur, idle, untouched, busy, changed) = (0x1000usize, 0x2000usize, 0x3000usize, 0x4000usize, 0x5000usize, 0x6000usize); + let mut s = State::default(); + s.cur.insert(alloc, cur); + s.aside.insert(alloc, vec![alloc, idle, untouched, busy, changed]); + for raw in [alloc, cur, idle, busy, changed] { + backing_mut(&mut s, raw); + } + move_list(&mut s, 0x9000, busy); + let (_, probes) = namespace_probes(&s, alloc); + let free: HashSet = probes.iter().filter(|probe| unsafe { probe.free() }).map(|probe| probe.raw).collect(); + assert!(free.contains(&idle) && free.contains(&changed) && !free.contains(&busy)); + // (a recording starts on it after it was seen idle) + move_list(&mut s, 0xa000, changed); + let mut gone: Vec = take_idle_spares(&mut s, alloc, &probes, &free).into_iter().map(|(raw, _)| raw).collect(); + gone.sort_unstable(); + assert_eq!(gone, vec![idle, untouched]); + assert_eq!(s.aside[&alloc], vec![alloc, busy, changed]); + assert_eq!(s.cur[&alloc], cur); + assert!(!s.backings.contains_key(&idle) && s.backings.contains_key(&busy)); + // while a Reset of the same title allocator runs nothing is taken + s.aside.get_mut(&alloc).unwrap().push(untouched); + let token = reserve_reset(&mut s, alloc).unwrap(); + assert!(take_idle_spares(&mut s, alloc, &probes, &free).is_empty()); + cancel_reset(&mut s, alloc, token); + } + + /// A trimmed Reset of an allocator nothing uses: a new PC allocator takes its place and the + /// grown one is put aside, where `take_idle_spares` finds it. It is not counted as a swap. + #[test] + fn a_trimmed_reset_goes_on_with_a_new_allocator_and_the_grown_one_goes() { + let (alloc, grown, new) = (0x1000usize, 0x2000usize, 0x3000usize); + let mut s = State::default(); + s.types.insert(alloc, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + s.cur.insert(alloc, grown); + // (recorded on since its last Reset: it holds what that recording took) + assert!(!backing_mut(&mut s, grown).already_reset); + let (mine, probes) = namespace_probes(&s, alloc); + let token = reserve_reset(&mut s, alloc).unwrap(); + assert!(commit_reset(&mut s, alloc, grown, new, token, &mine, &probes, true, true, true, &mut Vec::new())); + assert_eq!(s.cur.get(&alloc), Some(&new)); + assert_eq!(s.aside.get(&alloc), Some(&vec![grown])); + assert_eq!((s.made, s.replaced, s.swaps), (1, 1, 0)); + assert!(!s.resetting.contains_key(&alloc)); + let (_, probes) = namespace_probes(&s, alloc); + let free: HashSet = probes.iter().filter(|probe| unsafe { probe.free() }).map(|probe| probe.raw).collect(); + let gone: Vec = take_idle_spares(&mut s, alloc, &probes, &free).into_iter().map(|(raw, _)| raw).collect(); + assert_eq!(gone, vec![grown]); + assert!(s.aside[&alloc].is_empty() && !s.backings.contains_key(&grown)); + assert_eq!(s.cur.get(&alloc), Some(&new), "the one in use stays"); + } + /// The title's Reset (through `real::alloc_reset`) while the GPU has not run a submit of a /// recording on its allocator: the allocator is put aside, and what the recording left in /// unified memory stays until the GPU has passed it (#1358).