From 5d6fac8cb6c1ccddf95adc273862e5cb4be5ae2a 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 first takes the tiles the last eviction round gave back; only when there are none does it evict the least recently touched textures title_textures keeps in step with the title's memory (never GPU-owned targets, never textures the GPU wrote, none under 4 tiles or touched in the last 5 s) until 512 tiles came back. A round that finds nothing to evict is not repeated for a second (EVICT_IDLE): the pools grow past the budget meanwhile. Without that, every tile of a big texture walked all live targets (62 000 on the retail title) and held the title's CreatePlacedResourceX thread long enough for its stall watchdog. An evicted texture is mapped again before the work that uses it: before a submit whose lists transition it (revive_listed, ahead of refresh, so that submit uploads it whole), when the CPU wrote it again (before its upload), and when a copy into it is recorded (no upload over the GPU's texels). A failed remap keeps it evicted. Its content hash is forgotten so the unchanged-upload skip does not leave it out. Uploads and submitted transitions refresh the LRU time. Evicting unmaps a texture from another thread, which is safe only while a texture's last Release reaches vram::forget before the object goes, so the budget requires late release. Unset or 0 keeps the current behaviour. Tests (GPU): page_budget_evicts_the_least_recently_touched_cpu_filled_texture and page_budget_one_placement_at_the_cap_evicts_one_batch (vram.rs; the second fails without the take-from-the-batch-first change: 40 textures evicted instead of 32), and page_budget_an_evicted_texture_is_mapped_again_before_the_work_that_uses_it (title_textures.rs). Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/list_x.rs | 7 +- crates/xcl/src/hle/d3d12x/real.rs | 6 +- crates/xcl/src/hle/d3d12x/title_textures.rs | 146 ++++++++ crates/xcl/src/hle/d3d12x/vram.rs | 348 +++++++++++++++++++- crates/xcl/src/host.rs | 4 + 5 files changed, 507 insertions(+), 4 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 794c418ab..8f4f3f50e 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -2756,13 +2756,18 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { } let q_raw = queue as *mut c_void; - super::title_textures::refresh(q_raw); type ExecFn = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void); let exec: ExecFn = transmute_copy(&real::orig_fn(q_raw, PC_QUEUE_EXECUTE_COMMAND_LISTS)); // If this list was previously split mid-recording around a `Wait64`, flush all earlier closed // segments in exact order before submitting `this`, then resume recording on `primary`. let kickoff_split = super::title_list::reclaim_for_kickoff(this); + // page budget: evicted textures this list and the segments before it transition are mapped + // again, uploaded by the refresh + let mut lists = kickoff_split.as_ref().map_or_else(Vec::new, |(_, prior, _)| prior.clone()); + lists.push(this); + super::title_textures::revive_listed(&lists); + super::title_textures::refresh(q_raw); if let Some((_, ref prior, _)) = kickoff_split { if !prior.is_empty() { execute_with_waits_on(q_raw, prior, |chunk| { diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 5b01e8569..f0e65738b 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -5085,8 +5085,6 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis stop_if_device_removed(); return; } - // textures in title memory the CPU wrote since: uploaded again first - super::title_textures::refresh(this); // console-shaped lists run as the PC lists they were translated into (split title lists expand // into all of their recorded PC segments in exact chronological order) let mut mapped: Vec<*mut c_void> = Vec::with_capacity(n as usize); @@ -5097,6 +5095,10 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis mapped.push(l); } } + // page budget: evicted textures these lists transition are mapped again, uploaded below + super::title_textures::revive_listed(&mapped); + // textures in title memory the CPU wrote since: uploaded again first + super::title_textures::refresh(this); super::list_x::note_queue_for_lists(this as usize, &mapped); super::list_x::execute_with_waits_on(this, &mapped, |chunk| { f(this, chunk.len() as u32, chunk.as_ptr()); diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index ada439cba..d8c83ac28 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -393,6 +393,8 @@ pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, super::vram::unmap_superseded(r); } TEXTURES_GEN.fetch_add(1, Ordering::Release); + // page budget: its texels can be uploaded again from the title's memory + super::vram::set_evictable(res as usize); Ok(()) } @@ -464,6 +466,17 @@ 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; one + // already evicted is mapped again now, before the copy runs (the title's queue waits for + // the mapping), and is not uploaded (`gpu_written`). The title holds it while it records. + super::vram::pin(res); + if super::vram::any_evicted() { + let p = res as *mut c_void; + if let Some(r) = unsafe { ID3D12Resource::from_raw_borrowed(&p) } { + unsafe { super::vram::revive(r) }; + } + } } static GPU_WRITTEN: AtomicU64 = AtomicU64::new(0); @@ -570,6 +583,8 @@ pub fn submitted(lists: &[*mut c_void]) { if notes.is_empty() { return; } + // page budget: a texture the title uses is recent + super::vram::touch(notes.iter().map(|&(res, _, _)| res)); let mut t = TEXTURES.lock().unwrap(); for (res, sub, after) in notes { if let Some(e) = t.get_mut(res) { @@ -579,6 +594,46 @@ pub fn submitted(lists: &[*mut c_void]) { } } +/// Page budget: before the PC lists `lists` are submitted (and before `refresh`), the evicted +/// textures their transitions name are mapped again and made pending, so this submit uploads +/// them whole before the lists sample them. +pub(super) fn revive_listed(lists: &[*mut c_void]) { + if !super::vram::any_evicted() { + return; + } + let mut named: Vec = { + let g = LIST_NOTES.lock().unwrap(); + lists.iter().filter_map(|&l| g.get(&(l as usize))).flatten().map(|&(res, _, _)| res).filter(|&res| super::vram::is_evicted(res)).collect() + }; + if named.is_empty() { + return; + } + named.sort_unstable(); + named.dedup(); + // a reference each while they are mapped (taken under the lock `forget` takes) + let live = { + let t = TEXTURES.lock().unwrap(); + named.retain(|res| t.by_res.contains_key(res) || t.shadowed.contains_key(res)); + unsafe { clone_resources(&named) } + }; + let revived: Vec = live.iter().filter(|r| unsafe { super::vram::revive(r) }).map(|r| r.as_raw() as usize).collect(); + if revived.is_empty() { + return; + } + for &res in &revived { + forget_content(res); + } + let mut t = TEXTURES.lock().unwrap(); + for res in revived { + if let Some(e) = t.get_mut(res) { + if !e.pending && !e.gpu_written { + e.pending = true; + PENDING.fetch_add(1, Ordering::Relaxed); + } + } + } +} + /// Subresources of a texture kept in step (as `subresources` makes them). fn subresource_count(tex: &xg::Texture) -> usize { tex.texels().map_or(1, |s| s.array as usize * s.chain.levels.len()) @@ -776,6 +831,23 @@ unsafe fn refresh_once(queue: *mut c_void) { }) .collect() }); + // page budget: a texture the CPU wrote again is recent, and one evicted is mapped again + // before its whole upload (one that cannot be mapped now stays evicted and is not uploaded) + let mut todo = todo; + if super::vram::any_evicted() { + todo.retain(|(r, _)| { + let key = r.as_raw() as usize; + if !super::vram::is_evicted(key) { + return true; + } + let back = super::vram::revive(r); + if back { + forget_content(key); + } + back + }); + } + super::vram::touch(todo.iter().map(|(r, _)| r.as_raw() as usize)); upload_all(todo); } @@ -795,6 +867,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 { @@ -1219,6 +1297,74 @@ mod tests { forget(b); } + /// Page budget: before a submit, an evicted texture its lists transition is mapped again and + /// uploaded whole (pending, its content hash forgotten), and a copy into an evicted texture + /// maps it again when it is recorded, with no upload over what the GPU writes (#640 review). + #[test] + fn page_budget_an_evicted_texture_is_mapped_again_before_the_work_that_uses_it() { + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8_UNORM, DXGI_SAMPLE_DESC}; + let _vram_guard = super::super::vram::VRAM_TEST_LOCK.lock().unwrap(); + let _guard = TEST_LOCK.lock().unwrap(); + if super::super::backend() != super::super::Backend::Real { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + unsafe { + let dev = super::super::real::device_raw(); + // 512 x 512 R8: 4 tiles, the smallest texture the budget evicts + let pc = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: 512, Height: 512, DepthOrArraySize: 1, MipLevels: 1, Format: DXGI_FORMAT_R8_UNORM, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, ..Default::default() }; + let console = console_desc(3, 512, 512, 1, 1, DXGI_FORMAT_R8_UNORM.0 as u32, 1); + 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 = super::super::vram::place_pages(dev, va, &pc, D3D12_RESOURCE_STATE_COMMON.0 as u32, std::ptr::null(), Some(512 * 512), riid, &mut p); + if !hr.is_some_and(|hr| hr >= 0) || p.is_null() { + return None; + } + Some(ID3D12Resource::from_raw(p)) + }; + let (Some(sampled), Some(copied)) = (place_at(0x63_0000_0000), place_at(0x63_1000_0000)) else { + crate::gpu::recomp::runner::skip_test("no reserved textures"); + return; + }; + let (a, b) = (sampled.as_raw() as usize, copied.as_raw() as usize); + register(dev, sampled.as_raw(), 0x63_0000_0000, &console, D3D12_RESOURCE_STATE_COMMON).unwrap(); + register(dev, copied.as_raw(), 0x63_1000_0000, &console, D3D12_RESOURCE_STATE_COMMON).unwrap(); + { + // both uploaded once already + let mut t = TEXTURES.lock().unwrap(); + for r in [a, b] { + let e = t.get_mut(r).unwrap(); + if e.pending { + e.pending = false; + PENDING.fetch_sub(1, Ordering::Relaxed); + } + } + } + LAST_CONTENT.lock().unwrap().insert(a, 7); + assert!(super::super::vram::evict_for_test(a) && super::super::vram::evict_for_test(b)); + + // a list that samples `a` is submitted: `a` is mapped again first, and uploaded whole + let list = 0x7E57_0640usize; + LIST_NOTES.lock().unwrap().entry(list).or_default().push((a, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE)); + revive_listed(&[list as *mut c_void]); + assert!(!super::super::vram::is_evicted(a), "mapped again before the submit"); + assert!(TEXTURES.lock().unwrap().get_mut(a).unwrap().pending, "its upload runs in this submit's refresh"); + assert!(!LAST_CONTENT.lock().unwrap().contains_key(&a), "not left out as unchanged"); + + // a copy into `b` is recorded: mapped again now, and not uploaded over + assert!(super::super::vram::is_evicted(b)); + note_gpu_write(b); + assert!(!super::super::vram::is_evicted(b), "mapped again before the copy runs"); + assert!(!TEXTURES.lock().unwrap().get_mut(b).unwrap().pending, "the GPU's texels are not uploaded over"); + + list_reset(list); + forget(a); + forget(b); + drop((sampled, copied)); + } + } + /// 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 040d78a0c..5689652cd 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -166,6 +166,44 @@ 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: after a round that found nothing to evict, pools grow past the budget for this +/// long instead of trying again for every tile. +const EVICT_IDLE: std::time::Duration = std::time::Duration::from_secs(1); + +/// 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; + } + // evicting unmaps a texture from another thread: only safe while a texture's last + // Release reaches `forget` before the object goes (`late_release` holds it until then) + if !super::late_release::enabled() { + crate::xlog_warn!("D3D12.X: XCL_PAGE_BUDGET_MB needs late release (XCL_LATE_RELEASE=0 is set): no page budget"); + 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); +/// the number of textures in `EVICTED` (callers skip the lookup while it is 0) +static EVICTED_LEN: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +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); @@ -218,6 +256,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). @@ -241,6 +283,10 @@ struct Pages { targets: std::collections::HashMap, /// queue → the fence value it last waited for waited: std::collections::HashMap, + /// page budget: no eviction round before this (the last one found nothing to evict) + evict_idle_until: Option, + /// page budget: pool heaps the pages may take (`pool_cap`; 0: no limit) + cap: usize, } // D3D12 objects are free-threaded @@ -273,6 +319,8 @@ impl Pages { idle: std::collections::VecDeque::new(), targets: std::collections::HashMap::new(), waited: std::collections::HashMap::new(), + evict_idle_until: None, + cap: pool_cap(), }) } @@ -288,6 +336,23 @@ impl Pages { if self.cooling.front().is_some_and(|(_, at)| at.elapsed() >= COOL) { return self.cooling.pop_front().map(|(t, _)| t); } + if self.cap > 0 && self.pools.len() >= self.cap { + // one round gives back a batch of tiles (to `cooling`), which the next tiles take + // first; a round that found nothing to evict is not repeated for a second: each one + // walks every target, and a texture of many tiles asks once per tile + let now = std::time::Instant::now(); + if self.cooling.is_empty() && self.evict_idle_until.is_none_or(|t| now >= t) && self.evict_lru(EVICT_BATCH) == 0 { + self.evict_idle_until = Some(now + EVICT_IDLE); + } + 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() }, @@ -390,6 +455,52 @@ 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) -> 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); + } + let mut g = EVICTED.lock().unwrap(); + let s = g.get_or_insert_with(HashSet::new); + s.extend(evicted); + EVICTED_LEN.store(s.len(), std::sync::atomic::Ordering::Relaxed); + } + self.free.len() + self.cooling.len() - before + } + /// 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()?; @@ -553,7 +664,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: false, touched: std::time::Instant::now() }); drop(g); PLACED_TEXTURES.lock().unwrap().get_or_insert_with(HashSet::new).insert(raw as usize); Some(hr) @@ -603,10 +714,87 @@ 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. +pub(super) fn is_evicted(res: usize) -> bool { + any_evicted() && EVICTED.lock().unwrap().as_ref().is_some_and(|s| s.contains(&res)) +} + +/// Page budget: map `res` again if the page budget evicted it. True when it was evicted and is +/// mapped again (the caller uploads it whole); a failed remap leaves it evicted, to be tried +/// again at its next write, transition or copy. +pub(super) unsafe fn revive(res: &ID3D12Resource) -> bool { + let key = res.as_raw() as usize; + if !is_evicted(key) || !remap_if_unmapped(res) { + return false; + } + let mut g = EVICTED.lock().unwrap(); + let Some(s) = g.as_mut() else { return false }; + if !s.remove(&key) { + return false; + } + EVICTED_LEN.store(s.len(), std::sync::atomic::Ordering::Relaxed); + REMAPS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + true +} + +/// Page budget: whether any texture is evicted (callers skip the lookup otherwise). +pub(super) fn any_evicted() -> bool { + EVICTED_LEN.load(std::sync::atomic::Ordering::Relaxed) != 0 +} + +/// Page budget: the textures `res` were used (a transition the title submitted, a CPU write +/// uploaded): later to be evicted. +pub(super) fn touch(res: impl IntoIterator) { + if pool_cap() == 0 { + return; + } + let now = std::time::Instant::now(); + let mut g = PAGES.lock().unwrap(); + for r in res { + for pages in g.values_mut().flatten() { + if let Some(t) = pages.targets.get_mut(&r) { + t.touched = now; + break; + } + } + } +} + +/// Page budget: `res` is a texture `title_textures` keeps in step with the title's memory, so +/// its texels can be uploaded again after an eviction. +pub(super) fn set_evictable(res: usize) { + set_evictable_to(res, true); +} + +/// 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) { + set_evictable_to(res, false); +} + +fn set_evictable_to(res: usize, on: bool) { + 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.evictable = on; + 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(); @@ -616,6 +804,11 @@ 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); + EVICTED_LEN.store(s.len(), std::sync::atomic::Ordering::Relaxed); + } return; } } @@ -639,6 +832,22 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) { #[cfg(test)] pub(super) static VRAM_TEST_LOCK: Mutex<()> = Mutex::new(()); +/// Page budget, for tests: evict `res` now (as the least recently touched texture the CPU +/// fills); whether it was. +#[cfg(test)] +pub(super) unsafe fn evict_for_test(res: usize) -> bool { + let mut g = PAGES.lock().unwrap(); + for pages in g.values_mut().flatten() { + if let Some(t) = pages.targets.get_mut(&res) { + t.evictable = true; + t.touched = std::time::Instant::now().checked_sub(std::time::Duration::from_secs(600)).unwrap(); + pages.evict_lru(1); + return pages.targets.get(&res).is_some_and(|t| !t.mapped); + } + } + false +} + #[cfg(test)] pub(super) fn page_bytes_for(device: usize) -> (usize, usize) { let g = PAGES.lock().unwrap(); @@ -1032,4 +1241,141 @@ 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; + 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(); + // (`set_evictable` / `pin` do nothing without XCL_PAGE_BUDGET_MB) + for (r, age, evictable) in [(&old, 30, true), (&newer, 20, true), (&written, 40, false)] { + let t = pages.targets.get_mut(&key(r)).unwrap(); + t.touched = now - Duration::from_secs(age); + t.evictable = evictable; + } + let used_before = pages.pages.len(); + assert!(pages.evict_lru(1) > 0, "tiles came back"); + 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"); + // nothing left to evict: the round says so (take_tile then waits before the next) + pages.targets.get_mut(&key(&newer)).unwrap().evictable = false; + assert_eq!(pages.evict_lru(1), 0, "nothing evictable"); + } + assert!(is_evicted(key(&old)) && !is_evicted(key(&newer))); + assert!(revive(&old), "mapped again"); + assert!(!is_evicted(key(&old)) && !revive(&old), "once"); + assert!(PAGES.lock().unwrap().get(&dev_key).unwrap().as_ref().unwrap().targets[&key(&old)].mapped, "mapped again"); + drop((old, newer, written)); + } + } + + /// Page budget: at the cap, one texture placed evicts one batch, and its other tiles come + /// from that batch – not one more round per tile (#640 review: one placement evicted every + /// eligible texture). + #[test] + fn page_budget_one_placement_at_the_cap_evicts_one_batch() { + 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); + // 512 x 512 RGBA8: 16 tiles each + 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)) + }; + // 40 x 16 = 640 tiles: more than one batch of 512 + let old: Vec = (0..40).filter_map(|i| place_at(0x61_0000_0000 + i * 0x10_0000)).collect(); + if old.len() != 40 { + crate::gpu::recomp::runner::skip_test("no reserved textures"); + return; + } + let key = |r: &ID3D12Resource| r.as_raw() as usize; + let dev_key = dev.as_raw() as usize; + let now = Instant::now(); + let (saved_free, saved_cooling) = { + let mut g = PAGES.lock().unwrap(); + let pages = g.get_mut(&dev_key).unwrap().as_mut().unwrap(); + for (i, r) in old.iter().enumerate() { + let t = pages.targets.get_mut(&key(r)).unwrap(); + t.touched = now - Duration::from_secs(100 - i as u64); + t.evictable = true; + } + // at the cap with no spare tile: the next tile has to come from an eviction + pages.cap = pages.pools.len(); + pages.evict_idle_until = None; + (std::mem::take(&mut pages.free), std::mem::take(&mut pages.cooling)) + }; + let new = place_at(0x61_8000_0000); + let mapped: Vec = { + let mut g = PAGES.lock().unwrap(); + let pages = g.get_mut(&dev_key).unwrap().as_mut().unwrap(); + let mapped = old.iter().map(|r| pages.targets[&key(r)].mapped).collect(); + pages.cap = 0; + pages.free.extend(saved_free); + pages.cooling.extend(saved_cooling); + mapped + }; + assert!(new.is_some(), "placed from the evicted tiles"); + let evicted = mapped.iter().filter(|m| !**m).count(); + assert_eq!(evicted, 32, "one batch of 512 tiles: the 32 least recently touched"); + assert!(mapped[..32].iter().all(|m| !m) && mapped[32..].iter().all(|m| *m), "oldest first"); + for r in &old { + let _ = revive(r); + } + drop((old, new)); + } + } } 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; } });