Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 31 additions & 4 deletions crates/xcl/src/hle/d3d12x/title_textures.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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<u32> = 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<u32> = (0..subs.len() as u32).filter(|l| !present.contains(l)).collect();
super::vram::unmap_levels(r, &zero);
super::vram::map_levels(r, Some(&present))
}

Expand Down Expand Up @@ -4443,15 +4448,17 @@ 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();
let _guard = TEST_LOCK.lock().unwrap();
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");
Expand Down Expand Up @@ -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);
Expand Down
104 changes: 103 additions & 1 deletion crates/xcl/src/hle/d3d12x/vram.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -1427,6 +1433,88 @@ 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;
}
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);
}
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);

/// `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<T: Copy + Eq + std::hash::Hash>(v: &mut Vec<T>, gone: &[T]) {
if gone.is_empty() {
return;
}
let mut left: std::collections::HashMap<T, u32> = 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<u64> {
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()))
Expand Down Expand Up @@ -1550,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.
Expand Down
Loading