From 8111cf945fb38f53a4856edfb63bcba46b524b29 Mon Sep 17 00:00:00 2001 From: TG0000 <122870448+TG0000@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:08:30 +0100 Subject: [PATCH] D3D12.X: kept-in-step title textures on shared 64 KiB pages of video memory (#248) A texture the CPU fills (kept in step with title memory) placed at a 64 KiB aligned address is now a reserved resource on 64 KiB pages of video memory, one per page of the title's address, shared by every such texture placed there - as on the console, where a texture placed over another overwrites its memory. A committed PC texture per placement, never let go, held the sum of every texture a streaming title ever placed (12.7 GB over 4.0 GB of its memory at 90 s, then 0x887a0007). - vram: page bookkeeping in a plain Book (unit-tested); textures and GPU-owned targets in separate spaces, so a texture's CPU-view upload never overwrites what the GPU rendered into a target at the same address. - title_textures: uploads oldest placement first (the newest texture's texels win on shared pages); the upload queue waits for tile mappings. - device_x: pages first, committed as before when a texture cannot be reserved (unaligned address, 3D on tier 2, driver refusal). XCL_TITLE_TEXTURE_PAGES=0 turns it off. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/device_x.rs | 23 +- crates/xcl/src/hle/d3d12x/title_textures.rs | 45 +- crates/xcl/src/hle/d3d12x/vram.rs | 429 +++++++++++++++----- 3 files changed, 395 insertions(+), 102 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index e79381093..17614e759 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -890,11 +890,32 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, return hr; } } + // a texture the CPU fills: on the title's pages of such textures (`vram`), shared with the + // ones placed there before as on the console, else a committed texture of its own + let mut kept = if buffer { Err(String::new()) } else { super::title_textures::layout(&x) }; + let on_pages = kept.as_ref().ok().map(|t| t.size()).filter(|_| !super::vram::gpu_owned(flags)); + if let Some(console_bytes) = on_pages { + let pc = std::ptr::read_unaligned(d.as_ptr() as *const D3D12_RESOURCE_DESC); + if let Some(hr) = super::vram::place_title_texture(this, va as usize, &pc, state, console_bytes, riid, ppv) { + let res = *ppv; + let tex = std::mem::replace(&mut kept, Err(String::new())); + if tex.and_then(|t| super::title_textures::register(this, res, va as usize, t, D3D12_RESOURCE_STATES(state as i32))).is_ok() { + real::note_title_address(res as usize, va as usize); + return hr; + } + // (not kept in step: the pages are not its own – a resource of its own instead) + if !res.is_null() { + drop(windows::core::IUnknown::from_raw(res)); + } + *ppv = std::ptr::null_mut(); + kept = super::title_textures::layout(&x); + } + } let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; let hr = real::dev_create_committed_resource(this, &heap as *const _ as usize, 0, d.as_ptr() as usize, state as usize, clear as usize, riid, ppv); if hr >= 0 && !buffer && !(*ppv).is_null() { static M: AtomicU64 = AtomicU64::new(0); - match super::title_textures::register(this, *ppv, va as usize, &x, D3D12_RESOURCE_STATES(state as i32)) { + match kept.and_then(|tex| super::title_textures::register(this, *ppv, va as usize, tex, D3D12_RESOURCE_STATES(state as i32))) { Ok(()) => { real::note_title_address(*ppv as usize, va as usize); return hr; diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 2d8194e75..1e170a5c6 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -19,6 +19,11 @@ //! transitions of these textures are noted per PC command list as they are recorded //! (`note_transitions`) and applied, in submission order, when the list is submitted //! (`submitted`) – per subresource once a transition names one. +//! +//! The PC texture is a reserved resource on 64 KiB pages of video memory, one per page of the +//! title's address, shared by every such texture placed there (`vram::place_title_texture`) – +//! a title streaming its world places new textures over the old ones' memory; where it cannot +//! be (an address not 64 KiB aligned, a texture the driver does not reserve) it is committed. use std::collections::BTreeMap; use std::ffi::c_void; @@ -54,8 +59,15 @@ struct Entry { /// the title's GPU work wrote it (CopyTextureRegion into it): its CPU view is stale from /// then on and no longer uploaded gpu_written: bool, + /// the order it was placed in: textures placed over the same memory share its video memory + /// (`vram::place_title_texture`), and as on the console the newest one's texels are what it + /// holds – uploads go oldest first + seq: u64, } +/// the next texture's `Entry::seq` +static SEQ: AtomicU64 = AtomicU64::new(0); + /// textures waiting for their first upload static PENDING: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); @@ -80,8 +92,9 @@ pub fn counts() -> (usize, u64) { (TEXTURES.lock().unwrap().len(), UPLOADS.load(Ordering::Relaxed)) } -/// A texture the title placed at `va` (its console desc `desc`): kept in step with the memory. -pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, desc: &[u8; 0x38], state: D3D12_RESOURCE_STATES) -> Result<(), String> { +/// The console layout of a texture the title places (its console desc `desc`) when it can be +/// kept in step with the memory (`register`); Err: why not. +pub(super) fn layout(desc: &[u8; 0x38]) -> Result { let tex = xg::Texture::new(desc).map_err(|hr| format!("layout {hr:#x}"))?; // the console's 32-bit 116 / 117 floats are half floats on the PC (`pc_resource_desc`): the // title's bytes are not the resource's texels @@ -110,13 +123,20 @@ pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, static N: AtomicU64 = AtomicU64::new(0); let n = N.fetch_add(1, Ordering::Relaxed) + 1; if n <= 2 || n.is_power_of_two() { - crate::xlog_info!("D3D12.X: a small render target at {va:#x} ({} planes) is kept in step with the title's memory – a glyph cache the CPU fills ({n} so far)", tex.planes.len()); + crate::xlog_info!("D3D12.X: a small render target ({} planes) is kept in step with the title's memory – a glyph cache the CPU fills ({n} so far)", tex.planes.len()); } } + Ok(tex) +} + +/// A texture the title placed at `va` (its console layout `tex`, from `layout`): kept in step +/// with the memory. +pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, tex: xg::Texture, state: D3D12_RESOURCE_STATES) -> Result<(), String> { if ID3D12Resource::from_raw_borrowed(&res).is_none() { return Err("no resource".into()); } - let e = Entry { device: device as usize, va, tex: Arc::new(tex), states: vec![state], pending: true, gpu_written: false }; + let seq = SEQ.fetch_add(1, Ordering::Relaxed); + let e = Entry { device: device as usize, va, tex: Arc::new(tex), states: vec![state], pending: true, gpu_written: false, seq }; { let mut t = TEXTURES.lock().unwrap(); if let Some(old) = t.insert(res as usize, e) { @@ -392,7 +412,7 @@ unsafe fn refresh_once(queue: *mut c_void) { } // textures made since the last submit and those with a written page; a reference each // while they are uploaded - let todo: Vec<(ID3D12Resource, Upload)> = DIRTY_BUF.with(|dcell| { + let mut todo: Vec<(u64, ID3D12Resource, Upload)> = DIRTY_BUF.with(|dcell| { let dirty = dcell.borrow(); let mut t = TEXTURES.lock().unwrap(); t.iter_mut() @@ -412,11 +432,18 @@ unsafe fn refresh_once(queue: *mut c_void) { PENDING.fetch_sub(1, Ordering::Relaxed); } let p = res as *mut c_void; - ID3D12Resource::from_raw_borrowed(&p).map(|r| (r.clone(), (e.device, e.va, Arc::clone(&e.tex), e.states.clone()))) + ID3D12Resource::from_raw_borrowed(&p).map(|r| (e.seq, r.clone(), (e.device, e.va, Arc::clone(&e.tex), e.states.clone()))) }) .collect() }); - upload_all(todo); + upload_all(in_placement_order(&mut todo)); +} + +/// The uploads `todo` (placement order, PC texture, upload) oldest placement first: where +/// textures share video memory the newest one's upload is the last word. +fn in_placement_order(todo: &mut Vec<(u64, R, U)>) -> Vec<(R, U)> { + todo.sort_unstable_by_key(|t| t.0); + todo.drain(..).map(|(_, r, u)| (r, u)).collect() } /// staging bytes of one batch at most @@ -457,6 +484,8 @@ unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>) { continue; } }; + // textures on pages: their tiles' mappings come first + super::vram::before_execute(&queue); match own_work(|| texture::upload_batch(dev, &queue, &batch)) { Ok(failed) => { for (_, e) in failed { @@ -710,7 +739,7 @@ mod tests { assert_eq!(subresource_count(&tex), 6); // fake resource / list keys, never dereferenced: GPU-written, so no refresh uploads it let (res, other, l1, l2) = (0x7E57_0000_1000usize, 0x7E57_0000_2000usize, 0x7E57_0000_3000usize, 0x7E57_0000_4000usize); - TEXTURES.lock().unwrap().insert(res, Entry { device: 0, va: 0x7E57_0000_0000, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: true }); + TEXTURES.lock().unwrap().insert(res, Entry { device: 0, va: 0x7E57_0000_0000, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: true, seq: 0 }); TEXTURES_LEN.fetch_add(1, Ordering::Relaxed); let states = || TEXTURES.lock().unwrap().get(&res).unwrap().states.clone(); let (p1, p2) = (l1 as *mut c_void, l2 as *mut c_void); diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index dcca9ecb8..9b6c05891 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -22,6 +22,11 @@ //! Arenas remain for what cannot be tiled (an address not 64 KiB aligned, a resource the //! driver does not make reserved: D32S8, MSAA): heaps of the placement's size, shared by //! placements inside them, let go 2 s after their last resource (256 MiB ones: 2.8 GB of D32S8). +//! +//! Textures the CPU fills (kept in step with the title's memory, `title_textures`) go on pages +//! the same way, in a space of their own (`Space`): a title streaming its world places new +//! textures over memory it used before and lets few of the old ones go, and a committed texture +//! per placement held the sum of every texture ever placed (#248). use std::collections::HashSet; use std::ffi::c_void; @@ -170,28 +175,133 @@ const COOL: std::time::Duration = std::time::Duration::from_secs(2); /// A pool tile: (pool heap, tile in it). type Tile = (u32, u32); +/// Which resources share a title page's video memory. GPU-owned targets share with targets, +/// textures kept in step with the title's memory (`title_textures`) with such textures: their +/// uploads are the CPU's view of the memory, which over a target's page would overwrite what +/// the GPU rendered there (on the console the memory holds it; here the CPU's view does not). +#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] +pub(super) enum Space { + Targets, + Textures, +} + struct Page { tile: Tile, - /// targets using the page + /// resources using the page users: u32, /// when the last of them went idle_since: Option, } -/// The title's pages of video memory for GPU-owned textures (see the module's comment). +/// Which pool tile backs which title page, and which resource uses which pages – apart from +/// D3D12 (a new pool heap is the `grow` callback's). +struct Book { + free: Vec, + /// tiles given back, reusable after `COOL` + cooling: std::collections::VecDeque<(Tile, std::time::Instant)>, + /// (space, title page address) → its video memory + pages: std::collections::HashMap<(Space, usize), Page>, + /// resource → (its space, the title pages it uses, tiles of its own past the title's memory) + users: std::collections::HashMap, Vec)>, +} + +impl Book { + fn new() -> Book { + Book { free: Vec::new(), cooling: std::collections::VecDeque::new(), pages: std::collections::HashMap::new(), users: std::collections::HashMap::new() } + } + + /// Pages no resource used for `IDLE` go back to the pools. + fn sweep(&mut self, now: std::time::Instant) { + let old: Vec<(Space, usize)> = self.pages.iter().filter(|(_, p)| p.idle_since.is_some_and(|t| now.duration_since(t) >= IDLE)).map(|(&a, _)| a).collect(); + for a in old { + if let Some(p) = self.pages.remove(&a) { + self.cooling.push_back((p.tile, now)); + } + } + } + + /// A tile: a free one, one cooled down, else the first of a new pool heap (`grow`: its + /// index; None: no video memory). + fn take_tile(&mut self, now: std::time::Instant, grow: &mut impl FnMut() -> Option) -> Option { + if let Some(t) = self.free.pop() { + return Some(t); + } + if self.cooling.front().is_some_and(|&(_, at)| now.duration_since(at) >= COOL) { + return self.cooling.pop_front().map(|(t, _)| t); + } + let h = grow()?; + self.free.extend((1..POOL_PAGES).rev().map(|t| (h, t))); + Some((h, 0)) + } + + /// The tiles of resource `res` at title address `va` in `space`: `total` tiles, the first + /// `own` on the title's pages there (shared with every resource of the space on them), the + /// rest its own. None: no video memory for all of them (nothing is kept). + #[allow(clippy::too_many_arguments)] + fn claim(&mut self, space: Space, res: usize, va: usize, own: usize, total: usize, now: std::time::Instant, grow: &mut impl FnMut() -> Option) -> Option> { + self.sweep(now); + let mut tiles = Vec::with_capacity(total); + let mut used = Vec::with_capacity(own.min(total)); + let mut extra = Vec::new(); + for i in 0..total { + let tile = if i < own { + let a = va + i * PAGE; + let tile = match self.pages.get_mut(&(space, a)) { + Some(p) => { + p.users += 1; + p.idle_since = None; + Some(p.tile) + } + None => self.take_tile(now, grow).inspect(|&t| { + self.pages.insert((space, a), Page { tile: t, users: 1, idle_since: None }); + }), + }; + if tile.is_some() { + used.push(a); + } + tile + } else { + self.take_tile(now, grow).inspect(|&t| extra.push(t)) + }; + let Some(t) = tile else { break }; + tiles.push(t); + } + self.users.insert(res, (space, used, extra)); + if tiles.len() < total { + self.release(res, now); + return None; + } + Some(tiles) + } + + /// Resource `res` released: its pages are no longer its. + fn release(&mut self, res: usize, now: std::time::Instant) { + let Some((space, used, extra)) = self.users.remove(&res) else { return }; + for a in used { + if let Some(p) = self.pages.get_mut(&(space, a)) { + p.users = p.users.saturating_sub(1); + if p.users == 0 { + p.idle_since = Some(now); + } + } + } + self.cooling.extend(extra.into_iter().map(|t| (t, now))); + } + + /// bytes of the pages (idle ones included) and own tiles in use + fn bytes(&self) -> usize { + (self.pages.len() + self.users.values().map(|u| u.2.len()).sum::()) * PAGE + } +} + +/// The title's pages of video memory for textures in its memory (see the module's comment). struct Pages { queue: ID3D12CommandQueue, /// signalled after each mapping; title queues wait for it before their next work fence: ID3D12Fence, value: u64, pools: Vec, - free: Vec, - /// tiles given back, reusable after `COOL` - cooling: std::collections::VecDeque<(Tile, std::time::Instant)>, - /// title page address → its video memory - pages: std::collections::HashMap, - /// target → (the title pages it uses, tiles of its own past the title's memory) - targets: std::collections::HashMap, Vec)>, + book: Book, /// queue → the fence value it last waited for waited: std::collections::HashMap, } @@ -213,37 +323,12 @@ impl Pages { } let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).ok()?; let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; - crate::xlog_info!("D3D12.X: GPU-owned textures in title memory: tiled resources on 64 KiB pages of video memory, one per page of the title's"); - Some(Pages { - queue, - fence, - value: 0, - pools: Vec::new(), - free: Vec::new(), - cooling: std::collections::VecDeque::new(), - pages: std::collections::HashMap::new(), - targets: std::collections::HashMap::new(), - waited: std::collections::HashMap::new(), - }) - } - - /// Pages no target used for `IDLE` go back to the pools. - fn sweep(&mut self, now: std::time::Instant) { - let old: Vec = self.pages.iter().filter(|(_, p)| p.idle_since.is_some_and(|t| now.duration_since(t) >= IDLE)).map(|(&a, _)| a).collect(); - for a in old { - if let Some(p) = self.pages.remove(&a) { - self.cooling.push_back((p.tile, now)); - } - } + crate::xlog_info!("D3D12.X: textures in title memory: tiled resources on 64 KiB pages of video memory, one per page of the title's"); + Some(Pages { queue, fence, value: 0, pools: Vec::new(), book: Book::new(), waited: std::collections::HashMap::new() }) } - unsafe fn take_tile(&mut self, dev: &ID3D12Device) -> Option { - if let Some(t) = self.free.pop() { - return Some(t); - } - if self.cooling.front().is_some_and(|(_, at)| at.elapsed() >= COOL) { - return self.cooling.pop_front().map(|(t, _)| t); - } + /// A new pool heap (its index); None: no video memory. + unsafe fn grow(dev: &ID3D12Device, pools: &mut Vec) -> Option { let desc = D3D12_HEAP_DESC { SizeInBytes: POOL_PAGES as u64 * PAGE as u64, Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, @@ -253,13 +338,11 @@ impl Pages { }; let mut heap: Option = None; if let Err(e) = dev.CreateHeap(&desc, &mut heap) { - crate::xlog_warn!("D3D12.X: no video memory for more pages of GPU-owned textures ({e})"); + crate::xlog_warn!("D3D12.X: no video memory for more pages of textures in title memory ({e})"); return None; } - self.pools.push(heap?); - let h = self.pools.len() as u32 - 1; - self.free.extend((1..POOL_PAGES).rev().map(|t| (h, t))); - Some((h, 0)) + pools.push(heap?); + Some(pools.len() as u32 - 1) } /// Map every tile of `res` (`tiles[i]`: overall tile i) – one call per pool heap. @@ -308,10 +391,11 @@ fn heap_ranges(heap: u32, tiles: &[Tile]) -> Vec<(bool, u32, u32)> { out } -/// A GPU-owned texture at `va` as a reserved resource on the title's pages there +/// A texture at `va` as a reserved resource on the title's pages there in `space` /// (`console_bytes`: its size on the console – the pages it covers; tiles past them are its -/// own). None: it cannot be (the caller tries an arena). -unsafe fn place_on_pages(dev: &ID3D12Device, this: *mut c_void, va: usize, desc: &D3D12_RESOURCE_DESC, state: u32, clear: *const c_void, console_bytes: Option, riid: *const windows_sys::core::GUID, ppv: *mut *mut c_void) -> Option { +/// own). None: it cannot be (the caller tries an arena or a resource of its own). +#[allow(clippy::too_many_arguments)] +unsafe fn place_on_pages(dev: &ID3D12Device, this: *mut c_void, space: Space, va: usize, desc: &D3D12_RESOURCE_DESC, state: u32, clear: *const c_void, console_bytes: Option, riid: *const windows_sys::core::GUID, ppv: *mut *mut c_void) -> Option { if va % PAGE != 0 || desc.Layout != D3D12_TEXTURE_LAYOUT_UNKNOWN { return None; } @@ -323,7 +407,7 @@ unsafe fn place_on_pages(dev: &ID3D12Device, this: *mut c_void, va: usize, desc: if hr < 0 || (*ppv).is_null() { static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 { - crate::xlog_info!("D3D12.X: GPU-owned texture at {va:#x} ({}x{}, format {}, {} samples) not reserved ({hr:#x}): in an arena", desc.Width, desc.Height, desc.Format.0, desc.SampleDesc.Count); + crate::xlog_info!("D3D12.X: texture at {va:#x} ({space:?}: {}x{}, format {}, {} samples) not reserved ({hr:#x}): not on pages", desc.Width, desc.Height, desc.Format.0, desc.SampleDesc.Count); } return None; } @@ -332,63 +416,45 @@ unsafe fn place_on_pages(dev: &ID3D12Device, this: *mut c_void, va: usize, desc: let mut total = 0u32; dev.GetResourceTiling(res, Some(&mut total), None, None, None, 0, std::ptr::null_mut()); let own = console_bytes.map_or(total as usize, |b| (b as usize).div_ceil(PAGE)).min(total as usize); - let now = std::time::Instant::now(); - pages.sweep(now); - let mut tiles = Vec::with_capacity(total as usize); - let mut used = Vec::with_capacity(own); - let mut extra = Vec::new(); - for i in 0..total as usize { - let tile = if i < own { - let a = va + i * PAGE; - let tile = match pages.pages.get_mut(&a) { - Some(p) => { - p.users += 1; - p.idle_since = None; - Some(p.tile) - } - None => pages.take_tile(dev).inspect(|&t| { - pages.pages.insert(a, Page { tile: t, users: 1, idle_since: None }); - }), - }; - if tile.is_some() { - used.push(a); - } - tile - } else { - pages.take_tile(dev).inspect(|&t| extra.push(t)) - }; - let Some(t) = tile else { break }; - tiles.push(t); - } - pages.targets.insert(raw as usize, (used, extra)); - if tiles.len() < total as usize { - // no video memory for all of it: the target goes (its pages with it) + let Pages { book, pools, .. } = pages; + let Some(tiles) = book.claim(space, raw as usize, va, own, total as usize, std::time::Instant::now(), &mut || Pages::grow(dev, pools)) else { + // no video memory for all of it: the texture goes drop(g); - forget_pages(raw as usize); drop(windows::core::IUnknown::from_raw(raw)); *ppv = std::ptr::null_mut(); return None; - } + }; pages.map(res, &tiles); PLACED_TEXTURES.lock().unwrap().get_or_insert_with(HashSet::new).insert(raw as usize); Some(hr) } -/// A target released: its pages are no longer its. +/// A resource released: its pages are no longer its. fn forget_pages(resource: usize) { let mut g = PAGES.lock().unwrap(); let Some(Some(pages)) = g.as_mut() else { return }; - let Some((used, extra)) = pages.targets.remove(&resource) else { return }; - let now = std::time::Instant::now(); - for a in used { - if let Some(p) = pages.pages.get_mut(&a) { - p.users = p.users.saturating_sub(1); - if p.users == 0 { - p.idle_since = Some(now); - } - } + pages.book.release(resource, std::time::Instant::now()); +} + +/// A texture the title placed at `va` whose texels the CPU writes (kept in step with the memory, +/// `title_textures`) as a reserved resource on the title's pages of such textures (`desc`: the PC +/// description, `console_bytes` its size on the console). A title streams its world by placing +/// new textures over memory it used before – as the console allows: the new texture overwrites +/// the old one's memory – and lets few of the old ones go; a committed texture per placement +/// held the sum of every texture ever placed (a retail game: 12.7 GB of them over 4.0 GB of its +/// memory after 90 s, then the device was removed). On pages they cost the memory they cover. +/// None: not on pages (the caller makes a resource of its own). `XCL_TITLE_TEXTURE_PAGES=0` +/// turns this off. +pub unsafe fn place_title_texture(this: *mut c_void, va: usize, desc: &D3D12_RESOURCE_DESC, state: u32, console_bytes: u64, riid: *const windows_sys::core::GUID, ppv: *mut *mut c_void) -> Option { + static OFF: std::sync::OnceLock = std::sync::OnceLock::new(); + if *OFF.get_or_init(|| std::env::var("XCL_TITLE_TEXTURE_PAGES").is_ok_and(|v| v.trim() == "0")) { + return None; } - pages.cooling.extend(extra.into_iter().map(|t| (t, now))); + let dev = ID3D12Device::from_raw_borrowed(&this)?; + if !tier2(dev) { + return None; + } + place_on_pages(dev, this, Space::Textures, va, desc, state, std::ptr::null(), Some(console_bytes), riid, ppv) } /// Before a title queue's work: it waits for the pages mapped since its last work. @@ -406,7 +472,7 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) { pub fn page_bytes() -> (usize, usize) { let g = PAGES.lock().unwrap(); let Some(Some(p)) = g.as_ref() else { return (0, 0) }; - (p.pages.len() * PAGE + p.targets.values().map(|t| t.1.len()).sum::() * PAGE, p.pools.len() * POOL_PAGES as usize * PAGE) + (p.book.bytes(), p.pools.len() * POOL_PAGES as usize * PAGE) } /// Heaps of every kind of resource in one (resource heap tier 2) – else no arenas. @@ -425,7 +491,7 @@ pub unsafe fn place(this: *mut c_void, va: usize, desc: &D3D12_RESOURCE_DESC, st return None; } if std::env::var_os("XCL_VRAM_ARENAS").is_none() { - if let Some(hr) = place_on_pages(dev, this, va, desc, state, clear, console_bytes, riid, ppv) { + if let Some(hr) = place_on_pages(dev, this, Space::Targets, va, desc, state, clear, console_bytes, riid, ppv) { return Some(hr); } } @@ -463,6 +529,183 @@ mod tests { assert_eq!(heap_ranges(0, &[(0, 3), (0, 1), (0, 2)]), [(true, 3, 1), (true, 1, 2)]); } + /// A pool-heap maker for `Book` that numbers heaps as they are made. + fn heaps() -> impl FnMut() -> Option { + let mut n = 0; + move || { + n += 1; + Some(n - 1) + } + } + + /// Textures at one address share its pages, an overlapping one the pages they both cover; + /// targets there have pages of their own; tiles past the title's memory are each one's own. + #[test] + fn textures_share_pages_with_textures_not_with_targets() { + let (t, va) = (Instant::now(), 0x2_0000_0000usize); + let mut b = Book::new(); + let mut grow = heaps(); + let a = b.claim(Space::Textures, 1, va, 4, 4, t, &mut grow).unwrap(); + let same = b.claim(Space::Textures, 2, va, 4, 5, t, &mut grow).unwrap(); + assert_eq!(same[..4], a[..], "a texture placed over another one: the same memory"); + assert!(!a.contains(&same[4]), "a tile past the title's memory is its own"); + let over = b.claim(Space::Textures, 3, va + 2 * PAGE, 4, 4, t, &mut grow).unwrap(); + assert_eq!(over[..2], a[2..], "the pages both cover"); + assert!(!a.contains(&over[2]) && !a.contains(&over[3])); + let target = b.claim(Space::Targets, 4, va, 4, 4, t, &mut grow).unwrap(); + assert!(target.iter().all(|x| !a.contains(x) && !over.contains(x)), "a target's pages are not a texture's"); + // 6 texture pages, 4 target pages, 1 own tile + assert_eq!(b.bytes(), 11 * PAGE); + } + + /// The retail game's pattern (#248): textures streamed in over memory used before, nearly + /// none released. Committed, they held the sum of every texture placed; on pages, the memory + /// they cover. + #[test] + fn streamed_textures_cost_the_memory_they_cover() { + const SPAN: usize = 256 * MIB; + let (t, va) = (Instant::now(), 0x3_0000_0000usize); + let mut b = Book::new(); + let mut grow = heaps(); + let mut placed = 0usize; + // 8000 textures of 64 KiB to 4 MiB at page addresses all over the span + let mut x = 0x2545_F491u32; + for res in 0..8000usize { + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + let pages = 1usize << (x % 7); + let at = (x as usize >> 3) % (SPAN / PAGE - pages) * PAGE; + b.claim(Space::Textures, res, va + at, pages, pages, t, &mut grow).unwrap(); + placed += pages * PAGE; + } + assert!(placed > 30 * SPAN, "the test places {placed} bytes"); + assert!(b.bytes() <= SPAN, "{} bytes of pages for a span of {SPAN}", b.bytes()); + } + + /// A page no resource uses keeps its tile (and what it holds) for 2 s, then the tile cools + /// another 2 s before it is reused; a claim without video memory for all of it keeps nothing. + #[test] + fn released_pages_are_kept_then_cooled_before_reuse() { + let (t, va) = (Instant::now(), 0x4_0000_0000usize); + let s = Duration::from_secs; + let mut b = Book::new(); + let mut grow = heaps(); + let first = b.claim(Space::Textures, 1, va, 1, 1, t, &mut grow).unwrap(); + b.release(1, t); + assert_eq!(b.claim(Space::Textures, 2, va, 1, 1, t + s(1), &mut grow).unwrap(), first, "placed again within 2 s: the same memory"); + b.release(2, t + s(1)); + // the page is let go at 3 s (2 s idle) and its tile cools until 5 s + b.sweep(t + s(3)); + assert!(b.pages.is_empty()); + b.free.clear(); + assert!(b.claim(Space::Textures, 3, va, 1, 1, t + s(4), &mut || None).is_none(), "the tile is still cooling, no new heap"); + assert_eq!(b.claim(Space::Textures, 4, va + PAGE, 1, 1, t + s(5), &mut || None).unwrap(), first, "cooled down: reused"); + // 3 pages wanted, one tile to be had: nothing kept, the tile reusable + b.free.push((7, 7)); + assert!(b.claim(Space::Textures, 5, va + 8 * PAGE, 3, 3, t + s(5), &mut || None).is_none()); + assert!(!b.users.contains_key(&5)); + assert!(b.pages.get(&(Space::Textures, va + 8 * PAGE)).is_some_and(|p| p.users == 0), "its page is idle, not in use"); + } + + /// On the GPU: kept-in-step textures placed at one title address are one memory (an upload + /// through one is what the other reads), and many placements there take one texture's video + /// memory. Needs a hardware adapter with tiled resources tier 2 (skips otherwise). + #[test] + fn title_textures_at_one_address_share_video_memory() { + 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) { + eprintln!("SKIPPED title_textures_at_one_address_share_video_memory: software adapter"); + 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 memory: IDXGIAdapter3 = adapter.cast().unwrap(); + let local = || { + let mut i = DXGI_QUERY_VIDEO_MEMORY_INFO::default(); + let _ = memory.QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut i); + i.CurrentUsage as usize + }; + // RGBA8 512x512, one mip: 1 MiB (16 pages) on the console + let (w, h) = (512u32, 512u32); + let console_bytes = (w * h * 4) as u64; + let desc = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: w as u64, Height: h, DepthOrArraySize: 1, MipLevels: 1, Format: DXGI_FORMAT_R8G8B8A8_UNORM, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, ..Default::default() }; + let srv = D3D12_RESOURCE_STATES(D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE.0 | D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE.0); + 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_title_texture(dev.as_raw(), va, &desc, srv.0 as u32, console_bytes, riid, &mut p); + if hr.is_none() { + return None; + } + assert!(hr.is_some_and(|hr| hr >= 0) && !p.is_null(), "texture at {va:#x}"); + Some(ID3D12Resource::from_raw(p)) + }; + let va = 0x60_0000_0000usize; + let Some(a) = place_at(va) else { + eprintln!("SKIPPED title_textures_at_one_address_share_video_memory: no reserved RGBA8 textures"); + return; + }; + let b = place_at(va).unwrap(); + + // texels uploaded through b are what a holds + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + before_execute(&queue); + let texels: Vec = (0..w * h * 4).map(|i| (i.wrapping_mul(2_654_435_761) >> 13) as u8).collect(); + let sub = crate::gpu::texture::Subresource { rows: h as usize, row_bytes: w as usize * 4, depth: 1, data: texels.clone() }; + let failed = crate::gpu::texture::upload_batch(&dev, &queue, &[(b.clone(), vec![sub], vec![srv])]).unwrap(); + assert!(failed.is_empty(), "{failed:?}"); + let mut fp = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + let mut total = 0u64; + dev.GetCopyableFootprints(&desc, 0, 1, 0, Some(&mut fp), None, None, Some(&mut total)); + let buffer = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: total, Height: 1, DepthOrArraySize: 1, MipLevels: 1, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, ..Default::default() }; + let mut readback: Option = None; + let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }; + dev.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut readback).unwrap(); + let readback = readback.unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + let barrier = |from: D3D12_RESOURCE_STATES, to: D3D12_RESOURCE_STATES| { + let t = D3D12_RESOURCE_TRANSITION_BARRIER { pResource: std::mem::transmute_copy(&a), Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, StateBefore: from, StateAfter: to }; + D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, Anonymous: D3D12_RESOURCE_BARRIER_0 { Transition: std::mem::ManuallyDrop::new(t) }, ..Default::default() } + }; + // (tiles shared between two reserved resources: an aliasing barrier between them) + let alias = D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_ALIASING, Anonymous: D3D12_RESOURCE_BARRIER_0 { Aliasing: std::mem::ManuallyDrop::new(D3D12_RESOURCE_ALIASING_BARRIER { pResourceBefore: std::mem::transmute_copy(&b), pResourceAfter: std::mem::transmute_copy(&a) }) }, ..Default::default() }; + list.ResourceBarrier(&[alias, barrier(srv, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&readback), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: fp } }; + let src = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&a), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 } }; + list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + list.ResourceBarrier(&[barrier(D3D12_RESOURCE_STATE_COPY_SOURCE, srv)]); + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + crate::gpu::texture::wait(&dev, &queue).unwrap(); + let mut p = std::ptr::null_mut(); + readback.Map(0, None, Some(&mut p)).unwrap(); + let pitch = fp.Footprint.RowPitch as usize; + let bad = (0..h as usize).filter(|&y| std::slice::from_raw_parts((p as *const u8).add(y * pitch), w as usize * 4) != &texels[y * w as usize * 4..(y + 1) * w as usize * 4]).count(); + readback.Unmap(0, None); + assert_eq!(bad, 0, "rows of the texture placed first that differ from what was uploaded through the second"); + + // 256 more placements at 8 addresses: video memory for 8 textures, not 256 + let used0 = local(); + let pages0 = page_bytes().0; + let more: Vec = (0..256).map(|k| place_at(va + 0x100_0000 + (k % 8) * 0x10_0000).unwrap()).collect(); + let (used, pages) = (local().saturating_sub(used0), page_bytes().0 - pages0); + println!("256 RGBA8 512x512 textures at 8 addresses: {pages} bytes of pages, {used} bytes more local video memory"); + assert!(pages <= 8 * console_bytes as usize + 256 * PAGE, "{pages} bytes of pages"); + assert!(used < 64 * console_bytes as usize, "{used} bytes of video memory"); + drop((more, a, b)); + } + } + /// A placement's arena id, with heaps numbered as they are made. fn take(a: &mut Arenas, va: usize, bytes: usize, align: usize, now: Instant) -> u64 { let n = a.list.len() as u32;