diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index cae13913f2..c9c38d37e2 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.) @@ -3633,7 +3751,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()), @@ -3799,8 +3917,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; @@ -3848,11 +3968,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; @@ -3861,7 +3999,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; @@ -3882,7 +4020,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(); @@ -4886,9 +5029,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; } @@ -4920,6 +5073,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() } @@ -5894,7 +6048,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()); } } @@ -5980,7 +6134,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; } } @@ -8455,6 +8609,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 @@ -10316,6 +10472,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; @@ -11260,11 +11433,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)); } } @@ -11343,6 +11521,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/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 5281099647..77329e7c40 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -1582,6 +1582,59 @@ impl TilePool { } } +/// `XCL_TEXTURE_SYSMEM=1` (off by default; with `level_pages`): the levels of streamed textures +/// get their pages from pool heaps in system memory (custom heaps in L0, which the GPU samples +/// over PCIe); render targets and other textures keep video memory. A page of those heaps has +/// `SYS_TILE` in its heap index. +const SYS_TILE: u32 = 1 << 31; + +fn texture_sysmem() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| { + let on = level_pages() && std::env::var("XCL_TEXTURE_SYSMEM").is_ok_and(|v| v.trim() == "1"); + if on { + crate::xlog_info!("D3D12.X: XCL_TEXTURE_SYSMEM=1 - the levels of streamed textures in system memory"); + } + on + }) +} + +/// One 64 MiB system-memory heap for the pages of streamed texture levels (`texture_sysmem`). +unsafe fn alloc_sys_pool_heap(dev: &ID3D12Device) -> Option { + let desc = D3D12_HEAP_DESC { + SizeInBytes: POOL_PAGES as u64 * PAGE 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_NONE, + }; + let mut heap: Option = None; + if let Err(e) = super::title_textures::own_work(|| dev.CreateHeap(&desc, &mut heap)) { + crate::xlog_warn!("D3D12.X: no system-memory pool heap for texture levels ({e})"); + return None; + } + heap +} + +/// The pool a freed page's tile cools in: the system-memory pools for one with `SYS_TILE`. +fn tile_is_sys(tile: Tile) -> bool { + tile.0 & SYS_TILE != 0 +} + +/// A page's tile freed at `at` cools in its own pools: `sys_pool` (by its index there) for one +/// with `SYS_TILE`, else `pool`. +fn cool_in(pool: &mut TilePool, sys_pool: &mut TilePool, tile: Tile, at: std::time::Instant) { + if tile_is_sys(tile) { + sys_pool.push_cooling((tile.0 & !SYS_TILE, tile.1), at); + } else { + pool.push_cooling(tile, at); + } +} + /// Allocate one 64 MiB default heap for `Pages`. unsafe fn alloc_pool_heap(dev: &ID3D12Device) -> Option { let desc = D3D12_HEAP_DESC { @@ -1688,6 +1741,9 @@ struct Pages { /// pool heaps by `Tile` index (a reclaimed one's slot is empty, as `TilePool::live` has it) pools: PoolHeaps, pool: TilePool, + /// the system-memory pools of streamed texture levels (`texture_sysmem`; indices without `SYS_TILE`) + sys_pools: PoolHeaps, + sys_pool: TilePool, /// title page address → its video memory pages: std::collections::HashMap, /// extra / sub-64 KiB tiles keyed by `(va, tile_index)` so repeated placements at the same @@ -1846,6 +1902,8 @@ impl Pages { last_reclaim: std::time::Instant::now(), pools: PoolHeaps::new(), pool: TilePool::new(), + sys_pools: PoolHeaps::new(), + sys_pool: TilePool::new(), pages: std::collections::HashMap::new(), extra_pages: std::collections::HashMap::new(), idle: std::collections::VecDeque::new(), @@ -1865,7 +1923,11 @@ impl Pages { /// Pages no resource used for `IDLE` go back to the pools. fn sweep(&mut self, now: std::time::Instant) { - sweep_idle(&mut self.idle, &mut self.pages, &mut self.extra_pages, &mut self.pool.cooling, now); + let mut cooled = std::collections::VecDeque::new(); + sweep_idle(&mut self.idle, &mut self.pages, &mut self.extra_pages, &mut cooled, now); + for (t, at) in cooled { + self.cool(t, at); + } } /// Sweep expired idle pages, drain cooled tiles, and reclaim any completely empty 64 MiB @@ -1874,6 +1936,7 @@ impl Pages { fn sweep_and_reclaim(&mut self, now: std::time::Instant) -> Vec { self.sweep(now); self.pool.drain_cooling(now); + self.sys_pool.drain_cooling(now); let reclaimed_ids = self.pool.reclaim_empty_heaps(keep_spare_pools(), POOL_PAGES); let mut dropped = Vec::with_capacity(reclaimed_ids.len()); for idx in reclaimed_ids { @@ -1905,7 +1968,8 @@ impl Pages { for i in 0..self.scratch_heaps.len() { let h = self.scratch_heaps[i]; // (a tile is only ever of a heap the pool has: `TilePool::reclaim_empty_heaps`) - let Some(heap) = self.pools.get(h as usize) else { continue }; + let heap = if tile_is_sys((h, 0)) { self.sys_pools.get((h & !SYS_TILE) as usize) } else { self.pools.get(h as usize) }; + let Some(heap) = heap else { continue }; let ranges = heap_ranges_trimmed(h, tiles); if ranges.is_empty() { continue; @@ -2054,6 +2118,11 @@ impl Pages { done } + /// A page's tile freed: it cools in its own pools. + fn cool(&mut self, tile: Tile, at: std::time::Instant) { + cool_in(&mut self.pool, &mut self.sys_pool, tile, at); + } + fn release_tiles(&mut self, used: Vec, used_extra: Vec<(usize, usize)>, now: std::time::Instant, immediate_cool: bool) { for a in used { if let Some(p) = self.pages.get_mut(&a) { @@ -2061,7 +2130,7 @@ impl Pages { if p.users == 0 { if immediate_cool { if let Some(p) = self.pages.remove(&a) { - self.pool.push_cooling(p.tile, now); + self.cool(p.tile, now); } } else { p.idle_since = Some(now); @@ -2076,7 +2145,7 @@ impl Pages { if p.users == 0 { if immediate_cool { if let Some(p) = self.extra_pages.remove(&k) { - self.pool.push_cooling(p.tile, now); + self.cool(p.tile, now); } } else { p.idle_since = Some(now); @@ -2097,6 +2166,15 @@ impl Pages { unsafe fn bind_range( &mut self, dev: &ID3D12Device, res: &ID3D12Resource, va: usize, console_bytes: Option, total: u32, sub: u32, range: std::ops::Range, evictable: bool, + ) -> Option<(Vec, Vec<(usize, usize)>)> { + self.bind_range_in(dev, res, va, console_bytes, total, sub, range, evictable, false) + } + + /// `bind_range`, its new pages from the system-memory pools with `sys` (`texture_sysmem`). + #[allow(clippy::too_many_arguments)] + unsafe fn bind_range_in( + &mut self, dev: &ID3D12Device, res: &ID3D12Resource, va: usize, + console_bytes: Option, total: u32, sub: u32, range: std::ops::Range, evictable: bool, sys: bool, ) -> Option<(Vec, Vec<(usize, usize)>)> { let (first, own) = (total > 0).then(|| owned_pages(va, console_bytes, total as usize)).flatten()?; let now = std::time::Instant::now(); @@ -2111,18 +2189,33 @@ impl Pages { self.extra_pages.get(&(va, i)).map(|p| p.tile.0) }; match existing { - Some(h) if preferred.is_none() => preferred = Some(h), + Some(h) if preferred.is_none() && tile_is_sys((h, 0)) == sys => preferred = Some(h & !SYS_TILE), Some(_) => {} None => missing += 1, } } - let pools = &mut self.pools; - let pool = &mut self.pool; - let fresh = pool.take_batch(missing, preferred, evictable, now, POOL_PAGES, || { - let heap = alloc_pool_heap(dev)?; - Some(pools.push_heap(heap)) - })?; + // (with `sys` the system-memory pools; none there: video memory, as without it) + let fresh = if sys { + let pools = &mut self.sys_pools; + self.sys_pool.take_batch(missing, preferred, evictable, now, POOL_PAGES, || { + let heap = alloc_sys_pool_heap(dev)?; + Some(pools.push_heap(heap)) + }).map(|v| v.into_iter().map(|(h, t)| (h | SYS_TILE, t)).collect::>()) + } else { + None + }; + let fresh = match fresh { + Some(f) => f, + None => { + let pools = &mut self.pools; + let pool = &mut self.pool; + pool.take_batch(missing, preferred.filter(|_| !sys), evictable, now, POOL_PAGES, || { + let heap = alloc_pool_heap(dev)?; + Some(pools.push_heap(heap)) + })? + } + }; let mut fresh_iter = fresh.into_iter(); let mut tiles = Vec::with_capacity(range.len()); @@ -3014,7 +3107,7 @@ pub(super) unsafe fn map_levels(res: &ID3D12Resource, levels: Option<&[u32]>) -> let Some(dev) = ID3D12Device::from_raw_borrowed(&d) else { return Vec::new() }; let mut fresh = Vec::new(); for (k, sub, first, n, levels) in todo { - let Some((used, used_extra)) = pages.bind_range(dev, res, va, console_bytes, total, sub, first as usize..(first + n) as usize, false) else { continue }; + let Some((used, used_extra)) = pages.bind_range_in(dev, res, va, console_bytes, total, sub, first as usize..(first + n) as usize, false, texture_sysmem()) else { continue }; let Some(t) = pages.targets.get_mut(&key) else { return fresh }; if let Some(l) = t.levels.as_mut() { l.groups[k].3 = true; @@ -4061,6 +4154,27 @@ mod tests { const MIB: usize = 1 << 20; + /// A page of the system-memory pools (`SYS_TILE`) is told apart from one of video memory with + /// the same heap slot, and each, freed, cools in its own pools, by its index there. + #[test] + fn a_system_memory_page_is_told_apart_and_cools_in_its_own_pool() { + let video: Tile = (7, 3); + let system: Tile = (SYS_TILE | 7, 3); + assert!(!tile_is_sys(video) && tile_is_sys(system)); + let (mut pool, mut sys_pool) = (TilePool::new(), TilePool::new()); + pool.add_heap_at(7, POOL_PAGES, false); + sys_pool.add_heap_at(7, POOL_PAGES, false); + let t0 = std::time::Instant::now(); + cool_in(&mut pool, &mut sys_pool, video, t0); + cool_in(&mut pool, &mut sys_pool, system, t0); + assert_eq!(pool.cooling.iter().map(|&(t, _)| t).collect::>(), vec![video]); + assert_eq!(sys_pool.cooling.iter().map(|&(t, _)| t).collect::>(), vec![(7, 3)], "by its index there"); + let (free, sys_free) = (pool.free_total, sys_pool.free_total); + pool.drain_cooling(t0 + COOL); + sys_pool.drain_cooling(t0 + COOL); + assert_eq!((pool.free_total, sys_pool.free_total), (free + 1, sys_free + 1), "each back in its own pool"); + } + /// The levels of a texture with lazy levels: a group of tiles for each level with tiles of its /// own and one for the packed levels; a level past the last standard one is in the packed /// group; a tiling that does not add up to the resource's tiles gives none. diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 50d95b0f6e..15ffddfda8 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() {