diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index cae13913f2..fb532258fd 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -3544,6 +3544,8 @@ impl State { } let heap = heap?; let _ = heap.SetName(windows::core::w!("xcl sparse tile pool")); + // (once, when made: a retired pool taken back above keeps the priority it got) + super::vram::set_heap_priority(&self.dev, &heap, super::vram::HeapRole::WindowPool); let h = self.add_pool(heap); Some(((h, 0), false)) } diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 5281099647..3311c24ede 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -971,6 +971,87 @@ pub fn gpu_owned(flags: u32) -> bool { flags & 0x7 != 0 } +/// What one of XCL's own heaps of video memory holds, for its residency priority. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum HeapRole { + /// an arena of render targets and depth buffers (`arena_heap`) + TargetArena, + /// a tile pool of the sparse windows, which hold the title's buffers + WindowPool, + /// a 64 MiB pool of texture pages holding pages of a render target or depth buffer (by + /// default these are placed there, not in an arena: `place`) + TargetPages, + /// a 64 MiB pool of texture pages (`alloc_pool_heap`) + TexturePages, +} + +/// The role a texture with resource flags `flags` gives the pool heaps of its pages. +pub(super) fn pages_role(flags: u32) -> HeapRole { + if gpu_owned(flags) { + HeapRole::TargetPages + } else { + HeapRole::TexturePages + } +} + +/// Of the pool heaps `heaps` (repeats too), those not in `high` yet, in order; `high` then has +/// them, so each heap gets its priority once. +fn newly_high(high: &mut HashSet, heaps: impl IntoIterator) -> Vec { + heaps.into_iter().filter(|&h| high.insert(h)).collect() +} + +/// The residency priority a heap of `role` gets, `None` for the default (`NORMAL`, no call). +/// Over its video memory budget a process has heaps demoted to system memory, and Windows has +/// no hint which matter: what a frame renders to and the title's buffers go before idle pages +/// of textures only by chance. With them `HIGH`, the texture pages go first. +pub(super) fn role_priority(role: HeapRole) -> Option { + match role { + HeapRole::TargetArena | HeapRole::WindowPool | HeapRole::TargetPages => Some(D3D12_RESIDENCY_PRIORITY_HIGH), + HeapRole::TexturePages => None, + } +} + +/// `XCL_RESIDENCY_PRIORITY=1` (read once, off by default): XCL's own heaps get the residency +/// priority of their role (`role_priority`) when they are made; nothing is called per frame. +fn residency_priority_wanted() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| { + let on = std::env::var("XCL_RESIDENCY_PRIORITY").is_ok_and(|v| v.trim() == "1"); + if on { + crate::xlog_info!("D3D12.X: XCL_RESIDENCY_PRIORITY: render-target arenas, window tile pools and texture page pools holding targets get HIGH residency priority, other texture pages NORMAL"); + } + on + }) +} + +/// Gives a new heap of `role` its residency priority when `XCL_RESIDENCY_PRIORITY=1`. A failure +/// is logged (once) and leaves the heap at the default. +pub(super) unsafe fn set_heap_priority(dev: &ID3D12Device, heap: &ID3D12Heap, role: HeapRole) { + if !residency_priority_wanted() { + return; + } + let Some(priority) = role_priority(role) else { return }; + let set = dev.cast::().and_then(|d| { + let obj: ID3D12Pageable = heap.cast()?; + d.SetResidencyPriority(1, &Some(obj), &priority) + }); + if let Err(e) = set { + static WARNED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + if !WARNED.swap(true, std::sync::atomic::Ordering::Relaxed) { + crate::xlog_warn!("D3D12.X: XCL_RESIDENCY_PRIORITY: SetResidencyPriority ({role:?}): {e}"); + } + return; + } + // heaps given HIGH by role (`HeapRole` order), logged at each power of two of the total + use std::sync::atomic::{AtomicU32, Ordering::Relaxed}; + static GIVEN: [AtomicU32; 4] = [AtomicU32::new(0), AtomicU32::new(0), AtomicU32::new(0), AtomicU32::new(0)]; + GIVEN[role as usize].fetch_add(1, Relaxed); + let n = GIVEN.each_ref().map(|c| c.load(Relaxed)); + if (n[0] + n[1] + n[2]).is_power_of_two() { + crate::xlog_info!("D3D12.X: XCL_RESIDENCY_PRIORITY: HIGH given to {} render-target arenas, {} window tile pools, {} texture page pools holding targets", n[0], n[1], n[2]); + } +} + /// A new arena's heap: `size` bytes of video memory for title addresses from `va`. unsafe fn arena_heap(dev: &ID3D12Device, va: usize, size: usize, align: usize) -> Option { let desc = D3D12_HEAP_DESC { @@ -985,6 +1066,9 @@ unsafe fn arena_heap(dev: &ID3D12Device, va: usize, size: usize, align: usize) - crate::xlog_warn!("D3D12.X: video-memory arena for {va:#x}: CreateHeap: {e}"); return None; } + if let Some(h) = &heap { + set_heap_priority(dev, h, HeapRole::TargetArena); + } let made = MADE_BYTES.fetch_add(size, std::sync::atomic::Ordering::Relaxed) + size; static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); let n = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed); @@ -1596,6 +1680,9 @@ unsafe fn alloc_pool_heap(dev: &ID3D12Device) -> Option { crate::xlog_warn!("D3D12.X: no video memory for more pages of title textures ({e})"); return None; } + if let Some(h) = &heap { + set_heap_priority(dev, h, HeapRole::TexturePages); + } heap } @@ -1605,11 +1692,13 @@ struct PoolHeaps { slots: Vec>, free_slots: Vec, live: usize, + /// slots whose heap got `HIGH` for the pages of a target (`Pages::keep_pools`) + high: HashSet, } impl PoolHeaps { fn new() -> Self { - Self { slots: Vec::new(), free_slots: Vec::new(), live: 0 } + Self { slots: Vec::new(), free_slots: Vec::new(), live: 0, high: HashSet::new() } } fn len(&self) -> usize { @@ -1632,6 +1721,7 @@ impl PoolHeaps { fn take_heap(&mut self, idx: u32) -> Option { let h = self.slots.get_mut(idx as usize)?.take()?; self.live -= 1; + self.high.remove(&idx); self.free_slots.push(idx); Some(h) } @@ -2087,6 +2177,21 @@ impl Pages { } } + /// The pool heaps holding the pages `used` / `used_extra` of a texture of `role` + /// (`pages_role`) get its residency priority, each heap once (`newly_high`); a pool of only + /// sampled textures stays at the default. Nothing when `XCL_RESIDENCY_PRIORITY` is off. + unsafe fn keep_pools(&mut self, dev: &ID3D12Device, role: HeapRole, used: &[usize], used_extra: &[(usize, usize)]) { + if !residency_priority_wanted() || role_priority(role).is_none() { + return; + } + let heaps = used.iter().filter_map(|a| self.pages.get(a)).chain(used_extra.iter().filter_map(|k| self.extra_pages.get(k))).map(|p| p.tile.0); + for h in newly_high(&mut self.pools.high, heaps) { + if let Some(heap) = self.pools.get(h as usize) { + set_heap_priority(dev, heap, role); + } + } + } + /// Acquire/share all `total` tiles for `res` at `va` and map them on the `Pages` queue. unsafe fn bind(&mut self, dev: &ID3D12Device, res: &ID3D12Resource, va: usize, console_bytes: Option, total: u32) -> Option<(Vec, Vec<(usize, usize)>)> { self.bind_range(dev, res, va, console_bytes, total, 0, 0..total as usize, false) @@ -2378,6 +2483,7 @@ unsafe fn place_on_pages( pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used: Vec::new(), used_extra: Vec::new(), levels, texels, recycle: recycle_key }); true } else if let Some((used, used_extra)) = pages.bind(dev, res, va, console_bytes, total) { + pages.keep_pools(dev, pages_role(desc.Flags.0 as u32), &used, &used_extra); record_texel_insert(&texels); pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used, used_extra, levels: None, texels, recycle: recycle_key }); true @@ -2507,6 +2613,7 @@ pub(super) unsafe fn remap_if_unmapped(res: &ID3D12Resource) -> bool { let Some((used, used_extra)) = pages.bind(&dev, res, va, console_bytes, total) else { return false; }; + pages.keep_pools(&dev, pages_role(res.GetDesc().Flags.0 as u32), &used, &used_extra); if let Some(t) = pages.targets.get_mut(&key) { t.used = used; t.used_extra = used_extra; @@ -4046,6 +4153,46 @@ mod tests { SRV_TRACKING_FOR_TEST.store(false, std::sync::atomic::Ordering::Relaxed); } + /// Render-target arenas and the windows' tile pools are kept over texture pages: they get + /// `HIGH`, texture pages the default (no call), and nothing gets `MAXIMUM` (the UMA upload + /// segment's, which every console program reads from). + #[test] + fn role_priority_keeps_targets_and_windows_over_texture_pages() { + assert_eq!(role_priority(HeapRole::TargetArena), Some(D3D12_RESIDENCY_PRIORITY_HIGH)); + assert_eq!(role_priority(HeapRole::WindowPool), Some(D3D12_RESIDENCY_PRIORITY_HIGH)); + assert_eq!(role_priority(HeapRole::TargetPages), Some(D3D12_RESIDENCY_PRIORITY_HIGH)); + assert_eq!(role_priority(HeapRole::TexturePages), None); + for role in [HeapRole::TargetArena, HeapRole::WindowPool, HeapRole::TargetPages, HeapRole::TexturePages] { + // (the values are unsigned: HIGH is 0xa0010000, past i32's range) + let p = role_priority(role).unwrap_or(D3D12_RESIDENCY_PRIORITY_NORMAL).0 as u32; + assert!(p >= D3D12_RESIDENCY_PRIORITY_NORMAL.0 as u32 && p < D3D12_RESIDENCY_PRIORITY_MAXIMUM.0 as u32, "{role:?}: {p:#x}"); + } + } + + /// By default a render target or depth buffer goes on texture pages, not in an arena: the + /// pools holding its pages get `HIGH`, each once however many targets it holds, and a pool + /// of only sampled textures keeps the default. + #[test] + fn a_target_on_texture_pages_gets_its_pools_high_once() { + let rt = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET.0 as u32; + let ds = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL.0 as u32; + let uav = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 as u32; + for flags in [rt, ds, uav] { + assert_eq!(pages_role(flags), HeapRole::TargetPages, "{flags:#x}"); + assert_eq!(role_priority(pages_role(flags)), Some(D3D12_RESIDENCY_PRIORITY_HIGH)); + } + assert_eq!(pages_role(D3D12_RESOURCE_FLAG_NONE.0 as u32), HeapRole::TexturePages); + assert_eq!(role_priority(pages_role(D3D12_RESOURCE_FLAG_NONE.0 as u32)), None); + + let mut high = HashSet::new(); + // a target's tiles in pools 3, 3, 5, 3 + assert_eq!(newly_high(&mut high, [3, 3, 5, 3]), vec![3, 5]); + // another target in pools 5 and 7: only 7 is new + assert_eq!(newly_high(&mut high, [5, 7]), vec![7]); + // the same again: no call + assert!(newly_high(&mut high, [3, 5, 7]).is_empty()); + } + #[test] fn title_queue_mapping_wait_reservation_is_monotonic_and_per_queue() { let mut waited = HashMap::new();