From 38bf6a324ac3d11387b81592f3dd5fd6fe38ddac Mon Sep 17 00:00:00 2001 From: LeonardoS11 <311157225+LeonardoS11@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:43:23 -0300 Subject: [PATCH] D3D12.X: an optional page budget evicts CPU-filled title textures LRU The title-texture pages (vram.rs) grow with every 64 KiB page of title memory a texture has ever covered: pool heaps are never released, and a title that recycles texture memory inside its own allocator gives no signal that the old textures are dead. On a retail title that streams its world this reached 9.7 GB of pages (13.7 GB of local video memory on a 12 GB card) and the driver paging stalls set off the title's watchdog. XCL_PAGE_BUDGET_MB caps the pool heaps. At the cap, take_tile evicts the least recently touched textures the CPU fills (placed through place_pages; never GPU-owned targets, never textures the GPU wrote, none under 4 tiles or touched in the last 5 s) and reuses their tiles. An evicted texture is mapped again and uploaded whole when its memory is written again or a submitted transition names it; its content hash is forgotten so the unchanged-upload skip does not leave it out. Unset or 0 keeps the current behaviour. Tests: page_budget_evicts_the_least_recently_touched_cpu_filled_texture (vram.rs, GPU) and a_texture_mapped_again_after_eviction_is_uploaded_even_if_unchanged (title_textures.rs). Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/title_textures.rs | 56 ++++++ crates/xcl/src/hle/d3d12x/vram.rs | 197 +++++++++++++++++++- crates/xcl/src/host.rs | 4 + 3 files changed, 256 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index c35acab94..b8c06997e 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -464,6 +464,9 @@ pub fn note_gpu_write(res: usize) { GPU_WRITTEN.fetch_add(1, Ordering::Relaxed); } } + drop(t); + // page budget: its texels are not in the title's memory, so the page budget keeps it + super::vram::pin(res); } static GPU_WRITTEN: AtomicU64 = AtomicU64::new(0); @@ -570,7 +573,31 @@ pub fn submitted(lists: &[*mut c_void]) { if notes.is_empty() { return; } + // page budget: a texture the title uses is recent; an evicted one is + // mapped again and uploaded whole at the next submit + let mut revive = Vec::new(); + for &(res, _, _) in ¬es { + super::vram::touch(res); + if super::vram::any_evicted() && super::vram::take_evicted(res) { + revive.push(res); + } + } + for &res in &revive { + let p = res as *mut c_void; + if let Some(r) = unsafe { ID3D12Resource::from_raw_borrowed(&p) } { + unsafe { super::vram::remap_if_unmapped(r) }; + } + forget_content(res); + } let mut t = TEXTURES.lock().unwrap(); + for res in revive { + if let Some(e) = t.get_mut(res) { + if !e.pending { + e.pending = true; + PENDING.fetch_add(1, Ordering::Relaxed); + } + } + } for (res, sub, after) in notes { if let Some(e) = t.get_mut(res) { let n = subresource_count(&e.tex); @@ -765,6 +792,16 @@ unsafe fn refresh_once(queue: *mut c_void) { }) .collect() }); + // page budget: a texture the CPU wrote again is mapped again before its + // whole upload + if super::vram::any_evicted() { + for (r, _) in &todo { + if super::vram::take_evicted(r.as_raw() as usize) { + super::vram::remap_if_unmapped(r); + forget_content(r.as_raw() as usize); + } + } + } upload_all(todo); } @@ -784,6 +821,12 @@ fn same_as_last_upload(res: usize, h: u64) -> bool { LAST_CONTENT.lock().unwrap().insert(res, h) == Some(h) } +/// Page budget: `res` was mapped again on fresh tiles, so its next upload +/// must not be left out as unchanged. +fn forget_content(res: usize) { + LAST_CONTENT.lock().unwrap().remove(&res); +} + /// A 64-bit hash of `b` for "the same bytes as before" (four lanes of multiply-rotate over /// 8-byte words: gigabytes a second; not for anything adversarial). fn content_hash(b: &[u8]) -> u64 { @@ -1147,6 +1190,19 @@ mod tests { forget(b); } + /// Page budget: a texture mapped again after an eviction sits on fresh + /// tiles, so unchanged memory is uploaded again. + #[test] + fn a_texture_mapped_again_after_eviction_is_uploaded_even_if_unchanged() { + let a = 0x7E57_0000_3000usize; + let h = content_hash(&[7u8; 4096]); + assert!(!same_as_last_upload(a, h)); + assert!(same_as_last_upload(a, h), "unchanged: left out"); + forget_content(a); + assert!(!same_as_last_upload(a, h), "mapped again: uploaded whole"); + forget_content(a); + } + /// Real uploads, dirty-page detection and a source changing after registration: /// bookkeeping alone cannot show that the bytes the GPU sees follow the mirror. #[test] diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 507c5b696..33b57d8d4 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -166,6 +166,33 @@ const IDLE: std::time::Duration = std::time::Duration::from_secs(2); /// a pool tile given back is not reused before this (the GPU may still be at work on what the /// title released) const COOL: std::time::Duration = std::time::Duration::from_secs(2); +/// Page budget (`XCL_PAGE_BUDGET_MB`): a texture the CPU fills is not evicted before this +/// long after it was placed, remapped or used in a transition. +const EVICT_MIN_AGE: std::time::Duration = std::time::Duration::from_secs(5); +/// Page budget: textures smaller than this are never evicted (UI, fonts, small lookups). +const EVICT_MIN_TILES: u32 = 4; +/// Page budget: tiles freed per eviction round once the pools are at the budget. +const EVICT_BATCH: usize = 512; + +/// Page budget: pool heaps the pages may take, from `XCL_PAGE_BUDGET_MB` (0: no limit). +fn pool_cap() -> usize { + static CAP: std::sync::OnceLock = std::sync::OnceLock::new(); + *CAP.get_or_init(|| { + let mb: usize = std::env::var("XCL_PAGE_BUDGET_MB").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(0); + if mb == 0 { + return 0; + } + let pools = (mb << 20).div_ceil(POOL_PAGES as usize * PAGE).max(1); + crate::xlog_info!("D3D12.X: page budget {mb} MB ({pools} pools of 64 MB): CPU-filled textures are evicted least recently used first beyond it"); + pools + }) +} + +/// Page budget: textures whose tiles were evicted; the next upload or transition maps +/// them again and uploads them whole. +static EVICTED: Mutex>> = Mutex::new(None); +static EVICTIONS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); +static REMAPS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); /// A pool tile: (pool heap, tile in it). type Tile = (u32, u32); @@ -185,6 +212,10 @@ struct Target { mapped: bool, used: Vec, used_extra: Vec<(usize, usize)>, + /// a texture the CPU fills (its texels can be uploaded again from the title's memory) + evictable: bool, + /// placed, remapped or transitioned last + touched: std::time::Instant, } /// The title's pages of video memory for tiled textures (see the module's comment). @@ -262,6 +293,18 @@ impl Pages { if self.cooling.front().is_some_and(|(_, at)| at.elapsed() >= COOL) { return self.cooling.pop_front().map(|(t, _)| t); } + let cap = pool_cap(); + if cap > 0 && self.pools.len() >= cap { + self.evict_lru(EVICT_BATCH); + if let Some(t) = self.free.pop() { + return Some(t); + } + // at the budget a tile is reused before it cooled: a draw still in flight may read + // the newer texels there for a frame + if let Some((t, _)) = self.cooling.pop_front() { + return Some(t); + } + } let desc = D3D12_HEAP_DESC { SizeInBytes: POOL_PAGES as u64 * PAGE as u64, Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, @@ -362,6 +405,48 @@ impl Pages { } } + /// Page budget: unmap CPU-filled textures, least recently touched first, until `want` + /// tiles came back (pages other mapped textures still share stay). Each goes to `EVICTED`. + unsafe fn evict_lru(&mut self, want: usize) { + let now = std::time::Instant::now(); + let before = self.free.len() + self.cooling.len(); + let mut order: Vec<(std::time::Instant, usize)> = self + .targets + .iter() + .filter(|(_, t)| t.evictable && t.mapped && t.total >= EVICT_MIN_TILES && now.duration_since(t.touched) >= EVICT_MIN_AGE) + .map(|(&k, t)| (t.touched, k)) + .collect(); + order.sort_unstable(); + let mut evicted = Vec::new(); + for (_, key) in order { + if self.free.len() + self.cooling.len() - before >= want { + break; + } + let Some(t) = self.targets.get_mut(&key) else { continue }; + let total = t.total; + let used = std::mem::take(&mut t.used); + let used_extra = std::mem::take(&mut t.used_extra); + t.mapped = false; + let raw = key as *mut c_void; + if let Some(res) = ID3D12Resource::from_raw_borrowed(&raw) { + self.unmap(res, total); + } + self.release_tiles(used, used_extra, now, true); + evicted.push(key); + } + if !evicted.is_empty() { + let n = EVICTIONS.fetch_add(evicted.len() as u64, std::sync::atomic::Ordering::Relaxed) + evicted.len() as u64; + let freed = self.free.len() + self.cooling.len() - before; + static LOGGED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let step = LOGGED.load(std::sync::atomic::Ordering::Relaxed); + if n >= step { + LOGGED.store(n.max(1) * 2, std::sync::atomic::Ordering::Relaxed); + crate::xlog_info!("D3D12.X: page budget: {} textures evicted ({} MB back) this round, {n} so far", evicted.len(), (freed * PAGE) >> 20); + } + EVICTED.lock().unwrap().get_or_insert_with(HashSet::new).extend(evicted); + } + } + /// 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)>)> { let (first, own) = (total > 0).then(|| owned_pages(va, console_bytes, total as usize)).flatten()?; @@ -494,7 +579,7 @@ unsafe fn place_on_pages( *ppv = std::ptr::null_mut(); return None; }; - pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used, used_extra }); + pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used, used_extra, evictable: !require_aligned, touched: std::time::Instant::now() }); drop(g); PLACED_TEXTURES.lock().unwrap().get_or_insert_with(HashSet::new).insert(raw as usize); Some(hr) @@ -544,10 +629,58 @@ pub(super) unsafe fn remap_if_unmapped(res: &ID3D12Resource) -> bool { t.used = used; t.used_extra = used_extra; t.mapped = true; + t.touched = std::time::Instant::now(); } true } +/// Page budget: `res` was evicted by the page budget; true once, and the caller maps it +/// again (`remap_if_unmapped`) and uploads it whole. +pub(super) fn take_evicted(res: usize) -> bool { + let mut g = EVICTED.lock().unwrap(); + let hit = g.as_mut().is_some_and(|s| s.remove(&res)); + if hit { + REMAPS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + hit +} + +/// Page budget: whether any texture is evicted (callers skip the lookup otherwise). +pub(super) fn any_evicted() -> bool { + EVICTED.lock().unwrap().as_ref().is_some_and(|s| !s.is_empty()) +} + +/// Page budget: `res` was used (a transition the title submitted): later to be evicted. +pub(super) fn touch(res: usize) { + if pool_cap() == 0 { + return; + } + let mut g = PAGES.lock().unwrap(); + for pages in g.values_mut().flatten() { + if let Some(t) = pages.targets.get_mut(&res) { + t.touched = std::time::Instant::now(); + return; + } + } +} + +/// Page budget: the GPU wrote `res`; its texels are not in the title's memory, so it is +/// never evicted. +pub(super) fn pin(res: usize) { + let mut g = PAGES.lock().unwrap(); + for pages in g.values_mut().flatten() { + if let Some(t) = pages.targets.get_mut(&res) { + t.evictable = false; + return; + } + } +} + +/// Page budget: (textures evicted, textures mapped again) so far. +pub fn eviction_counts() -> (u64, u64) { + (EVICTIONS.load(std::sync::atomic::Ordering::Relaxed), REMAPS.load(std::sync::atomic::Ordering::Relaxed)) +} + /// A resource released: its pages are no longer its. fn forget_pages(resource: usize) { let mut g = PAGES.lock().unwrap(); @@ -557,6 +690,10 @@ fn forget_pages(resource: usize) { if t.mapped { pages.release_tiles(t.used, t.used_extra, now, false); } + drop(g); + if let Some(s) = EVICTED.lock().unwrap().as_mut() { + s.remove(&resource); + } return; } } @@ -875,4 +1012,62 @@ mod tests { drop(last); } } + + /// Page budget: the least recently touched CPU-filled texture gives its + /// pages back first, a GPU-written one never does, and an evicted one maps again. + #[test] + fn page_budget_evicts_the_least_recently_touched_cpu_filled_texture() { + let _vram_guard = VRAM_TEST_LOCK.lock().unwrap(); + use windows::core::Interface; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::Common::*; + use windows::Win32::Graphics::Dxgi::*; + unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory1().expect("DXGI factory"); + let Ok(adapter) = factory.EnumAdapters1(0) else { return }; + if adapter.GetDesc1().is_ok_and(|d| d.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0) { + return; + } + let mut dev: Option = None; + let _ = D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_11_0, &mut dev); + let Some(dev) = dev.filter(|d| tier2(d)) else { return }; + super::super::real::adopt(dev.as_raw(), super::super::real::Kind::Device); + let desc = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: 512, Height: 512, DepthOrArraySize: 1, MipLevels: 1, Format: DXGI_FORMAT_R8G8B8A8_UNORM, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, ..Default::default() }; + let riid = &ID3D12Resource::IID as *const windows::core::GUID as *const windows_sys::core::GUID; + let place_at = |va: usize| { + let mut p = std::ptr::null_mut(); + let hr = place_pages(dev.as_raw(), va, &desc, D3D12_RESOURCE_STATE_COMMON.0 as u32, std::ptr::null(), Some(1 << 20), riid, &mut p); + if !hr.is_some_and(|hr| hr >= 0) || p.is_null() { + return None; + } + Some(ID3D12Resource::from_raw(p)) + }; + let (Some(old), Some(newer), Some(written)) = (place_at(0x60_0000_0000), place_at(0x60_1000_0000), place_at(0x60_2000_0000)) else { + crate::gpu::recomp::runner::skip_test("no reserved textures"); + return; + }; + let key = |r: &ID3D12Resource| r.as_raw() as usize; + pin(key(&written)); + let dev_key = dev.as_raw() as usize; + let now = Instant::now(); + { + let mut g = PAGES.lock().unwrap(); + let pages = g.get_mut(&dev_key).unwrap().as_mut().unwrap(); + for (r, age) in [(&old, 30), (&newer, 20), (&written, 40)] { + pages.targets.get_mut(&key(r)).unwrap().touched = now - Duration::from_secs(age); + } + let used_before = pages.pages.len(); + pages.evict_lru(1); + assert!(!pages.targets[&key(&old)].mapped, "the oldest CPU-filled texture is evicted"); + assert!(pages.targets[&key(&newer)].mapped, "one is enough for one tile"); + assert!(pages.targets[&key(&written)].mapped, "a GPU-written texture is never evicted"); + assert!(pages.pages.len() < used_before, "its pages went back"); + } + assert!(take_evicted(key(&old))); + assert!(!take_evicted(key(&old)), "true once"); + assert!(remap_if_unmapped(&old)); + assert!(PAGES.lock().unwrap().get(&dev_key).unwrap().as_ref().unwrap().targets[&key(&old)].mapped, "mapped again"); + drop((old, newer, written)); + } + } } diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index ba5dcb473..7d809391c 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -73,6 +73,10 @@ pub fn host_main(boot_path: &Path) -> i32 { mb(pools as u64), mb(pools_mapped as u64) ); + let (evicted, mapped_again) = crate::hle::d3d12x::vram::eviction_counts(); + if evicted > 0 { + crate::xlog_info!("page budget: {evicted} textures evicted, {mapped_again} mapped again"); + } last = now; } });