Skip to content
Draft
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
176 changes: 160 additions & 16 deletions crates/xcl/src/hle/d3d12x/title_textures.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@
//! transitions of these textures are captured in each physical command-list segment's immutable
//! submission effects and applied in submission order – per subresource once one is named.

use std::collections::{BTreeMap, BTreeSet};
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::ffi::c_void;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::sync::{Arc, Mutex, RwLock};

use windows::core::Interface;
use windows::Win32::Graphics::Direct3D12::*;
Expand Down Expand Up @@ -148,6 +148,9 @@ struct Table {
/// Largest byte span currently in `shadowed` (bounds range queries)
max_shadowed_size: usize,
next_generation: u64,
/// the process's table (`TEXTURES`): its entries' generations are mirrored in `RES_GENERATIONS`
/// (a test's own table leaves the mirror alone)
global: bool,
/// the active textures by the 1 MiB pieces of their source (`Entry::src`) they cover: which of
/// them lie under a written page. A title has tens of thousands of textures; a submit asks
/// about the few its dirty pages touch
Expand All @@ -157,6 +160,9 @@ struct Table {
/// 16 MiB blocks of the textures' sources -> how many active ones cover it: the part of the
/// watched ranges that textures make (cheap to rebuild from, unlike all textures)
coarse: BTreeMap<usize, u32>,
/// the entries of `by_res` with `Entry::cpu_backed` (`CPU_TEXTURES_LEN`), counted as they come
/// and go: a title has tens of thousands, and every placement and release counted them anew
cpu_backed_count: usize,
}

/// the size of `Table::coarse`'s blocks
Expand All @@ -175,17 +181,55 @@ fn in_view_window(src: usize) -> bool {
}

impl Table {
#[cfg(test)]
const fn new() -> Self {
Self::with_global(false)
}

const fn with_global(global: bool) -> Self {
Table {
by_res: BTreeMap::new(),
by_va: BTreeMap::new(),
shadowed: BTreeMap::new(),
shadowed_by_va: BTreeMap::new(),
max_shadowed_size: 0,
next_generation: 0,
global,
src_pieces: BTreeMap::new(),
pending_res: std::collections::BTreeSet::new(),
coarse: BTreeMap::new(),
cpu_backed_count: 0,
}
}

/// `by_res.insert`, counting `cpu_backed_count`.
fn insert_active(&mut self, res: usize, e: Entry) {
if e.cpu_backed {
self.cpu_backed_count += 1;
}
if let Some(prev) = self.by_res.insert(res, e) {
if prev.cpu_backed {
self.cpu_backed_count -= 1;
}
}
}

/// `by_res.remove`, counting `cpu_backed_count`.
fn remove_active(&mut self, res: usize) -> Option<Entry> {
let old = self.by_res.remove(&res)?;
if old.cpu_backed {
self.cpu_backed_count -= 1;
}
Some(old)
}

/// `res` leaves the table: out of `RES_GENERATIONS` too (`global`).
fn forget_generation(&self, res: usize) {
if !self.global {
return;
}
if let Some(m) = RES_GENERATIONS.write().unwrap_or_else(|e| e.into_inner()).as_mut() {
m.remove(&res);
}
}

Expand Down Expand Up @@ -293,7 +337,8 @@ impl Table {
let (mut pending_delta, mut retired, mut to_unmap) = (0isize, 0usize, Vec::new());
for (ova, ores, _) in self.active_overlaps(va, end) {
self.by_va.remove(&(ova, ores));
if let Some(old) = self.by_res.remove(&ores) {
if let Some(old) = self.remove_active(ores) {
self.forget_generation(ores);
self.unlink_src(ores, old.src, old.tex.size() as usize);
if old.pending {
pending_delta -= 1;
Expand All @@ -307,6 +352,7 @@ impl Table {
for (sva, sres, _) in self.shadowed_overlaps(va, end) {
self.shadowed_by_va.remove(&(sva, sres));
if let Some(old) = self.shadowed.remove(&sres) {
self.forget_generation(sres);
if old.placed && !old.unmapped {
to_unmap.push(sres);
}
Expand All @@ -329,7 +375,7 @@ impl Table {
let end = va.saturating_add(entry.tex.size() as usize);
let mut pending_delta = 0isize;
let mut to_unmap = Vec::new();
if let Some(old) = self.by_res.remove(&res) {
if let Some(old) = self.remove_active(res) {
self.unlink_src(res, old.src, old.tex.size() as usize);
self.by_va.remove(&(old.va, res));
if old.pending {
Expand All @@ -344,7 +390,7 @@ impl Table {
continue;
}
self.by_va.remove(&(ova, ores));
if let Some(mut old) = self.by_res.remove(&ores) {
if let Some(mut old) = self.remove_active(ores) {
self.unlink_src(ores, old.src, old.tex.size() as usize);
if old.pending {
pending_delta -= 1;
Expand Down Expand Up @@ -382,22 +428,28 @@ impl Table {
self.by_va.insert((va, res), end);
let (src, size) = (entry.src, entry.tex.size() as usize);
self.link_src(res, src, size);
self.by_res.insert(res, entry);
if self.global {
let mut g = RES_GENERATIONS.write().unwrap_or_else(|e| e.into_inner());
g.get_or_insert_with(HashMap::new).insert(res, entry.generation);
}
self.insert_active(res, entry);
(pending_delta, to_unmap)
}

/// Remove `res` on COM release, reactivating any shadowed older textures it uncovered (newest
/// first). Returns `(was_present, pending_delta, unmapped_res_to_remap, uniform_state)`.
fn remove(&mut self, res: usize) -> (bool, isize, Vec<usize>, Option<D3D12_RESOURCE_STATES>) {
if let Some(old) = self.shadowed.remove(&res) {
self.forget_generation(res);
self.shadowed_by_va.remove(&(old.va, res));
if self.shadowed.is_empty() {
self.max_shadowed_size = 0;
}
let st = (old.states.len() == 1).then(|| old.states[0]);
return (true, 0, Vec::new(), st);
}
let Some(old) = self.by_res.remove(&res) else { return (false, 0, Vec::new(), None) };
let Some(old) = self.remove_active(res) else { return (false, 0, Vec::new(), None) };
self.forget_generation(res);
self.unlink_src(res, old.src, old.tex.size() as usize);
let st = (old.states.len() == 1).then(|| old.states[0]);
self.by_va.remove(&(old.va, res));
Expand Down Expand Up @@ -435,7 +487,7 @@ impl Table {
if e.pending {
self.pending_res.insert(sres);
}
self.by_res.insert(sres, e);
self.insert_active(sres, e);
}
}
if self.shadowed.is_empty() {
Expand Down Expand Up @@ -477,7 +529,12 @@ unsafe fn clone_resources(ptrs: &[usize]) -> Vec<ID3D12Resource> {
}

/// PC texture → its place in the title's memory
static TEXTURES: Mutex<Table> = Mutex::new(Table::new());
static TEXTURES: Mutex<Table> = Mutex::new(Table::with_global(true));
/// The registration generation of each texture of `TEXTURES` (active or shadowed), written under
/// its lock: `capture_transitions` (every barrier of a list) and `capture_gpu_write` (every copy
/// and clear) read it under a shared lock instead of waiting for `TEXTURES`, which submits hold
/// while they choose the textures to upload.
static RES_GENERATIONS: RwLock<Option<HashMap<usize, u64>>> = RwLock::new(None);
// The dirty-page scan consumes write-watch state for every submission thread.
// Keep the scan, pending-list update and GPU uploads together.
static REFRESH: Mutex<()> = Mutex::new(());
Expand Down Expand Up @@ -513,7 +570,18 @@ unsafe fn committed_allocation_bytes(device: *mut c_void, resource: *mut c_void,

fn update_lengths(t: &Table) {
TEXTURES_LEN.store(t.by_res.len(), Ordering::Relaxed);
CPU_TEXTURES_LEN.store(t.by_res.values().filter(|e| e.cpu_backed).count(), Ordering::Relaxed);
debug_assert_eq!(t.cpu_backed_count, t.by_res.values().filter(|e| e.cpu_backed).count(), "a by_res change bypassed insert_active / remove_active");
#[cfg(debug_assertions)]
if t.global {
let g = RES_GENERATIONS.read().unwrap_or_else(|e| e.into_inner());
let m = g.as_ref();
debug_assert!(
m.map_or(0, |m| m.len()) == t.by_res.len() + t.shadowed.len()
&& t.by_res.iter().chain(&t.shadowed).all(|(r, e)| m.and_then(|m| m.get(r)) == Some(&e.generation)),
"RES_GENERATIONS missed a change of TEXTURES"
);
}
CPU_TEXTURES_LEN.store(t.cpu_backed_count, Ordering::Relaxed);
}

/// Whether a non-depth render target / UAV texture is small enough to be a CPU-filled glyph or UI
Expand Down Expand Up @@ -917,9 +985,9 @@ pub(super) fn capture_gpu_write(res: usize, subresource: u32) -> Option<GpuWrite
}
}
}
let t = TEXTURES.lock().unwrap();
let e = t.by_res.get(&res).or_else(|| t.shadowed.get(&res))?;
Some(GpuWrite { res, generation: e.generation, subresource })
let g = RES_GENERATIONS.read().unwrap_or_else(|e| e.into_inner());
let generation = *g.as_ref()?.get(&res)?;
Some(GpuWrite { res, generation, subresource })
}

/// Publish writes from command-list segments that the native submission gate accepted. On the
Expand Down Expand Up @@ -1079,12 +1147,13 @@ pub(super) fn capture_transitions(transitions: &[(usize, u32, D3D12_RESOURCE_STA
if !any() || transitions.is_empty() {
return Vec::new();
}
let t = TEXTURES.lock().unwrap();
let g = RES_GENERATIONS.read().unwrap_or_else(|e| e.into_inner());
let Some(generations) = g.as_ref() else { return Vec::new() };
transitions
.iter()
.filter_map(|&(res, subresource, after)| {
let e = t.by_res.get(&res).or_else(|| t.shadowed.get(&res))?;
Some(Transition { res, generation: e.generation, subresource, after })
let &generation = generations.get(&res)?;
Some(Transition { res, generation, subresource, after })
})
.collect()
}
Expand Down Expand Up @@ -5568,6 +5637,36 @@ pub(super) mod tests {
forget(res);
}

/// `capture_gpu_write` and `capture_transitions` read the generations of `TEXTURES` from
/// `RES_GENERATIONS`: a texture has one while it is active or shadowed, a new one each time it
/// is placed again, and none once released or retired; a test's own table leaves it alone.
#[test]
fn the_generation_mirror_follows_the_table() {
let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let tex = Arc::new(xg::Texture::new(&console_desc(3, 64, 64, 1, 1, 28, 0x105)).unwrap());
let entry = |va: usize| Entry { device: 0, committed_bytes: 0, va, src: va, in_gpu_view: false, paged: false, tex: Arc::clone(&tex), states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: true, written_call: 0, gpu_writers: Vec::new(), cpu_backed: true, placed: false, unmapped: false, generation: 0, known: Default::default(), target: false };
// fake resources, never dereferenced
let (a, b, local) = (0x7E57_0000_3000usize, 0x7E57_0000_4000usize, 0x7E57_0000_5000usize);
let va = 0x7E57_0010_0000usize;
let generation = |res| capture_gpu_write(res, 0).map(|w| w.generation);
TEXTURES.lock().unwrap().insert(a, entry(va));
let first = generation(a).expect("an active texture has a generation");
// (b over part of a's range: a is shadowed, and keeps its generation)
TEXTURES.lock().unwrap().insert(b, entry(va + 0x1000));
assert!(TEXTURES.lock().unwrap().shadowed.contains_key(&a));
assert_eq!(generation(a), Some(first));
assert!(generation(b).is_some_and(|g| g != first));
TEXTURES.lock().unwrap().insert(a, entry(va));
assert!(generation(a).is_some_and(|g| g != first), "placed again: a new generation");
TEXTURES.lock().unwrap().remove(a);
assert_eq!(generation(a), None, "released");
TEXTURES.lock().unwrap().retire_range(va, va + 0x1_0000);
assert_eq!(generation(b), None, "retired");
let mut t = Table::new();
t.insert(local, entry(va));
assert_eq!(generation(local), None, "a test's own table");
}

/// The title's bytes outside the coherent window are read as `read_committed` reads them (the
/// pages that are not committed as zeros, never what an earlier read on the thread left);
/// inside it they are used where they are.
Expand Down Expand Up @@ -6123,6 +6222,51 @@ pub(super) mod tests {
assert!(!tbl.by_res.contains_key(&10) && !tbl.by_res.contains_key(&11) && tbl.by_res.contains_key(&12));
}

/// `Table::cpu_backed_count` (`CPU_TEXTURES_LEN`) follows the CPU-backed active textures
/// through placements, a texture placed again, shadowing, releases and retirement, as counting
/// them all does.
#[test]
fn the_cpu_backed_count_follows_the_active_textures() {
let tex = Arc::new(xg::Texture::new(&console_desc(3, 64, 64, 1, 1, 28, 0x105)).unwrap());
let entry = |va: usize, cpu_backed: bool| Entry {
device: 0,
committed_bytes: 0,
va,
src: va,
in_gpu_view: false,
paged: false,
tex: Arc::clone(&tex),
states: vec![D3D12_RESOURCE_STATE_COMMON],
pending: false,
gpu_written: false,
written_call: 0,
gpu_writers: Vec::new(),
cpu_backed,
placed: true,
unmapped: false,
generation: 0,
known: Default::default(),
target: false,
};
let counted = |t: &Table| t.by_res.values().filter(|e| e.cpu_backed).count();
let mut tbl = Table::new();
tbl.insert(1, entry(0x10_0000, true));
tbl.insert(2, entry(0x10_4000, false));
tbl.insert(3, entry(0x10_8000, true));
assert_eq!((tbl.cpu_backed_count, counted(&tbl)), (2, 2));
// (the same range over 1 shadows it; 3 placed again replaces itself)
tbl.insert(4, entry(0x10_0000, false));
tbl.insert(3, entry(0x10_8000, true));
assert!(tbl.shadowed.contains_key(&1));
assert_eq!(tbl.cpu_backed_count, counted(&tbl));
tbl.remove(4);
assert_eq!(tbl.cpu_backed_count, counted(&tbl));
tbl.remove(2);
assert_eq!(tbl.cpu_backed_count, counted(&tbl));
tbl.retire_range(0x10_0000, 0x10_C000);
assert_eq!((tbl.cpu_backed_count, counted(&tbl), tbl.by_res.len()), (0, 0, 0));
}

/// Real GPU (#248): placed title textures share `vram::Pages` so streaming unreleased
/// overlapping placements stays bounded in video memory, superseded textures never corrupt
/// newer placements on shared tiles, 4 KiB-aligned neighbours never false-alias, and mip
Expand Down
Loading