From e26bb4169b8b6d4b33c2404d900be31699346707 Mon Sep 17 00:00:00 2001 From: Trey Bertram <113378171+treybertram06@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:29:49 -0800 Subject: [PATCH 1/2] D3D12.X: sparse tiles outside the GPU heaps can live in system memory With XCL_COHERENT_HEAPS=sparse the title's GPU heaps (committed memory with a PAGE_GRAPHICS_* protection, ~4.5 GB in a retail title) live in the sparse windows. Those are the data the title's shaders read and write every frame; in the coherent window (system memory, read over PCIe) one retail compute program took 1,364 ms a frame on an RTX 3080, under 33 ms in video memory. With them in video memory the windows hold ~7.5 GB of tiles and the device ran out of its budget (19 GB in use against 8.9 GB, removed at 659 s). XCL_SPARSE_SYSMEM=1 (off by default): kernelx registers a GPU heap's range as hot before its commit maps its tiles (sparse::alloc_as); every other sparse-window tile takes a pool tile in system-memory pool heaps (custom heaps, L0, write-back), which the GPU reads over PCIe. A pool tile of those heaps has SYS in its pool index; freed ones cool in their own lists, kept by the heap's number without SYS (the free table is indexed by heap number). RTX 3080, retail title, 400 s of its world after the menus: heaps in video memory alone 0.98 presents/s and 19 GB of video memory; with this and the texture-level counterpart 1.70 presents/s, 12.7 GB, no device removal in 900 s. An RTX 4080 report on #2688 found the same with a port of it. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/sparse.rs | 262 ++++++++++++++++++++++++++-- crates/xcl/src/hle/kernelx.rs | 3 +- 2 files changed, 254 insertions(+), 11 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index fb532258fd..00129892df 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -481,6 +481,61 @@ impl FreePools { } } +/// `XCL_SPARSE_SYSMEM=1`: sparse-window tiles outside the +/// title's GPU heaps (`note_hot`) get pool tiles in system memory (custom heaps in L0, read by +/// the GPU over PCIe) instead of video memory; the GPU heaps' tiles keep video memory. A pool +/// tile of these heaps has `SYS` set in its pool index. +const SYS: u32 = 1 << 31; + +#[derive(Default)] +struct SysPools { + heaps: Vec, + /// (by the heap's index without `SYS`: `FreePools` sizes its table by it) + free: FreePools, + cooling: VecDeque<((u32, u32), std::time::Instant)>, +} + +// D3D12 heaps are free-threaded +unsafe impl Send for SysPools {} + +static SYS_POOLS: Mutex> = Mutex::new(None); +/// the title's GPU heaps in the sparse windows (`XCL_COHERENT_HEAPS=sparse`): (start, bytes) +static HOT: Mutex> = Mutex::new(Vec::new()); + +/// `[a, a + n)` is a GPU heap of the title: its tiles keep video memory under `XCL_SPARSE_SYSMEM`. +pub fn note_hot(a: usize, n: usize) { + HOT.lock().unwrap().push((a, n)); +} + +/// The reservation at `a` is released: a later one there is placed by its own kind. +pub fn forget_hot(a: usize) { + HOT.lock().unwrap().retain(|&(s, _)| s != a); +} + +#[cfg_attr(test, allow(unreachable_code))] +fn sysmem_tiles() -> bool { + // (a test's own thread decides: the environment of a test run does not) + #[cfg(test)] + return tests::SYSMEM_FOR_TEST.with(|c| c.get()); + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| { + let on = std::env::var("XCL_SPARSE_SYSMEM").is_ok_and(|v| v.trim() == "1"); + if on { + crate::xlog_info!("sparse windows: XCL_SPARSE_SYSMEM=1 - tiles outside the title's GPU heaps in system memory"); + } + on + }) +} + +fn is_hot(a: usize) -> bool { + HOT.lock().unwrap().iter().any(|&(s, n)| a >= s && a < s + n) +} + +/// Bytes of the system-memory pool heaps. +pub fn sys_pool_bytes() -> usize { + SYS_POOLS.lock().unwrap().as_ref().map_or(0, |p| p.heaps.len() * POOL_TILES as usize * TILE) +} + /// Whether the oldest tile of `cooling` was freed `COOL` ago or more at `now` fn cooled(cooling: &VecDeque<((u32, u32), std::time::Instant)>, now: std::time::Instant) -> bool { cooling.front().is_some_and(|&(_, at)| now.duration_since(at) >= COOL) @@ -3127,7 +3182,8 @@ pub fn pool_bytes() -> (usize, usize) { let _held = holding(Holder::Other); let Some(s) = g.as_ref() else { return (0, 0) }; let pools = s.pools.iter().filter(|p| p.is_some()).count() * POOL_TILES as usize * TILE; - let quarantined: usize = s.quarantined.iter().map(|b| b.tiles.len()).sum(); + // (tiles of the system-memory pools, `SYS`, are none of these bytes) + let quarantined: usize = s.quarantined.iter().map(|b| b.tiles.iter().filter(|t| t.0 & SYS == 0).count()).sum(); (pools, pools.saturating_sub((s.free.len() + s.cooling.len() + quarantined) * TILE)) } @@ -3508,6 +3564,68 @@ impl State { Some(UploadPageObservation { page, pool: entry.pool, hole, sent, source }) } + /// `take_tile` from the system-memory pools (`XCL_SPARSE_SYSMEM`). + unsafe fn take_sys_tile(&mut self) -> Option<((u32, u32), bool)> { + self.drain_quarantined(); + let mut g = SYS_POOLS.lock().unwrap(); + let p = g.get_or_insert_with(SysPools::default); + if let Some((h, t)) = reuse_tile(&mut p.free, &mut p.cooling, std::time::Instant::now()) { + return Some(((SYS | h, t), true)); + } + let desc = D3D12_HEAP_DESC { + SizeInBytes: POOL_TILES as u64 * TILE as u64, + Properties: D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_CUSTOM, + CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, + MemoryPoolPreference: D3D12_MEMORY_POOL_L0, + ..Default::default() + }, + Alignment: 0, + Flags: D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES | D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES, + }; + let mut heap: Option = None; + if let Err(e) = super::title_textures::own_work(|| self.dev.CreateHeap(&desc, &mut heap)) { + crate::xlog_warn!("sparse windows: no system-memory pool heap ({e}) - video memory instead"); + drop(g); + return self.take_tile(); + } + let heap = heap?; + let _ = heap.SetName(windows::core::w!("xcl sparse system-memory pool")); + p.heaps.push(heap); + let h = p.heaps.len() as u32 - 1; + p.free.add_heap(h); + let n = p.heaps.len(); + if n.is_power_of_two() { + crate::xlog_info!("sparse windows: {} MB of system-memory pool heaps", n * POOL_TILES as usize * TILE >> 20); + } + Some(((SYS | h, 0), false)) + } + + /// A pool tile for window tile `t`: from the system-memory pools under `XCL_SPARSE_SYSMEM` + /// unless `t` is in a GPU heap of the title. + unsafe fn take_tile_for(&mut self, t: usize) -> Option<((u32, u32), bool)> { + if sysmem_tiles() && !is_hot(t) { self.take_sys_tile() } else { self.take_tile() } + } + + /// The heap of pool index `h` (video memory, or a system-memory pool with `SYS`). + fn pool_heap(&self, h: u32) -> ID3D12Heap { + if h & SYS != 0 { + return SYS_POOLS.lock().unwrap().as_ref().expect("system-memory pools").heaps[(h & !SYS) as usize].clone(); + } + self.pools[h as usize].clone().expect("a pool tile of a live pool") + } + + /// A freed pool tile cools in its own pools' queue. + fn cool(&mut self, tile: (u32, u32), at: std::time::Instant) { + if tile.0 & SYS != 0 { + if let Some(p) = SYS_POOLS.lock().unwrap().as_mut() { + p.cooling.push_back(((tile.0 & !SYS, tile.1), at)); + } + } else { + self.cooling.push_back((tile, at)); + } + } + /// A pool tile (true: used before, to be cleared). One freed less than `COOL` ago, or one /// still `quarantined`, is not taken: a retired pool is taken back or a heap made instead. /// (Parked tiles are not flushed for it: freed now, they would wait and cool all the same.) @@ -3635,7 +3753,7 @@ impl State { coords.len() as u32, Some(coords.as_ptr()), Some(regions.as_ptr()), - self.pools[h as usize].as_ref().expect("a pool tile of a live pool"), + &self.pool_heap(h), flags.len() as u32, Some(flags.as_ptr()), Some(offsets.as_ptr()), @@ -3801,8 +3919,10 @@ impl State { while t < end { if self.mapped.get(&t).is_some_and(|e| e.pool == LAZY) { let at_hand = !self.free.is_empty() || cooled(&self.cooling, std::time::Instant::now()) || !self.retired.is_empty(); - let wait = left > 0 || (!force && self.short_of_memory() && !at_hand); - match if wait { None } else { self.take_tile() } { + // (short of video memory: a tile of the system-memory pools does not wait for it) + let sys = sysmem_tiles() && !is_hot(t); + let wait = left > 0 || (!force && !sys && self.short_of_memory() && !at_hand); + match if wait { None } else { self.take_tile_for(t) } { Some((tile, used)) => { if let Some(e) = self.mapped.get_mut(&t) { e.pool = tile; @@ -3850,11 +3970,29 @@ impl State { let end = a.saturating_add(n); let mut new = false; let mut unparked = false; + // parked system-memory tiles at addresses of a GPU heap now (`XCL_SPARSE_SYSMEM`) + let mut replaced = Vec::new(); let mut t = first; while t < end { if !self.mapped.contains_key(&t) && !self.mirror_src.contains_key(&t) && self.window_index(t).is_some() { - // still mapped there: no new mapping, what it held is cleared - if let Some(tile) = self.parked.remove(&t).or_else(|| self.kept.remove(&t)) { + // a tile parked here from before is in system memory and a GPU heap of the title + // is here now: a video-memory tile takes its place, mapped over it at once, and it + // goes once the GPU is past that (one a placed buffer uses stays; none found: it stays) + let swap = self.parked.get(&t).is_some_and(|tile| tile.0 & SYS != 0 && !self.pinned.contains_key(tile)) && is_hot(t); + if let Some((tile, reused)) = if swap { self.take_tile() } else { None } { + replaced.extend(self.parked.remove(&t)); + let (holes, not_rw) = initial_state(t); + let mut entry = TileEntry::with_holes(tile, holes); + entry.not_rw = not_rw; + self.mapped.insert(t, entry); + early_add(&mut self.runs, t, t + TILE); + if reused { + self.to_zero.insert((t, TILE)); + } + self.pending.push(t); + new = true; + } else if let Some(tile) = self.parked.remove(&t).or_else(|| self.kept.remove(&t)) { + // still mapped there: no new mapping, what it held is cleared let (holes, not_rw) = initial_state(t); let mut entry = TileEntry::with_holes(tile, holes); entry.not_rw = not_rw; @@ -3863,7 +4001,7 @@ impl State { self.to_zero.insert((t, TILE)); unparked = true; } else { - let Some((tile, reused)) = self.take_tile() else { break }; + let Some((tile, reused)) = self.take_tile_for(t) else { break }; let (holes, not_rw) = initial_state(t); let mut entry = TileEntry::with_holes(tile, holes); entry.not_rw = not_rw; @@ -3884,7 +4022,12 @@ impl State { if new || unparked { MAPPED_GEN.fetch_add(1, Ordering::Release); } - if self.pending.len() >= PENDING_MAX { + if !replaced.is_empty() { + // (their new mappings sent first: the old tiles go behind the fence of that) + self.flush_pending(); + let completion = super::present::queue_completion_snapshot(); + self.quarantine_tiles_for(replaced, &completion.active, &completion.retiring, completion.blocked); + } else if self.pending.len() >= PENDING_MAX { self.flush_pending(); } else if !self.pending.is_empty() { pending_soon(); @@ -4888,9 +5031,19 @@ fn uav_to_copy(r: &ID3D12Resource) -> D3D12_RESOURCE_BARRIER { /// 4 GiB window boundary when `size <= 4 GiB`). Commits the CPU pages and maps VRAM tiles /// (or queues them until the D3D12 device exists). Returns `(address, rounded_size)`. pub unsafe fn alloc(size: usize, align: usize) -> Option<(usize, usize)> { + alloc_as(size, align, false) +} + +/// `alloc` of a title GPU heap (`hot`: its tiles keep video memory under `XCL_SPARSE_SYSMEM`, +/// known before its commit maps them). +pub unsafe fn alloc_as(size: usize, align: usize, hot: bool) -> Option<(usize, usize)> { let u = crate::gpu::uma::get()?; let (addr, rounded) = u.sparse_alloc(size, align)?; + if hot { + note_hot(addr, rounded); + } if VirtualAlloc(addr as *const c_void, rounded, MEM_COMMIT, PAGE_READWRITE).is_null() { + forget_hot(addr); u.sparse_release(addr); return None; } @@ -4922,6 +5075,7 @@ pub unsafe fn free(p: usize) -> bool { let Some((start, len)) = u.sparse_reservation(p).filter(|&(start, _)| start == p) else { return false }; decommitted(start, len); VirtualFree(p as *mut c_void, len, MEM_DECOMMIT); + forget_hot(start); u.sparse_release(p).is_some() } @@ -5896,7 +6050,7 @@ impl State { && self.parked.get(&t) != Some(&tile) && !self.quarantined.iter().any(|b| b.tiles.contains(&tile)) { - self.cooling.push_back((tile, std::time::Instant::now())); + self.cool(tile, std::time::Instant::now()); } } @@ -5982,7 +6136,7 @@ impl State { let at = batch.at; for tile in batch.tiles { if !self.pinned.contains_key(&tile) { - self.cooling.push_back((tile, at)); + self.cool(tile, at); freed = true; } } @@ -8457,6 +8611,8 @@ mod tests { pub(super) static LAZY_COMMITS_FOR_TEST: std::cell::Cell> = const { std::cell::Cell::new(None) }; /// `take_tile` finds no video memory on this thread pub(super) static NO_TILES: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// `sysmem_tiles` (`XCL_SPARSE_SYSMEM`) for the test on this thread (`Lazy::sysmem`) + pub(super) static SYSMEM_FOR_TEST: std::cell::Cell = const { std::cell::Cell::new(false) }; } /// The runs of the tiles mapped, made from all of them (but those over a CPU view: their @@ -10318,6 +10474,23 @@ mod tests { } } + #[test] + fn the_title_gpu_heaps_are_hot_and_nothing_around_them() { + // (addresses no other test uses: `HOT` is global) + let (a, n) = (0x7f12_3400_0000usize, 3 * TILE); + assert!(!is_hot(a)); + note_hot(a, n); + assert!(is_hot(a) && is_hot(a + TILE) && is_hot(a + n - 1)); + assert!(!is_hot(a - 1) && !is_hot(a + n)); + // a pool tile of the system-memory pools is told apart by its pool index + let (video, system) = ((7u32, 3u32), (SYS | 7, 3u32)); + assert!(video.0 & SYS == 0 && system.0 & SYS != 0); + assert_eq!(system.0 & !SYS, video.0); + // released: a reservation there later is placed by its own kind + forget_hot(a); + assert!(!is_hot(a) && !is_hot(a + TILE)); + } + #[test] fn aligned_tile_addresses_spread_across_hash_buckets() { use std::hash::BuildHasher; @@ -11262,11 +11435,16 @@ mod tests { fn no_tiles(&self, none: bool) { NO_TILES.with(|c| c.set(none)); } + /// `XCL_SPARSE_SYSMEM` on for this thread + fn sysmem(&self, on: bool) { + SYSMEM_FOR_TEST.with(|c| c.set(on)); + } } impl Drop for Lazy { fn drop(&mut self) { LAZY_COMMITS_FOR_TEST.with(|c| c.set(None)); NO_TILES.with(|c| c.set(false)); + SYSMEM_FOR_TEST.with(|c| c.set(false)); } } @@ -11345,6 +11523,70 @@ mod tests { drop(lazy); } + /// Under `XCL_SPARSE_SYSMEM` a lazy tile outside the title's GPU heaps gets its memory from the + /// system-memory pools at its first bytes, as an eager one does, and the bytes reach the GPU. + #[test] + fn a_lazy_tile_outside_the_gpu_heaps_gets_system_memory() { + let lazy = Lazy::on(true); + lazy.sysmem(true); + unsafe { + let Some((base, mut s, queue)) = lazy_state(2) else { return crate::gpu::recomp::runner::skip_test("no GPU with tiled resources tier 2") }; + let eager = base + TILE; + s.ensure_mapped(eager, TILE, |_| (0, 0)); + if s.mapped[&eager].pool.0 & SYS == 0 { + return crate::gpu::recomp::runner::skip_test("no system-memory pool heap"); + } + s.commit_range(base, TILE); + assert_eq!(s.mapped[&base].pool, LAZY); + let dirty = write_tile(base, 11); + s.before_execute_on(&queue, &dirty, PAGE); + assert_ne!(s.mapped[&base].pool.0 & SYS, 0, "its first bytes gave it a system-memory tile"); + let cpu = std::slice::from_raw_parts(base as *const u8, TILE).to_vec(); + assert!(window_bytes(&mut s, base, TILE) == cpu, "the bytes reached the GPU"); + } + drop(lazy); + } + + /// A system-memory tile parked at an address that is a GPU heap of the title by its next commit + /// gives way to a video-memory tile, mapped there before the old one goes (behind the fences), + /// and the heap's bytes reach the GPU through the new one. + #[test] + fn a_parked_system_memory_tile_gives_way_to_a_gpu_heap() { + let eager = Lazy::on(false); + eager.sysmem(true); + unsafe { + let Some((base, mut s, queue)) = lazy_state(1) else { return crate::gpu::recomp::runner::skip_test("no GPU with tiled resources tier 2") }; + s.ensure_mapped(base, TILE, |_| (0, 0)); + let old = s.mapped[&base].pool; + if old.0 & SYS == 0 { + return crate::gpu::recomp::runner::skip_test("no system-memory pool heap"); + } + s.flush_pending(); + s.decommit_range(base, TILE); + assert_eq!(s.parked.get(&base), Some(&old)); + note_hot(base, TILE); + s.ensure_mapped(base, TILE, |_| (0, 0)); + let now = s.mapped[&base].pool; + assert_eq!(now.0 & SYS, 0, "a GPU heap's tile is in video memory"); + assert!(!s.parked.contains_key(&base) && s.pending.is_empty(), "the new mapping went out"); + assert!(s.quarantined.iter().any(|b| b.tiles.contains(&old)), "the old tile waits for the GPU"); + let dirty = write_tile(base, 13); + s.before_execute_on(&queue, &dirty, PAGE); + let cpu = std::slice::from_raw_parts(base as *const u8, TILE).to_vec(); + assert!(window_bytes(&mut s, base, TILE) == cpu, "the bytes reached the GPU"); + // once the GPU is past it, the old tile cools among the system-memory pools: the + // video-memory pools' free table is indexed by heap number, and `SYS` is none + settle_quarantined(&mut s); + assert!(s.quarantined.is_empty(), "the GPU is past the old tile"); + assert!(!s.cooling.iter().any(|&(t, _)| t == old), "not in the video-memory pools' queue"); + assert!(s.free.by_heap.len() <= s.pools.len(), "the video-memory free table keeps its size"); + let sys = (old.0 & !SYS, old.1); + assert!(SYS_POOLS.lock().unwrap().as_ref().is_some_and(|p| p.cooling.iter().any(|&(t, _)| t == sys)), "it cools among the system-memory pools"); + forget_hot(base); + } + drop(eager); + } + /// Bytes that found no video memory at an upload are owed and go up whole once there is some. #[test] fn bytes_that_found_no_memory_go_up_once_there_is_some() { diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 624bee86f1..02cb4d5e9a 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -1015,7 +1015,7 @@ pub unsafe extern "system" fn VirtualAlloc(addr: *const c_void, size: usize, t: // (#505). Costs a second copy in video memory and the write-watch scan of it. if sparse_heaps_min().is_some_and(|min| size >= min) { let rounded = size.max(1).div_ceil(align) * align; - if let Some((q, _)) = crate::hle::d3d12x::sparse::alloc(rounded, align) { + if let Some((q, _)) = crate::hle::d3d12x::sparse::alloc_as(rounded, align, true) { crate::xlog_info!("kernelx: a GPU heap of {} MB in the sparse windows (XCL_COHERENT_HEAPS)", size >> 20); trace_mem("VirtualAlloc (graphics heap, sparse VRAM)", 0, rounded, t as u64, p, q); // nothing of it in the coherent window, noted all the same: a run whose heaps all @@ -1221,6 +1221,7 @@ pub unsafe extern "system" fn VirtualFree(addr: *mut c_void, size: usize, t: u32 mirrors::released(a); forget_title_mappings(a, n); let gone = mirrors::place_gone(a, n); + crate::hle::d3d12x::sparse::forget_hot(a); u.sparse_release(a); // (tiles may show pages kept here) if mirrors::any_mapped() { From 24a84ca327cdbed51c37f2622585b2ea89d77336 Mon Sep 17 00:00:00 2001 From: throny <11830644+throny@users.noreply.github.com> Date: Tue, 1 Dec 2026 19:46:20 +0100 Subject: [PATCH 2/2] D3D12.X: system-memory sparse pools give back heaps whose tiles are all free The system-memory pools of XCL_SPARSE_SYSMEM only grew: unlike the video pools they had no retirement path, so the process kept its peak (about 3.8 GB in our world runs). Review point on #2987: https://github.com/xcl-dev/xcl/pull/2987#discussion_r4759072509 A heap whose 64 tiles are all free or cooled (COOL) is released, and kept alive in a retired list until the sparse queue's fence is past the value it got, as State::retired does for video memory (the tiles' unmaps were already quarantined behind the fences before they cooled). Heap slots become Option so the indexes encoded in tile handles of live heaps do not move; the next heap takes the free slot, and a retired heap is taken back before a new one is created (#913). State::retire_free_pools_with runs it, and the submit path's retire_due also looks at the system pools' cooling queue. Test: a_system_memory_heap_with_all_tiles_free_is_given_back fails with retirement disabled and passes with it. Co-Authored-By: Claude Sonnet 5.5 --- crates/xcl/src/hle/d3d12x/sparse.rs | 115 ++++++++++++++++++++++++++-- 1 file changed, 107 insertions(+), 8 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 00129892df..f31636e5e4 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -489,10 +489,58 @@ const SYS: u32 = 1 << 31; #[derive(Default)] struct SysPools { - heaps: Vec, + /// None: a heap given back (`retire`); its index is taken by the next heap (`add_heap`), the + /// indexes of the live heaps are in the tile handles and never move + heaps: Vec>, /// (by the heap's index without `SYS`: `FreePools` sizes its table by it) free: FreePools, cooling: VecDeque<((u32, u32), std::time::Instant)>, + /// heaps given back, kept until the sparse queue's fence is past the value they got + /// (`State::retired` of the video pools) + retired: Vec<(ID3D12Heap, u64, std::time::Instant)>, +} + +impl SysPools { + /// `heap` becomes a pool (in a given-back heap's index if there is one); its tiles but the + /// first, which the caller takes, go to the free list. + fn add_heap(&mut self, heap: ID3D12Heap) -> u32 { + let h = match self.heaps.iter().position(|p| p.is_none()) { + Some(i) => { + self.heaps[i] = Some(heap); + i as u32 + } + None => { + self.heaps.push(Some(heap)); + self.heaps.len() as u32 - 1 + } + }; + self.free.add_heap(h); + h + } + + /// Heaps whose every tile is free again (cooled, `COOL`) are given back (`State::retire_free_pools_with` + /// does the same for video memory): `value` is the sparse queue's last fence value, `done` what + /// it has reached; a retired heap is dropped once it is past its mark. + fn retire(&mut self, value: u64, done: u64, now: std::time::Instant) { + self.retired.retain(|(_, v, at)| !(done >= *v && now.duration_since(*at).as_secs() >= 2)); + self.free.drain_cooling(&mut self.cooling, now); + let gone: Vec = free_heaps(&self.free, &self.cooling, self.heaps.len(), now).into_iter().filter(|&h| self.heaps[h].is_some()).collect(); + for h in gone { + self.free.clear_heap(h); + if let Some(heap) = self.heaps[h].take() { + self.retired.push((heap, value, now)); + } + } + } + + /// Whether `State::retire_free_pools_with` has something to do here at `now` (`retire_due`). + fn retire_waiting(&self, now: std::time::Instant) -> bool { + !self.retired.is_empty() || self.free.has_empty_heap() || cooled(&self.cooling, now) + } + + fn bytes(&self) -> usize { + self.heaps.iter().flatten().count() * POOL_TILES as usize * TILE + } } // D3D12 heaps are free-threaded @@ -533,7 +581,7 @@ fn is_hot(a: usize) -> bool { /// Bytes of the system-memory pool heaps. pub fn sys_pool_bytes() -> usize { - SYS_POOLS.lock().unwrap().as_ref().map_or(0, |p| p.heaps.len() * POOL_TILES as usize * TILE) + SYS_POOLS.lock().unwrap().as_ref().map_or(0, SysPools::bytes) } /// Whether the oldest tile of `cooling` was freed `COOL` ago or more at `now` @@ -3572,6 +3620,11 @@ impl State { if let Some((h, t)) = reuse_tile(&mut p.free, &mut p.cooling, std::time::Instant::now()) { return Some(((SYS | h, t), true)); } + // a heap given back a moment ago is taken back first (as `take_tile` does) + if let Some((heap, _, _)) = p.retired.pop() { + let h = p.add_heap(heap); + return Some(((SYS | h, 0), true)); + } let desc = D3D12_HEAP_DESC { SizeInBytes: POOL_TILES as u64 * TILE as u64, Properties: D3D12_HEAP_PROPERTIES { @@ -3591,10 +3644,8 @@ impl State { } let heap = heap?; let _ = heap.SetName(windows::core::w!("xcl sparse system-memory pool")); - p.heaps.push(heap); - let h = p.heaps.len() as u32 - 1; - p.free.add_heap(h); - let n = p.heaps.len(); + let h = p.add_heap(heap); + let n = p.heaps.iter().flatten().count(); if n.is_power_of_two() { crate::xlog_info!("sparse windows: {} MB of system-memory pool heaps", n * POOL_TILES as usize * TILE >> 20); } @@ -3610,7 +3661,7 @@ impl State { /// The heap of pool index `h` (video memory, or a system-memory pool with `SYS`). fn pool_heap(&self, h: u32) -> ID3D12Heap { if h & SYS != 0 { - return SYS_POOLS.lock().unwrap().as_ref().expect("system-memory pools").heaps[(h & !SYS) as usize].clone(); + return SYS_POOLS.lock().unwrap().as_ref().expect("system-memory pools").heaps[(h & !SYS) as usize].clone().expect("a pool tile of a live system-memory heap"); } self.pools[h as usize].clone().expect("a pool tile of a live pool") } @@ -3693,6 +3744,9 @@ impl State { let now = std::time::Instant::now(); self.retire_tried = now; self.retired.retain(|(_, v, at)| !(done >= *v && now.duration_since(*at).as_secs() >= 2)); + if let Some(p) = SYS_POOLS.lock().unwrap().as_mut() { + p.retire(self.value, done, now); + } self.free.drain_cooling(&mut self.cooling, now); let gone: Vec = free_heaps(&self.free, &self.cooling, self.pools.len(), now).into_iter().filter(|&h| self.pools[h].is_some()).collect(); if gone.is_empty() { @@ -7896,7 +7950,8 @@ impl State { // cool there: `retire_due` sees them) let flushed = s.flush_parked_with(Some(queue)); s.drain_quarantined_with(|fence| observed_completion(observed, fence, |known, current| known.as_raw() == current.as_raw())); - if flushed || retire_due(&s.cooling, !s.retired.is_empty() || s.free.has_empty_heap(), s.retire_tried, std::time::Instant::now()) { + let sys_waiting = SYS_POOLS.lock().unwrap().as_ref().is_some_and(|p| p.retire_waiting(std::time::Instant::now())); + if flushed || retire_due(&s.cooling, !s.retired.is_empty() || s.free.has_empty_heap() || sys_waiting, s.retire_tried, std::time::Instant::now()) { let sparse_done = observed_completion(observed, &s.fence, |known, current| known.as_raw() == current.as_raw()); s.retire_free_pools_with(sparse_done); } @@ -11587,6 +11642,50 @@ mod tests { drop(eager); } + /// A system-memory heap whose tiles are all free and cooled is given back once the sparse + /// queue's fence is past it; the heaps in use keep their index, and the next heap takes the + /// given-back one's (or the retired heap itself, taken back). + #[test] + fn a_system_memory_heap_with_all_tiles_free_is_given_back() { + unsafe { + let dev = test_device(); + let make = || { + let desc = D3D12_HEAP_DESC { + SizeInBytes: 64 * 1024, + Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + Alignment: 0, + Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS, + }; + let mut heap: Option = None; + dev.CreateHeap(&desc, &mut heap).ok().and(heap) + }; + let (Some(a), Some(b), Some(c)) = (make(), make(), make()) else { return crate::gpu::recomp::runner::skip_test("no heap") }; + let t0 = std::time::Instant::now(); + let at = |s: u64| t0 + std::time::Duration::from_secs(s); + let mut p = SysPools::default(); + // two heaps; the first tile of each was taken by the caller + assert_eq!((p.add_heap(a), p.add_heap(b)), (0, 1)); + let grown = p.bytes(); + assert_eq!(grown, 2 * POOL_TILES as usize * TILE); + // heap 0's taken tile is freed (and cools); heap 1's stays in use + p.cooling.push_back(((0, 0), at(0))); + p.retire(7, 7, at(1)); + assert_eq!(p.bytes(), grown, "still cooling"); + p.retire(7, 7, at(2)); + assert!(p.heaps[0].is_none() && p.heaps[1].is_some(), "heap 0 is given back, heap 1 keeps its index"); + assert_eq!(p.bytes(), grown / 2, "its memory is no longer counted"); + assert_eq!(p.retired.len(), 1, "it is kept until the fence is past it"); + p.retire(7, 6, at(5)); + assert_eq!(p.retired.len(), 1, "the sparse queue's fence is not there yet"); + p.retire(7, 7, at(5)); + assert!(p.retired.is_empty(), "past its mark and 2 s old: dropped"); + // a later heap takes the empty slot, the live one stays + assert_eq!(p.add_heap(c), 0); + assert!(p.heaps.iter().all(|h| h.is_some())); + assert_eq!(p.bytes(), grown); + } + } + /// Bytes that found no video memory at an upload are owed and go up whole once there is some. #[test] fn bytes_that_found_no_memory_go_up_once_there_is_some() {