From 813778957e7acdb610e7d79fdddf682a4a899716 Mon Sep 17 00:00:00 2001 From: Raul Paiva <63853678+Raul-Paiva@users.noreply.github.com> Date: Sat, 28 Nov 2026 19:35:55 +0000 Subject: [PATCH] D3D12.X: XCL's render-target arenas and window pools get a residency priority On an 8 GB card a retail title's world holds about 16 GB of local video memory against a 7.25 GB DXGI budget (10 GB with the lazy sparse and level-page switches). Windows then demotes allocations to system memory with no hint which matter, so what a frame renders to can be paged out while idle texture pages stay. XCL never called SetResidencyPriority on its own heaps (only #3007's GPU_UPLOAD segment, under XCL_UMA_DRIVER=mixed). With XCL_RESIDENCY_PRIORITY=1 (read once, off by default so it can be measured) each heap gets the priority of its role once, with nothing per frame: - render-target / depth arenas (vram.rs arena_heap): HIGH, when made - tile pools of the sparse windows, which hold the title's buffers (sparse.rs take_tile): HIGH, when made; a retired pool taken back keeps it - 64 MiB texture page pools holding pages of a render target, depth buffer or UAV texture: HIGH, once per pool, when the target is mapped onto it (Pages::keep_pools, from place_on_pages and remap_if_unmapped). By default `place` puts these targets on texture pages, not in arenas (arenas only with XCL_VRAM_ARENAS=1 or for a target that cannot be reserved), so without this the switch gave HIGH to no target at all. A reclaimed pool's slot forgets it; a pool keeps HIGH after its target leaves. - other texture page pools (vram.rs alloc_pool_heap): NORMAL, the default, so no call None gets MAXIMUM, which stays #3007's. The mapping is pure (role_priority, pages_role, newly_high) with unit tests; a failed call is logged once and leaves the heap at the default. The heaps given HIGH are counted by role and logged at each power of two of the total. andrewDoing's test report on the PR found that with the default backing policy render, depth and UAV targets went on texture pages and the switch issued no HIGH call; only XCL_VRAM_ARENAS=1 gave the arenas HIGH. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/sparse.rs | 2 + crates/xcl/src/hle/d3d12x/vram.rs | 149 +++++++++++++++++++++++++++- 2 files changed, 150 insertions(+), 1 deletion(-) 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();