diff --git a/crates/xcl/src/hle/d3d12x/console_heap.rs b/crates/xcl/src/hle/d3d12x/console_heap.rs index 176973ea2..51023dda5 100644 --- a/crates/xcl/src/hle/d3d12x/console_heap.rs +++ b/crates/xcl/src/hle/d3d12x/console_heap.rs @@ -389,6 +389,42 @@ pub fn resource_at(at: usize) -> Option { RES.lock().unwrap().as_ref()?.get(&at).copied() } +/// shared-heap SRV index → the texture on pages its view names (page budget, census). A T# +/// keeps that index wherever the title copies it, so the slots holding it name the texture. +static INDEX_RES: Mutex>> = Mutex::new(None); + +/// The SRV made for slot `s` names `res`, a texture on pages. False: the slot's heap is not +/// in the shared heap, so its T# cannot be followed. +pub fn note_index(s: &Slot, res: usize) -> bool { + if s.sampler || s.shared_srv == 0 { + return false; + } + INDEX_RES.lock().unwrap().get_or_insert_with(Default::default).insert(s.index, res); + true +} + +/// The textures on pages whose T# is in a slot now: (in a shader-visible view heap, only in +/// CPU-only ones). +pub fn referenced() -> (Vec, Vec) { + let index = INDEX_RES.lock().unwrap(); + let Some(index) = index.as_ref().filter(|m| !m.is_empty()) else { return (Vec::new(), Vec::new()) }; + let heaps = HEAPS.lock().unwrap(); + let (mut visible, mut cpu) = (std::collections::HashSet::new(), std::collections::HashSet::new()); + for h in heaps.iter().filter(|h| !h.sampler) { + let set = if h.visible { &mut visible } else { &mut cpu }; + for k in 0..h.n { + let w = unsafe { std::slice::from_raw_parts((h.shadow + (k * SLOT) as usize) as *const u32, 4) }; + if w[3] >> 28 >= 8 { + if let Some(&r) = index.get(&w[0]) { + set.insert(r); + } + } + } + } + let cpu = cpu.difference(&visible).copied().collect(); + (visible.into_iter().collect(), cpu) +} + pub fn write(s: &Slot, words: &[u32]) { let n = words.len().min(if s.sampler { 4 } else { 8 }); unsafe { std::ptr::copy_nonoverlapping(words.as_ptr(), s.at as *mut u32, n) }; @@ -504,6 +540,32 @@ mod tests { assert!(free.is_empty()); } + #[test] + fn textures_are_referenced_by_the_heaps_their_t_is_in() { + let Some(_) = crate::gpu::uma::get() else { return }; + let (a, b, c) = (0x7FFF_0001u32, 0x7FFF_0003, 0x7FFF_0005); + INDEX_RES.lock().unwrap().get_or_insert_with(Default::default).extend([(a, 0xAAA0), (b, 0xBBB0), (c, 0xCCC0)]); + assert!(register(0xC1, 4, 0x2000, 0x6000, 32, false, false, true)); + assert!(register(0xC2, 4, 0x3000, 0, 32, false, false, false)); + let (v, cpu) = (start(0xC1).unwrap(), start(0xC2).unwrap()); + let image = |i: u32| [i, 0x0470_0000, 0, 9 << 28, 0, 0, 0, 0]; + // a: in both kinds of heap; b: only in the CPU-only one; c: as a buffer V#'s word 0 + write(&slot(v).unwrap(), &image(a)); + write(&slot(v + 32).unwrap(), &[c, 0, 64, 0x3101_6FAC, 0, 0, 0, 0]); + write(&slot(cpu).unwrap(), &image(a)); + write(&slot(cpu + 32).unwrap(), &image(b)); + let (visible, cpu_only) = referenced(); + assert!(visible.contains(&0xAAA0) && !visible.contains(&0xBBB0) && !visible.contains(&0xCCC0), "{visible:x?}"); + assert!(cpu_only.contains(&0xBBB0) && !cpu_only.contains(&0xAAA0) && !cpu_only.contains(&0xCCC0), "{cpu_only:x?}"); + unregister(0xC1); + unregister(0xC2); + if let Some(m) = INDEX_RES.lock().unwrap().as_mut() { + for i in [a, b, c] { + m.remove(&i); + } + } + } + #[test] fn slots_copy_and_release() { let Some(u) = crate::gpu::uma::get() else { return }; diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 26019155e..d7fdc337c 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -1994,6 +1994,12 @@ unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void, f(this, res, desc, slot.pc_srv); super::console_heap::publish(&slot, false); super::console_heap::note_resource(&slot, res as usize); + if super::vram::tracking() && super::vram::is_placed_texture(res as usize) { + // a view the heaps cannot be followed to: never taken for unused + if !super::console_heap::note_index(&slot, res as usize) { + super::vram::pin(res as usize); + } + } if super::present::trace_frame() && super::title_textures::address(res as usize).is_some() { static N: AtomicU64 = AtomicU64::new(0); if N.fetch_add(1, Ordering::Relaxed) < 24 { diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index c35acab94..af1a93639 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); @@ -557,6 +560,58 @@ pub fn list_reset(list: usize) { } } +/// Page budget: evicted textures `revive` are mapped again and uploaded whole at the next look. +/// One that could not be mapped stays evicted, for the next use to try again. +fn map_again(revive: &[usize]) { + let mut mapped = Vec::with_capacity(revive.len()); + for &res in revive { + // released since it was taken from the evicted (its pages forgotten): not touched + if !super::vram::is_placed_texture(res) { + continue; + } + let p = res as *mut c_void; + if !unsafe { ID3D12Resource::from_raw_borrowed(&p).is_some_and(|r| super::vram::remap_if_unmapped(r)) } { + super::vram::evicted_again(res); + continue; + } + forget_content(res); + mapped.push(res); + } + if mapped.is_empty() { + return; + } + let mut t = TEXTURES.lock().unwrap(); + for res in mapped { + if let Some(e) = t.get_mut(res) { + if !e.pending { + e.pending = true; + PENDING.fetch_add(1, Ordering::Relaxed); + } + } + } +} + +/// Page budget: about once a second, the textures whose T# is in a shader-visible view heap +/// are in use (a title that only samples a texture submits no transition for it); evicted ones +/// among them are mapped again before the title's next work. +fn look_at_view_heaps() { + if !super::vram::tracking() || super::console_heap::global_heap().is_none() { + return; + } + static LAST: Mutex> = Mutex::new(None); + { + let mut last = LAST.lock().unwrap(); + let now = std::time::Instant::now(); + if last.is_some_and(|l| now.duration_since(l) < std::time::Duration::from_secs(1)) { + return; + } + *last = Some(now); + } + let (visible, cpu_only) = super::console_heap::referenced(); + let back = super::vram::seen(&visible, &cpu_only); + map_again(&back); +} + /// The PC lists `lists` were submitted, in this order: the textures kept in step are in the /// states their transitions leave them in. pub fn submitted(lists: &[*mut c_void]) { @@ -570,6 +625,16 @@ 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); + } + } + map_again(&revive); let mut t = TEXTURES.lock().unwrap(); for (res, sub, after) in notes { if let Some(e) = t.get_mut(res) { @@ -727,6 +792,9 @@ unsafe fn refresh_once(queue: *mut c_void) { crate::xlog_info!("frame trace: title textures: {with} with data in memory, {without} all zero; {dirty_len} dirty pages this look"); } } + // page budget: textures in use by their T#; evicted ones are mapped again (before the + // queue waits for the mappings) and uploaded below + look_at_view_heaps(); // the title's own memory: what the CPU wrote goes to its video memory first if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) { DIRTY_BUF.with(|dcell| { @@ -765,6 +833,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 +862,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 +1231,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..7800b5595 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -166,6 +166,42 @@ 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); +/// Page budget: textures with no T# in any view heap (while the heaps are looked at) may be +/// evicted this long after they were placed or last seen, small ones too. +const EVICT_UNSEEN_AGE: std::time::Duration = std::time::Duration::from_secs(2); +/// whether the console view heaps are looked at (`seen`): only then does "no T#" mean unused +static HEAPS_LOOKED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +/// Page budget: after a round that gave back fewer tiles than wanted (the rest of the +/// candidates' pages are shared), the next is not tried for this long: every tile taken at the +/// budget would otherwise sort and walk the same textures again. +const EVICT_RETRY: std::time::Duration = std::time::Duration::from_secs(1); /// A pool tile: (pool heap, tile in it). type Tile = (u32, u32); @@ -185,6 +221,20 @@ 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, transitioned or its T# seen in a shader-visible heap last + touched: std::time::Instant, + /// where the last look at the view heaps found its T# (`seen`) + seen: Seen, +} + +/// Where a texture's T# was at the last look at the console view heaps. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Seen { + None, + CpuOnly, + Visible, } /// The title's pages of video memory for tiled textures (see the module's comment). @@ -206,6 +256,8 @@ struct Pages { targets: std::collections::HashMap, /// queue → the fence value it last waited for waited: std::collections::HashMap, + /// no eviction round before this (`EVICT_RETRY`) + evict_after: Option, } // D3D12 objects are free-threaded @@ -237,6 +289,7 @@ impl Pages { extra_pages: std::collections::HashMap::new(), targets: std::collections::HashMap::new(), waited: std::collections::HashMap::new(), + evict_after: None, }) } @@ -262,6 +315,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 +427,72 @@ 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`. + /// After a round that fell short, none for `EVICT_RETRY`. + unsafe fn evict_lru(&mut self, want: usize) { + let now = std::time::Instant::now(); + if self.evict_after.is_some_and(|t| now < t) { + return; + } + let before = self.free.len() + self.cooling.len(); + // with the view heaps looked at, a texture whose T# is in none cannot be sampled: it + // goes first, small or not, once `EVICT_UNSEEN_AGE` old + let heaps = HEAPS_LOOKED.load(std::sync::atomic::Ordering::Relaxed); + let mut order: Vec<(bool, std::time::Instant, usize)> = self + .targets + .iter() + .filter_map(|(&k, t)| { + if !t.evictable || !t.mapped { + return None; + } + let unseen = heaps && t.seen == Seen::None; + let age = now.duration_since(t.touched); + let ok = if unseen { age >= EVICT_UNSEEN_AGE } else { t.total >= EVICT_MIN_TILES && age >= EVICT_MIN_AGE }; + ok.then_some((!unseen, t.touched, k)) + }) + .collect(); + order.sort_unstable(); + let mut evicted = Vec::new(); + let mut shared = 0u64; + for (_, _, key) in order { + if self.free.len() + self.cooling.len() - before >= want { + break; + } + let Some(t) = self.targets.get(&key) else { continue }; + // a texture whose pages all are other mapped textures' too gives nothing back + let alone = t.used.iter().any(|a| self.pages.get(a).is_some_and(|p| p.users <= 1)) + || t.used_extra.iter().any(|k| self.extra_pages.get(k).is_some_and(|p| p.users <= 1)); + if !alone { + shared += 1; + continue; + } + 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); + } + let freed = self.free.len() + self.cooling.len() - before; + self.evict_after = (freed < want).then(|| now + EVICT_RETRY); + if !evicted.is_empty() { + let n = EVICTIONS.fetch_add(evicted.len() as u64, std::sync::atomic::Ordering::Relaxed) + evicted.len() as u64; + 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; {shared} passed over, all their pages shared", 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 +625,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(), seen: Seen::None }); drop(g); PLACED_TEXTURES.lock().unwrap().get_or_insert_with(HashSet::new).insert(raw as usize); Some(hr) @@ -544,10 +675,102 @@ 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`, taken from the evicted, could not be mapped again: evicted still. +pub(super) fn evicted_again(res: usize) { + if is_placed_texture(res) { + EVICTED.lock().unwrap().get_or_insert_with(HashSet::new).insert(res); + REMAPS.fetch_sub(1, std::sync::atomic::Ordering::Relaxed); + } +} + +/// 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()) +} + +/// Whether the page budget follows the use of textures. +pub(super) fn tracking() -> bool { + pool_cap() != 0 +} + +/// Page budget: the T# of the textures `visible` is in a shader-visible view heap (they may be +/// sampled: recent now), that of `cpu_only` only in CPU-only heaps. Returns the evicted ones of +/// `visible`, which the caller maps again and uploads before the title's next work. +pub(super) fn seen(visible: &[usize], cpu_only: &[usize]) -> Vec { + let now = std::time::Instant::now(); + HEAPS_LOOKED.store(true, std::sync::atomic::Ordering::Relaxed); + let mut g = PAGES.lock().unwrap(); + for pages in g.values_mut().flatten() { + for t in pages.targets.values_mut() { + t.seen = Seen::None; + } + for r in visible { + if let Some(t) = pages.targets.get_mut(r) { + t.touched = now; + t.seen = Seen::Visible; + } + } + for r in cpu_only { + if let Some(t) = pages.targets.get_mut(r) { + t.seen = Seen::CpuOnly; + } + } + } + drop(g); + let mut e = EVICTED.lock().unwrap(); + let Some(e) = e.as_mut().filter(|s| !s.is_empty()) else { return Vec::new() }; + let back: Vec = visible.iter().copied().filter(|r| e.remove(r)).collect(); + REMAPS.fetch_add(back.len() as u64, std::sync::atomic::Ordering::Relaxed); + back +} + +/// Page budget: `res` was used (a transition the title submitted): later to be evicted. +pub(super) fn touch(res: usize) { + if !tracking() { + 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 +780,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 +1102,123 @@ 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_takes_unseen_textures_first_and_passes_over_shared_pages() { + 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)) + }; + // two textures at the same address share every page + let (Some(a), Some(b), Some(unseen), Some(own)) = (place_at(0x61_0000_0000), place_at(0x61_0000_0000), place_at(0x61_1000_0000), place_at(0x61_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(); + HEAPS_LOOKED.store(true, std::sync::atomic::Ordering::Relaxed); + { + let mut g = PAGES.lock().unwrap(); + let pages = g.get_mut(&dev_key).unwrap().as_mut().unwrap(); + for (r, age, seen) in [(&a, 60, Seen::CpuOnly), (&b, 60, Seen::CpuOnly), (&unseen, 3, Seen::None), (&own, 30, Seen::CpuOnly)] { + let t = pages.targets.get_mut(&key(r)).unwrap(); + t.touched = now - Duration::from_secs(age); + t.seen = seen; + } + pages.evict_lru(1); + assert!(!pages.targets[&key(&unseen)].mapped, "a texture with no T# goes first, though younger"); + assert!(pages.targets[&key(&a)].mapped && pages.targets[&key(&b)].mapped && pages.targets[&key(&own)].mapped); + pages.evict_lru(1); + assert!(pages.targets[&key(&a)].mapped && pages.targets[&key(&b)].mapped, "shared pages give nothing back: passed over"); + assert!(!pages.targets[&key(&own)].mapped, "the next with pages of its own is evicted"); + assert!(pages.evict_after.is_none(), "rounds that gave back what was wanted are not held back"); + pages.evict_lru(usize::MAX); + assert!(pages.evict_after.is_some_and(|t| t > Instant::now()), "a round that fell short holds the next back"); + assert!(pages.targets[&key(&a)].mapped && pages.targets[&key(&b)].mapped); + } + HEAPS_LOOKED.store(false, std::sync::atomic::Ordering::Relaxed); + assert!(take_evicted(key(&unseen)) && take_evicted(key(&own))); + drop((a, b, unseen, own)); + } + } + + #[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; } });