From db0780c3c96ba5f7bc0bfd1d08ce5f9c40492b82 Mon Sep 17 00:00:00 2001 From: Prime <215761102+Prime1997@users.noreply.github.com> Date: Thu, 26 Nov 2026 16:03:37 -0800 Subject: [PATCH 1/2] D3D12.X: a texture level that lost its texels gives its pages back With XCL_TEXTURE_LEVEL_PAGES=1 a streamed texture's level gets video memory pages at the first upload with texels for it, and kept them for as long as the texture lived. A streaming title takes the memory from under the large levels of textures it no longer shows at that size (its GPU-view pages unmapped), and the texture is uploaded again with those levels all zeros: the pages stayed, holding zeros. In a retail title's world on an 8 GB card the target pages grew from 2.7 GB to 4.2 GB in four minutes with 0 MB idle, more than the title's whole texture pool (63,632 pages, 3.98 GB), and video memory reached 10.2 GB on a 7.1 GB budget. Before such an upload a group of levels that has pages and is all zeros now gives them back (vram::unmap_levels: its tiles unmapped on the mapping queue, its pages released as a released texture's are, idle and then back to the pools when no other texture uses them). Tiles without memory read as zeros (tiled resources tier 2), as the zero texels the upload would have written; the level gets pages again with its next texels (map_levels). Test: the level-pages GPU test goes on: the title decommits mip 0 again, the next upload gives back mip 0's pages (86 -> 22 tiles with pages; 86 without this change), mip 0 reads zeros and the other levels keep their texels, the other texture on the same pages keeps them, and mip 0 gets them back with its texels. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/title_textures.rs | 35 +++++++-- crates/xcl/src/hle/d3d12x/vram.rs | 79 ++++++++++++++++++++- 2 files changed, 109 insertions(+), 5 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index fd04827aaf..990dc67f05 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -2412,8 +2412,9 @@ pub unsafe fn upload_and_wait(dev: &ID3D12Device, queue: &ID3D12CommandQueue, re } /// (`vram::level_pages`) Before an upload of title texture `r`: its levels with texels in `subs` -/// (its subresources as they go up) get their video memory pages if they have none - a texture -/// placed with lazy levels; any other: nothing to do. A level of zeros has no texels: a streamed +/// (its subresources as they go up) get their video memory pages if they have none, and those +/// with pages and no texels now give them back (`vram::unmap_levels`) - a texture placed with +/// lazy levels; any other: nothing to do. A level of zeros has no texels: a streamed /// texture's larger levels before the title has memory behind them (read as zeros, /// `read_committed`). It keeps no pages, reads as zeros as it would with them, and its copy goes /// to tiles that are not mapped, which drops it (tiled resources tier 2). Returns the levels that @@ -2424,6 +2425,10 @@ unsafe fn map_levels_with_texels(r: &ID3D12Resource, subs: &[Subresource]) -> Ve } // (one slice: its subresources are its levels) let present: Vec = subs.iter().enumerate().filter(|(_, s)| !all_zero(&s.data)).map(|(i, _)| i as u32).collect(); + // a level that had texels and has none now: the title took its memory, and it gives back its + // pages (this upload would only have written zeros to them) + let zero: Vec = (0..subs.len() as u32).filter(|l| !present.contains(l)).collect(); + super::vram::unmap_levels(r, &zero); super::vram::map_levels(r, Some(&present)) } @@ -4443,7 +4448,9 @@ pub(super) mod tests { /// first upload, then pages for those levels only and their texels right, zeros where there /// are none. With memory under the largest level too, a texture placed there again (as a /// title does) takes that level's pages - the others are shared - and holds all of it. A - /// texture the GPU writes gets the pages of all its levels. + /// texture the GPU writes gets the pages of all its levels. When the title takes the memory + /// from under the largest level again, that level gives its pages back at the next upload + /// (the other texture on them keeps them), and gets them again with its texels. #[test] fn a_placed_texture_gets_the_pages_of_a_level_with_its_texels() { let _vram_guard = super::super::vram::VRAM_TEST_LOCK.lock().unwrap(); @@ -4451,7 +4458,7 @@ pub(super) mod tests { use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; use windows::Win32::Graphics::Dxgi::*; - use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE}; + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_DECOMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE}; const NAME: &str = "a_placed_texture_gets_the_pages_of_a_level_with_its_texels"; unsafe { let factory: IDXGIFactory4 = CreateDXGIFactory1().expect("DXGI factory"); @@ -4572,6 +4579,26 @@ pub(super) mod tests { note_gpu_write(0, small.as_raw() as usize); assert_eq!(dev_pages() - p0, (all as usize) << 16, "the same pages"); assert!(read_sub(&small, 0) == want[0].data, "a GPU-written texture has pages under all its levels"); + // the title takes the memory from under mip 0 again (a streamed level it let go): the + // second texture's next upload finds mip 0 all zeros, and mip 0 gives back its pages; + // the first one, on the same pages, keeps them + let full_key = full.as_raw() as usize; + assert_eq!(super::super::vram::mapped_level_tiles(full_key), Some(all as u64)); + assert_ne!(VirtualFree((at + top) as *mut c_void, size - top, MEM_DECOMMIT), 0); + assert!(map_levels_with_texels(&full, &subresources(at, &tex)).is_empty(), "no level got pages"); + assert_eq!(super::super::vram::mapped_level_tiles(full_key), Some((all - top_tiles) as u64), "mip 0 gave its pages back"); + assert!(super::super::vram::has_unmapped_levels(full_key)); + assert!(read_sub(&full, 0).iter().all(|&b| b == 0), "a level that gave its pages back reads as zeros"); + for sub in 1..11u32 { + assert!(read_sub(&full, sub) == want[sub as usize].data, "level {sub} keeps its pages and texels"); + } + assert!(read_sub(&small, 0) == want[0].data, "the other texture on those pages keeps them"); + // mip 0's texels come back: its pages too, the ones the other texture holds + assert!(!VirtualAlloc((at + top) as *const c_void, size - top, MEM_COMMIT, PAGE_READWRITE).is_null()); + std::ptr::copy_nonoverlapping(whole.as_ptr().add(top), (at + top) as *mut u8, size - top); + assert_eq!(map_levels_with_texels(&full, &subresources(at, &tex)), vec![0], "mip 0 got its pages again"); + assert_eq!(super::super::vram::mapped_level_tiles(full_key), Some(all as u64)); + assert!(read_sub(&full, 0) == want[0].data, "mip 0 on the pages the other texture kept"); super::super::vram::LEVEL_PAGES_FOR_TEST.store(false, Ordering::Relaxed); drop((small, full)); VirtualFree(at as *mut c_void, 0, MEM_RELEASE); diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index a87a56b4e0..afd3026a4a 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -743,10 +743,16 @@ impl Pages { /// Unmap every tile of `res` (`D3D12_TILE_RANGE_FLAG_NULL`) so its unshared tiles can return /// to the pool even while the title keeps the COM object alive. unsafe fn unmap(&mut self, res: &ID3D12Resource, total: u32) { + self.unmap_range(res, 0, total); + } + + /// `unmap` for the `n` tiles of `res` from the first one of subresource `sub` on. + unsafe fn unmap_range(&mut self, res: &ID3D12Resource, sub: u32, n: u32) { + let total = n; if total == 0 { return; } - let coord = D3D12_TILED_RESOURCE_COORDINATE::default(); + let coord = D3D12_TILED_RESOURCE_COORDINATE { Subresource: sub, ..Default::default() }; let region = D3D12_TILE_REGION_SIZE { NumTiles: total, UseBox: false.into(), ..Default::default() }; let flag = D3D12_TILE_RANGE_FLAG_NULL; self.queue.UpdateTileMappings( @@ -1427,6 +1433,77 @@ pub(super) unsafe fn map_levels(res: &ID3D12Resource, levels: Option<&[u32]>) -> Vec::new() } +/// The levels `zero` of `res` hold no texels now: the title took the memory from under them, as +/// a streaming title does with the levels of a texture it no longer shows at that size. A +/// texture placed with lazy levels gives back the pages of each group of levels that has pages +/// and whose levels are all in `zero`, as it had none before their first texels (`map_levels` +/// gives them pages again with their next ones): tiles without memory read as zeros, as those +/// levels would with it (tiled resources tier 2). Its pages go back to the pools when no other +/// texture uses them (`release_tiles`, `IDLE`). Returns the tiles that lost their pages. +pub(super) unsafe fn unmap_levels(res: &ID3D12Resource, zero: &[u32]) -> u64 { + let key = res.as_raw() as usize; + let mut g = PAGES.lock().unwrap(); + for pages in g.values_mut().flatten() { + let Some(t) = pages.targets.get_mut(&key) else { continue }; + let (va, console_bytes, total) = (t.va, t.console_bytes, t.total); + let Some(lv) = t.levels.as_mut().filter(|_| t.mapped) else { return 0 }; + let Some((first_page, own)) = owned_pages(va, console_bytes, total as usize) else { return 0 }; + let mut ranges = Vec::new(); + let (mut gone, mut gone_extra) = (Vec::new(), Vec::new()); + for k in 0..lv.groups.len() { + if !lv.groups[k].3 || !lv.levels_of(k).all(|l| zero.contains(&l)) { + continue; + } + let (sub, first, n, _) = lv.groups[k]; + lv.groups[k].3 = false; + ranges.push((sub, n)); + // (the keys `bind_range` gave these tiles) + for i in first as usize..(first + n) as usize { + if i < own { + gone.push(first_page + i * PAGE); + } else { + gone_extra.push((va, i)); + } + } + } + if ranges.is_empty() { + return 0; + } + for a in &gone { + if let Some(i) = t.used.iter().position(|u| u == a) { + t.used.swap_remove(i); + } + } + for k in &gone_extra { + if let Some(i) = t.used_extra.iter().position(|u| u == k) { + t.used_extra.swap_remove(i); + } + } + let freed: u64 = ranges.iter().map(|&(_, n)| n as u64).sum(); + for (sub, n) in ranges { + pages.unmap_range(res, sub, n); + } + pages.release_tiles(gone, gone_extra, std::time::Instant::now(), false); + LEVEL_STATS[2].fetch_sub(freed, std::sync::atomic::Ordering::Relaxed); + let n = LEVELS_GIVEN_BACK.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; + if n.is_power_of_two() && n >= 64 { + let (textures, stand, mapped, _) = level_stats(); + crate::xlog_info!("D3D12.X: level pages: {n} times a texture's levels lost their texels and gave their pages back; {textures} textures standing for {} MB have pages for {} MB", stand >> 4, mapped >> 4); + } + return freed; + } + 0 +} + +/// The times `unmap_levels` gave pages back. +static LEVELS_GIVEN_BACK: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// The tiles of texture `resource` (lazy levels) that have pages: for a test. +#[cfg(test)] +pub(super) fn mapped_level_tiles(resource: usize) -> Option { + PAGES.lock().unwrap().values().flatten().find_map(|p| p.targets.get(&resource).and_then(|t| t.levels.as_ref()).map(|l| l.mapped_tiles())) +} + /// Whether `resource` is a texture whose levels get their pages one by one (`map_levels`). pub(super) fn has_lazy_levels(resource: usize) -> bool { PAGES.lock().unwrap().values().flatten().any(|p| p.targets.get(&resource).is_some_and(|t| t.levels.is_some())) From 0c8378463f04ae17b4070f1fe96e528ef57adcdb Mon Sep 17 00:00:00 2001 From: Prime <215761102+Prime1997@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:04:54 -0800 Subject: [PATCH 2/2] D3D12.X: a level giving its pages back drops their keys in one pass Review note on #2927: unmap_levels searched the texture's page keys and swap_removed one for each key given back, under PAGES: quadratic in the pages of a large level. remove_once_each counts the keys to drop and takes one occurrence of each in a single retain. Test: remove_once_each_takes_one_occurrence_for_each_naming (duplicates, keys not named, nothing to take); the level-pages GPU test still passes. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/vram.rs | 45 ++++++++++++++++++++++++------- 1 file changed, 35 insertions(+), 10 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index afd3026a4a..065467f1ee 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -1469,16 +1469,8 @@ pub(super) unsafe fn unmap_levels(res: &ID3D12Resource, zero: &[u32]) -> u64 { if ranges.is_empty() { return 0; } - for a in &gone { - if let Some(i) = t.used.iter().position(|u| u == a) { - t.used.swap_remove(i); - } - } - for k in &gone_extra { - if let Some(i) = t.used_extra.iter().position(|u| u == k) { - t.used_extra.swap_remove(i); - } - } + remove_once_each(&mut t.used, &gone); + remove_once_each(&mut t.used_extra, &gone_extra); let freed: u64 = ranges.iter().map(|&(_, n)| n as u64).sum(); for (sub, n) in ranges { pages.unmap_range(res, sub, n); @@ -1498,6 +1490,25 @@ pub(super) unsafe fn unmap_levels(res: &ID3D12Resource, zero: &[u32]) -> u64 { /// The times `unmap_levels` gave pages back. static LEVELS_GIVEN_BACK: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); +/// `v` without one occurrence of each item of `gone` (an item named twice: two of them), in one +/// pass: a search of `v` for each would go over it again for every page of a large level. +fn remove_once_each(v: &mut Vec, gone: &[T]) { + if gone.is_empty() { + return; + } + let mut left: std::collections::HashMap = std::collections::HashMap::with_capacity(gone.len()); + for &g in gone { + *left.entry(g).or_insert(0) += 1; + } + v.retain(|x| match left.get_mut(x) { + Some(n) if *n > 0 => { + *n -= 1; + false + } + _ => true, + }); +} + /// The tiles of texture `resource` (lazy levels) that have pages: for a test. #[cfg(test)] pub(super) fn mapped_level_tiles(resource: usize) -> Option { @@ -1627,6 +1638,20 @@ mod tests { const MIB: usize = 1 << 20; + /// `remove_once_each` takes one occurrence for each time an item is named, keeps the rest + /// (duplicates too) and items not named, and leaves the list as it was for nothing to take. + #[test] + fn remove_once_each_takes_one_occurrence_for_each_naming() { + let mut v = vec![1, 2, 3, 2, 4, 2, 5]; + remove_once_each(&mut v, &[2, 4, 2, 9]); + assert_eq!(v, vec![1, 3, 2, 5]); + let mut w = vec![(1, 1), (1, 2)]; + remove_once_each(&mut w, &[]); + assert_eq!(w, vec![(1, 1), (1, 2)]); + remove_once_each(&mut w, &[(1, 2), (1, 2)]); + assert_eq!(w, vec![(1, 1)]); + } + /// The levels of a texture with lazy levels: a group of tiles for each level with tiles of its /// own and one for the packed levels; a level past the last standard one is in the packed /// group; a tiling that does not add up to the resource's tiles gives none.