diff --git a/crates/victory-gpu/src/bindless.rs b/crates/victory-gpu/src/bindless.rs index 1cd7ecc0d..0c29656b0 100644 --- a/crates/victory-gpu/src/bindless.rs +++ b/crates/victory-gpu/src/bindless.rs @@ -15,6 +15,7 @@ use std::sync::{Arc, Mutex}; use crate::backend::HostGpu; use crate::census_fast::{Snapshot, SnapshotCache, UnorderedIndex}; +use crate::census_maps::{Hashing, RangesMap}; use crate::descriptor::View; use crate::host::HostList; use crate::object::This; @@ -22,7 +23,7 @@ use crate::shadow::Shadow; /// What a title heap slot views that title memory feeds. #[derive(Clone)] -enum Seen { +pub(crate) enum Seen { /// `len` bytes at `address` of a buffer's host copy; unordered access. Buffer(Arc, u64, u64, bool), /// A title texture (resource object) whose contents the title writes. @@ -33,6 +34,27 @@ enum Seen { Left(#[cfg_attr(not(feature = "diagnostics"), allow(dead_code))] (usize, u64, u64)), } +impl Seen { + /// Constructs a shader-resource (non-UAV) buffer entry matching [`seen`], + /// clamping `len` to the bytes remaining in `shadow` from `address`. + pub(crate) fn shader_buffer(shadow: Arc, address: u64, len: u64) -> Option { + if len == 0 { + return None; + } + let len = len.min(shadow.left(address)); + Some(Self::Buffer(shadow, address, len, false)) + } +} + +/// One slot update submitted to [`Viewed::set_batch_resolved`]. +#[cfg(windows)] +pub(crate) enum BatchUpdate<'a> { + /// Already-resolved slot entry (or `None` to clear the slot). + Resolved(Option), + /// View to resolve via [`seen`] or [`left_kind`] outside the registry lock. + View(&'a View, bool), +} + /// Kinds of views left without a host view, for the census. #[cfg(feature = "diagnostics")] const KINDS: [&str; 4] = ["buffer", "unordered buffer", "placed texture", "other"]; @@ -46,22 +68,33 @@ pub(crate) struct Viewed { /// Monotonic generation bumped whenever `inner.hulls` changes, so /// submission batching can skip repeat `refresh` walks of an unchanged heap. hull_generation: AtomicU64, + /// Whether fast multiply-and-fold hashing is active (`VICTORY_QUICK_SYNC`). + quick_maps: bool, } impl Default for Viewed { fn default() -> Self { - Self::new(crate::census_fast::on()) + Self::with_options(crate::census_fast::on(), crate::census_maps::quick_maps()) } } impl Viewed { /// Creates a bindless registry, optionally enabling the fast UAV range - /// index and snapshot cache (`VICTORY_CENSUS_FAST=1`). + /// index and snapshot cache (`VICTORY_CENSUS_FAST=1`) while following + /// `VICTORY_QUICK_SYNC` for map selection. + #[cfg(test)] pub(crate) fn new(fast: bool) -> Self { + Self::with_options(fast, crate::census_maps::quick_maps()) + } + + /// Creates a bindless registry with explicit `VICTORY_CENSUS_FAST` (`fast`) + /// and `VICTORY_QUICK_SYNC` (`quick_maps`) settings. + pub(crate) fn with_options(fast: bool, quick_maps: bool) -> Self { Viewed { - inner: Mutex::new(Inner::new(fast)), + inner: Mutex::new(Inner::new(fast, quick_maps)), fast: fast.then(SnapshotCache::default), hull_generation: AtomicU64::new(0), + quick_maps, } } @@ -71,7 +104,7 @@ impl Viewed { } } -type Range = (usize, u64, u64, bool); +pub(crate) type Range = (usize, u64, u64, bool); /// A merged range: copy, start, bytes, unordered access, the copy's bit in /// the change tracker (`crate::watch::clean_bit`). @@ -87,8 +120,8 @@ struct ActiveWord { } struct Inner { - slots: HashMap, - ranges: BTreeMap)>, + slots: HashMap, + ranges: RangesMap)>, /// Per title texture, the slots viewing it: an entry names its slots, so /// releasing the texture ([`Inner::forget`]) does not search the heap. textures: BTreeMap>, @@ -98,7 +131,7 @@ struct Inner { /// run perf4). Stored densely so `refresh` indexes directly without hashing. hulls: Vec, /// Maps `(copy_ptr, uav)` to its dense index in `hulls`. - hull_pos: HashMap<(usize, bool), u32>, + hull_pos: HashMap<(usize, bool), u32, Hashing>, /// Sorted by `word`; lets `refresh` test 64 copies per atomic word load /// and index `hulls` directly with zero hash lookups. active_words: Vec, @@ -110,28 +143,28 @@ struct Inner { /// copies, not from every range (the title rewrites slots between most /// lists, and remerging the world's 130,000 ranges each time cost 0.15 /// s per frame). - ends: HashMap<(usize, bool), Ends>, + ends: HashMap<(usize, bool), Ends, Hashing>, /// Secondary index of active UAV ranges only (`VICTORY_CENSUS_FAST=1`). unordered: Option>, } impl Default for Inner { fn default() -> Self { - Self::new(false) + Self::new(false, false) } } impl Inner { - fn new(fast: bool) -> Self { + fn new(fast: bool, quick_maps: bool) -> Self { Inner { - slots: HashMap::new(), - ranges: BTreeMap::new(), + slots: HashMap::with_hasher(Hashing::new(quick_maps)), + ranges: RangesMap::new(quick_maps), textures: BTreeMap::new(), hulls: Vec::new(), - hull_pos: HashMap::new(), + hull_pos: HashMap::with_hasher(Hashing::new(quick_maps)), active_words: Vec::new(), untracked_hulls: Vec::new(), - ends: HashMap::new(), + ends: HashMap::with_hasher(Hashing::new(quick_maps)), unordered: fast.then(UnorderedIndex::new), } } @@ -246,7 +279,7 @@ impl Inner { match seen { Seen::Buffer(shadow, address, len, uav) => { let key = (Arc::as_ptr(shadow) as usize, *address, address + len, *uav); - let e = self.ranges.entry(key).or_insert_with(|| (0, shadow.clone())); + let e = self.ranges.entry_or(key, || (0, shadow.clone())); let was = e.0; step(&mut e.0); let now = e.0; @@ -378,22 +411,40 @@ impl Viewed { /// Batched [`Viewed::set`]: computes each unique view's entry outside the /// lock (deduplicating repeated view pointers) and applies all slot /// updates under one hold of `self.inner`. - #[cfg(windows)] + #[cfg(all(windows, test))] pub(crate) fn set_batch(&self, updates: &[(u32, Option<&View>, bool)]) { + let converted: Vec<(u32, BatchUpdate<'_>)> = updates + .iter() + .map(|&(index, view, made)| match view { + Some(v) => (index, BatchUpdate::View(v, made)), + None => (index, BatchUpdate::Resolved(None)), + }) + .collect(); + self.set_batch_resolved(&converted); + } + + /// Batched slot update accepting both pre-resolved [`Seen`] entries (from + /// `descriptor::host::quick`, avoiding redundant shadow lookups) and + /// unresolved [`View`] references (resolved and deduplicated outside + /// `self.inner`). Applies all slot transitions under one hold of + /// `self.inner`. + #[cfg(windows)] + pub(crate) fn set_batch_resolved(&self, updates: &[(u32, BatchUpdate<'_>)]) { if updates.is_empty() { return; } - let mut cache: HashMap<(usize, bool), Option> = HashMap::new(); + let mut cache: HashMap<(usize, bool), Option, Hashing> = + HashMap::with_hasher(Hashing::new(self.quick_maps)); let mut entries: Vec<(u32, Option)> = Vec::with_capacity(updates.len()); - for &(index, view, made) in updates { - let entry = match view { - None => None, - Some(v) => { - let key = (std::ptr::from_ref(v) as usize, made); + for (index, update) in updates { + let entry = match update { + BatchUpdate::Resolved(entry) => entry.clone(), + BatchUpdate::View(v, made) => { + let key = (std::ptr::from_ref(*v) as usize, *made); cache .entry(key) .or_insert_with(|| { - if made { + if *made { seen(v) } else { Some(Seen::Left(left_kind(v))) @@ -402,7 +453,7 @@ impl Viewed { .clone() } }; - entries.push((index, entry)); + entries.push((*index, entry)); } let mut inner = self.inner.lock().unwrap_or_else(|e| e.into_inner()); let (mut unordered_changed, mut hulls_changed) = (false, false); @@ -429,6 +480,18 @@ impl Viewed { } } + /// Active buffer range `(copy_ptr, address, len, uav)` recorded for slot + /// `index`, if it currently holds a buffer view (tests). + #[cfg(test)] + pub(crate) fn range_at(&self, index: u32) -> Option { + match self.inner.lock().unwrap_or_else(|e| e.into_inner()).slots.get(&index)? { + Seen::Buffer(shadow, address, len, uav) => { + Some((Arc::as_ptr(shadow) as usize, *address, *len, *uav)) + } + _ => None, + } + } + /// A slot whose unordered view reaches `len` bytes of `shadow` at /// `address` (tests: no view or resource needed). #[cfg(test)] @@ -837,11 +900,10 @@ pub(crate) fn widened_writes_into(viewed: &Viewed, out: &mut Vec<(Arc, u if !crate::under_wine() { return; } + let start = out.len(); + let inner = viewed.inner.lock().unwrap_or_else(|e| e.into_inner()); out.extend( - viewed - .inner - .lock() - .unwrap_or_else(|e| e.into_inner()) + inner .ranges .iter() .filter(|((_, address, end, uav), _)| *uav && address < end) @@ -849,6 +911,13 @@ pub(crate) fn widened_writes_into(viewed: &Viewed, out: &mut Vec<(Arc, u (shadow.clone(), *address as usize, (end - address) as usize) }), ); + let hashed = inner.ranges.is_hashed(); + drop(inner); + if hashed { + out[start..].sort_unstable_by_key(|(s, address, len)| { + (Arc::as_ptr(s) as usize, *address, *len) + }); + } } /// Cached UAV buffer ranges for widening (`VICTORY_CENSUS_FAST=1`). Returns @@ -963,6 +1032,7 @@ pub(crate) fn log(frames: f64) { let inner = viewed.inner.lock().unwrap_or_else(|e| e.into_inner()); let copies = { let mut c: Vec = inner.ranges.keys().map(|k| k.0).collect(); + c.sort_unstable(); c.dedup(); c.len() }; @@ -1523,6 +1593,259 @@ void main(uint3 id : SV_DispatchThreadID) { } } + /// All four `(VICTORY_CENSUS_FAST, VICTORY_QUICK_SYNC=maps)` combinations + /// produce identical `widened_writes_into`, `unordered_writes`, hulls, + /// `hull_generation` invariance across interior edits, and per-slot ranges + /// across single sets, `set_batch_resolved` (mixing pre-resolved + /// `Seen::shader_buffer` and `BatchUpdate::View`), clears, and randomized + /// updates. + #[test] + fn quick_maps_matches_standard_with_and_without_fast_census() { + let Some(_host) = crate::host::host() else { + return; // no host GPU here + }; + let bufs = [ + resource(1, 0x1000, 1, 0, 1), + resource(1, 0x1000, 1, 0, 1), + ]; + let mut shadows = Vec::new(); + for &buf in &bufs { + let (ptr, size) = crate::resource::buffer_bytes(buf).unwrap(); + shadows.push(( + ptr as u64, + crate::shadow::find(ptr as u64, size).expect("shadow"), + )); + } + let uav0 = View::Unordered(bufs[0] as usize, 0, Some([39, 1, 0, 0, 64, 0, 0, 0, 1, 0])); + let uav1 = View::Unordered(bufs[1] as usize, 0, Some([39, 1, 16, 0, 32, 0, 0, 0, 1, 0])); + let srv0 = View::Shader(bufs[0] as usize, Some([39, 1, 0x1688, 0, 0, 0, 64, 0, 1, 0])); + let srv1 = View::Shader(bufs[1] as usize, Some([39, 1, 0x1688, 0, 8, 0, 48, 0, 1, 0])); + let resolved_srv0 = Seen::shader_buffer(shadows[0].1.clone(), shadows[0].0, 64 * 4); + let resolved_srv1 = Seen::shader_buffer(shadows[1].1.clone(), shadows[1].0 + 32, 48 * 4); + + let variants = [ + Viewed::with_options(false, false), + Viewed::with_options(false, true), + Viewed::with_options(true, false), + Viewed::with_options(true, true), + ]; + let raw_writes = |writes: &[(Arc, usize, usize)]| -> Vec<(usize, usize, usize)> { + writes + .iter() + .map(|(s, a, l)| (Arc::as_ptr(s) as usize, *a, *l)) + .collect() + }; + let normalize_writes = |writes: &[(Arc, usize, usize)]| { + let mut out = raw_writes(writes); + out.sort_unstable(); + out + }; + let normalize_hulls = |viewed: &Viewed| { + let mut out: Vec<_> = viewed + .ranges() + .iter() + .map(|h| (Arc::as_ptr(&h.0) as usize, h.1, h.2, h.3)) + .collect(); + out.sort_unstable(); + out + }; + let assert_all_equal = |label: &str| { + let mut base_writes = Vec::new(); + widened_writes_into(&variants[0], &mut base_writes); + let base_raw = raw_writes(&base_writes); + let base_norm = normalize_writes(&base_writes); + let base_hulls = normalize_hulls(&variants[0]); + for (idx, v) in variants.iter().enumerate() { + let mut got_writes = Vec::new(); + widened_writes_into(v, &mut got_writes); + assert_eq!( + raw_writes(&got_writes), + base_raw, + "{label}: variant {idx} widened_writes_into order" + ); + if let Some(fast_writes) = unordered_writes(v) { + assert_eq!( + normalize_writes(&fast_writes), + base_norm, + "{label}: variant {idx} unordered_writes" + ); + } + assert_eq!( + normalize_hulls(v), + base_hulls, + "{label}: variant {idx} hulls" + ); + for slot in 0..32u32 { + assert_eq!( + v.range_at(slot), + variants[0].range_at(slot), + "{label}: variant {idx} slot {slot}" + ); + } + } + }; + + // Mix pre-resolved SRVs, unresolved views, duplicates, and clears. + for (idx, v) in variants.iter().enumerate() { + if idx % 2 == 1 { + v.set_batch_resolved(&[ + (0, BatchUpdate::Resolved(resolved_srv0.clone())), + (1, BatchUpdate::Resolved(resolved_srv0.clone())), + (2, BatchUpdate::Resolved(resolved_srv1.clone())), + (3, BatchUpdate::View(&uav0, true)), + (4, BatchUpdate::View(&uav1, true)), + (5, BatchUpdate::View(&uav1, false)), + ]); + } else { + v.set_batch(&[ + (0, Some(&srv0), true), + (1, Some(&srv0), true), + (2, Some(&srv1), true), + (3, Some(&uav0), true), + (4, Some(&uav1), true), + (5, Some(&uav1), false), + ]); + } + } + assert_all_equal("initial batch"); + + // Interior view edits via `set_batch_resolved` must leave `hull_generation` unchanged. + let inner_srv = Seen::shader_buffer(shadows[0].1.clone(), shadows[0].0 + 16, 32); + let inner_uav = View::Unordered(bufs[0] as usize, 0, Some([39, 1, 8, 0, 16, 0, 0, 0, 1, 0])); + let gens_before: Vec = variants.iter().map(Viewed::hull_generation).collect(); + for v in &variants { + v.set_batch_resolved(&[ + (6, BatchUpdate::Resolved(inner_srv.clone())), + (7, BatchUpdate::View(&inner_uav, true)), + ]); + } + for (idx, v) in variants.iter().enumerate() { + assert_eq!( + v.hull_generation(), + gens_before[idx], + "variant {idx} interior edit via set_batch_resolved must not bump hull_generation" + ); + } + assert_all_equal("after interior set_batch_resolved"); + for v in &variants { + v.set_batch_resolved(&[ + (6, BatchUpdate::Resolved(None)), + (7, BatchUpdate::Resolved(None)), + ]); + } + for (idx, v) in variants.iter().enumerate() { + assert_eq!( + v.hull_generation(), + gens_before[idx], + "variant {idx} interior clear via set_batch_resolved must not bump hull_generation" + ); + } + assert_all_equal("after interior clear"); + + let views = [&srv0, &srv1, &uav0, &uav1]; + let mut rng = 0xD1B5_4A32_D192_ED03u64; + let mut next = || { + rng ^= rng << 13; + rng ^= rng >> 7; + rng ^= rng << 17; + rng + }; + for step in 0..300usize { + let slot = (next() % 32) as u32; + let pick = (next() % 5) as usize; + let made = !next().is_multiple_of(7); + for v in &variants { + if pick == 4 { + v.set(slot, None, false); + } else { + v.set(slot, Some(views[pick]), made); + } + } + if step % 25 == 0 { + assert_all_equal("randomized step"); + } + } + assert_all_equal("final"); + + drop(variants); + for buf in bufs { + crate::object::release_ref(buf); + } + } + + /// `widened_writes_into` must produce the exact same deterministic order + /// with `quick_maps = true` as with `quick_maps = false`, while preserving + /// any entries already in `out` before the call. + #[test] + fn widened_writes_into_order_matches_tree_when_quick_maps_enabled() { + let Some(_host) = crate::host::host() else { + return; // no host GPU here + }; + let bufs = [ + resource(1, 0x2000, 1, 0, 1), + resource(1, 0x2000, 1, 0, 1), + resource(1, 0x2000, 1, 0, 1), + ]; + let mut shadows = Vec::new(); + for &buf in &bufs { + let (ptr, size) = crate::resource::buffer_bytes(buf).unwrap(); + shadows.push(( + ptr as u64, + crate::shadow::find(ptr as u64, size).expect("shadow"), + )); + } + + let tree = Viewed::with_options(false, false); + let hash = Viewed::with_options(false, true); + // Insert ranges across several shadows in deliberately scrambled order + // (including distinct lengths at the same address and reverse offsets). + let specs: &[(usize, u64, u64)] = &[ + (2, 0x800, 0x100), + (0, 0x400, 0x200), + (1, 0x100, 0x80), + (0, 0x400, 0x40), + (2, 0x0, 0x100), + (1, 0x900, 0x100), + (0, 0x0, 0x100), + (0, 0x800, 0x100), + (2, 0x200, 0x180), + (1, 0x100, 0x200), + ]; + for &(bi, off, len) in specs { + let (base, ref shadow) = shadows[bi]; + tree.add_unordered(shadow, base + off, len); + hash.add_unordered(shadow, base + off, len); + } + + // Seed `out` with a sentinel entry to confirm only the newly appended + // slice is sorted, leaving prior entries in place. + let sentinel = (shadows[2].1.clone(), usize::MAX - 16, 16usize); + let mut tree_out = vec![sentinel.clone()]; + let mut hash_out = vec![sentinel]; + widened_writes_into(&tree, &mut tree_out); + widened_writes_into(&hash, &mut hash_out); + + let keys = |v: &[(Arc, usize, usize)]| -> Vec<(usize, usize, usize)> { + v.iter() + .map(|(s, a, l)| (Arc::as_ptr(s) as usize, *a, *l)) + .collect() + }; + assert_eq!( + keys(&hash_out), + keys(&tree_out), + "quick_maps=true must match BTreeMap order without caller sorting" + ); + if crate::under_wine() { + assert_eq!(hash_out.len(), 1 + specs.len()); + assert_eq!(hash_out[0].1, usize::MAX - 16, "sentinel stays first"); + } + + drop((tree_out, hash_out, tree, hash, shadows)); + for buf in bufs { + crate::object::release_ref(buf); + } + } + /// The title writes a buffer and a texture, and views of them and of an /// output buffer into its heap; a shader reaching them only through the /// heap (no table entry names them) reads what the title wrote at diff --git a/crates/victory-gpu/src/census_maps.rs b/crates/victory-gpu/src/census_maps.rs new file mode 100644 index 000000000..c3409ff83 --- /dev/null +++ b/crates/victory-gpu/src/census_maps.rs @@ -0,0 +1,519 @@ +//! Opt-in fast hashing and hash-backed range table for the bindless view +//! registry (`VICTORY_QUICK_SYNC=1`, off by default). +//! +//! During descriptor-heap syncs, the bindless registry (`crate::bindless`) +//! updates slot-to-view and active buffer-range reference counts tens of +//! thousands of times per frame across hundreds of thousands of live entries. +//! Replacing the default `BTreeMap` range table with a hash map and using a +//! lightweight multiply-and-fold hasher for internal integer/tuple keys cuts +//! pointer chasing and per-slot hashing overhead without changing observable +//! registry semantics. +//! +//! Pure `std` so unit tests run on every host as well as under Windows/Wine. + +#![cfg_attr(not(windows), allow(dead_code))] + +use std::collections::{BTreeMap, HashMap, btree_map, hash_map}; +use std::ffi::OsStr; +use std::hash::{BuildHasher, DefaultHasher, Hash, Hasher, RandomState}; +use std::sync::OnceLock; + +/// Parsed `VICTORY_QUICK_SYNC` feature selection. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct QuickSync { + /// Use multiply-and-fold hashing and hash-backed range counts in `bindless`. + pub(crate) maps: bool, + /// Deduplicate and pre-resolve buffer SRV/CBV records per synced heap page. + pub(crate) views: bool, +} + +/// Parses `VICTORY_QUICK_SYNC` (off by default). +/// +/// Recognized values (case-insensitive, comma-separated tokens allowed): +/// - unset, `""`, `"0"`, `"false"`, `"off"` => both off +/// - `"1"`, `"true"`, `"on"`, `"all"` => both on +/// - `"maps"` => fast bindless maps only +/// - `"views"` => per-page quick buffer-SRV/CBV resolution only +/// - `"maps,views"` => both on +pub(crate) fn parse_quick_sync(value: Option<&OsStr>) -> QuickSync { + let Some(raw) = value.and_then(OsStr::to_str) else { + return QuickSync { + maps: false, + views: false, + }; + }; + let trimmed = raw.trim(); + if trimmed.is_empty() { + return QuickSync { + maps: false, + views: false, + }; + } + let mut cfg = QuickSync { + maps: false, + views: false, + }; + for token in trimmed.split(',') { + match token.trim().to_ascii_lowercase().as_str() { + "0" | "false" | "off" | "" => {} + "1" | "true" | "on" | "all" => { + cfg.maps = true; + cfg.views = true; + } + "maps" => cfg.maps = true, + "views" => cfg.views = true, + _ => {} + } + } + cfg +} + +/// Cached `VICTORY_QUICK_SYNC` configuration for this process. +pub(crate) fn quick_sync() -> QuickSync { + static CFG: OnceLock = OnceLock::new(); + *CFG.get_or_init(|| { + let cfg = parse_quick_sync(std::env::var_os("VICTORY_QUICK_SYNC").as_deref()); + if cfg.maps || cfg.views { + tracing::info!( + maps = cfg.maps, + views = cfg.views, + "quick heap sync enabled (VICTORY_QUICK_SYNC)" + ); + } + cfg + }) +} + +/// Whether fast bindless registry maps (`VICTORY_QUICK_SYNC=1` or `=maps`) are enabled. +pub(crate) fn quick_maps() -> bool { + quick_sync().maps +} + +/// Whether per-page quick buffer-SRV/CBV resolution (`VICTORY_QUICK_SYNC=1` or `=views`) is enabled. +pub(crate) fn quick_views() -> bool { + quick_sync().views +} + +/// Hash builder selecting either `std`'s randomized SipHash (`Standard`) or +/// fast 128-bit multiply-and-fold hashing (`Fold`) for trusted internal keys. +#[derive(Clone)] +pub(crate) enum Hashing { + Standard(RandomState), + Fold, +} + +impl Hashing { + pub(crate) fn new(quick: bool) -> Self { + if quick { + Self::Fold + } else { + Self::Standard(RandomState::new()) + } + } +} + +impl BuildHasher for Hashing { + type Hasher = FoldHasher; + + fn build_hasher(&self) -> Self::Hasher { + match self { + Self::Standard(state) => FoldHasher::Standard(state.build_hasher()), + Self::Fold => FoldHasher::Fold(0), + } + } +} + +/// 128-bit odd golden-ratio multiplier for multiply-and-fold mixing. +const FOLD_MULTIPLIER: u128 = 0x9E37_79B9_7F4A_7C15_F39C_C060_5CED_C835; + +/// Hasher produced by [`Hashing`]. +pub(crate) enum FoldHasher { + Standard(DefaultHasher), + Fold(u64), +} + +impl FoldHasher { + #[inline] + fn mix(state: &mut u64, word: u64) { + let product = u128::from(*state ^ word).wrapping_mul(FOLD_MULTIPLIER); + *state = (product as u64) ^ ((product >> 64) as u64); + } +} + +impl Hasher for FoldHasher { + #[inline] + fn finish(&self) -> u64 { + match self { + Self::Standard(h) => h.finish(), + Self::Fold(state) => *state, + } + } + + #[inline] + fn write(&mut self, bytes: &[u8]) { + match self { + Self::Standard(h) => h.write(bytes), + Self::Fold(state) => { + for chunk in bytes.chunks(8) { + let mut buf = [0u8; 8]; + buf[..chunk.len()].copy_from_slice(chunk); + Self::mix(state, u64::from_le_bytes(buf)); + } + // Mix length so byte slices differing only by trailing zero bytes hash distinctly. + Self::mix(state, bytes.len() as u64); + } + } + } + + #[inline] + fn write_u8(&mut self, i: u8) { + match self { + Self::Standard(h) => h.write_u8(i), + Self::Fold(state) => Self::mix(state, u64::from(i)), + } + } + + #[inline] + fn write_u16(&mut self, i: u16) { + match self { + Self::Standard(h) => h.write_u16(i), + Self::Fold(state) => Self::mix(state, u64::from(i)), + } + } + + #[inline] + fn write_u32(&mut self, i: u32) { + match self { + Self::Standard(h) => h.write_u32(i), + Self::Fold(state) => Self::mix(state, u64::from(i)), + } + } + + #[inline] + fn write_u64(&mut self, i: u64) { + match self { + Self::Standard(h) => h.write_u64(i), + Self::Fold(state) => Self::mix(state, i), + } + } + + #[inline] + fn write_usize(&mut self, i: usize) { + match self { + Self::Standard(h) => h.write_usize(i), + Self::Fold(state) => Self::mix(state, i as u64), + } + } +} + +/// Active buffer-range table inside `bindless::Viewed`: either the default +/// `BTreeMap` or a fold-hashed `HashMap` when `quick_maps` is enabled. +pub(crate) enum RangesMap { + Tree(BTreeMap), + Hash(HashMap), +} + +impl RangesMap { + pub(crate) fn new(quick: bool) -> Self { + if quick { + Self::Hash(HashMap::with_hasher(Hashing::Fold)) + } else { + Self::Tree(BTreeMap::new()) + } + } + + /// Whether iteration order is unordered (hash-backed) rather than sorted by key. + #[inline] + pub(crate) fn is_hashed(&self) -> bool { + matches!(self, Self::Hash(_)) + } + + #[inline] + pub(crate) fn entry_or(&mut self, key: K, make: impl FnOnce() -> V) -> &mut V { + match self { + Self::Tree(map) => map.entry(key).or_insert_with(make), + Self::Hash(map) => map.entry(key).or_insert_with(make), + } + } + + #[inline] + pub(crate) fn remove(&mut self, key: &K) -> Option { + match self { + Self::Tree(map) => map.remove(key), + Self::Hash(map) => map.remove(key), + } + } + + #[cfg(any(test, feature = "diagnostics"))] + pub(crate) fn len(&self) -> usize { + match self { + Self::Tree(map) => map.len(), + Self::Hash(map) => map.len(), + } + } + + pub(crate) fn iter(&self) -> RangesIter<'_, K, V> { + match self { + Self::Tree(map) => RangesIter::Tree(map.iter()), + Self::Hash(map) => RangesIter::Hash(map.iter()), + } + } + + #[cfg(any(test, feature = "diagnostics"))] + pub(crate) fn keys(&self) -> RangesKeys<'_, K, V> { + match self { + Self::Tree(map) => RangesKeys::Tree(map.keys()), + Self::Hash(map) => RangesKeys::Hash(map.keys()), + } + } +} + +/// Borrowing iterator over entries of [`RangesMap`] without heap allocation. +pub(crate) enum RangesIter<'a, K, V> { + Tree(btree_map::Iter<'a, K, V>), + Hash(hash_map::Iter<'a, K, V>), +} + +impl<'a, K, V> Iterator for RangesIter<'a, K, V> { + type Item = (&'a K, &'a V); + + #[inline] + fn next(&mut self) -> Option { + match self { + Self::Tree(it) => it.next(), + Self::Hash(it) => it.next(), + } + } +} + +/// Borrowing iterator over keys of [`RangesMap`] without heap allocation. +#[cfg(any(test, feature = "diagnostics"))] +pub(crate) enum RangesKeys<'a, K, V> { + Tree(btree_map::Keys<'a, K, V>), + Hash(hash_map::Keys<'a, K, V>), +} + +#[cfg(any(test, feature = "diagnostics"))] +impl<'a, K, V> Iterator for RangesKeys<'a, K, V> { + type Item = &'a K; + + #[inline] + fn next(&mut self) -> Option { + match self { + Self::Tree(it) => it.next(), + Self::Hash(it) => it.next(), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::HashSet; + + type RangeKey = (usize, u64, u64, bool); + + struct XorShift64(u64); + + impl XorShift64 { + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + + fn range(&mut self, copies: u64, starts: u64) -> RangeKey { + let copy = 0x7000_0000_0000 + (self.next() % copies) as usize * 0x140; + let start = 0x1_0000_0000 + (self.next() % starts) * 16; + let len = 16 + (self.next() % 4096); + (copy, start, start + len, self.next().is_multiple_of(8)) + } + } + + #[test] + fn quick_sync_env_parsing() { + let parse = |s: &str| parse_quick_sync(Some(OsStr::new(s))); + assert_eq!( + parse_quick_sync(None), + QuickSync { + maps: false, + views: false + } + ); + for off in ["", " ", "0", "false", "OFF", "False", "unknown"] { + assert_eq!( + parse(off), + QuickSync { + maps: false, + views: false + }, + "value {off:?}" + ); + } + for both in ["1", "true", "ON", "all", "maps,views", " views , MAPS "] { + assert_eq!( + parse(both), + QuickSync { + maps: true, + views: true + }, + "value {both:?}" + ); + } + assert_eq!( + parse("maps"), + QuickSync { + maps: true, + views: false + } + ); + assert_eq!( + parse("views"), + QuickSync { + maps: false, + views: true + } + ); + } + + #[test] + fn standard_hashing_matches_random_state() { + let state = RandomState::new(); + let hashing = Hashing::Standard(state.clone()); + for slot in [0u32, 1, 63, 64, 65_535, 639_999, u32::MAX] { + assert_eq!(hashing.hash_one(slot), state.hash_one(slot)); + } + let key: RangeKey = (0x7000_1234_5678, 0x1_0000_0040, 0x1_0000_0140, true); + assert_eq!(hashing.hash_one(key), state.hash_one(key)); + assert_eq!(hashing.hash_one(b"sample-key"), state.hash_one(b"sample-key")); + } + + #[test] + fn fold_hasher_avalanche_and_uniqueness() { + let fold = Hashing::Fold; + let distribution = |hashes: &[u64]| { + let low: HashSet = hashes.iter().map(|h| h & 0xFFFF).collect(); + let high: HashSet = hashes.iter().map(|h| h >> 57).collect(); + (low.len(), high.len()) + }; + + let slot_hashes: Vec = (0..1u32 << 16).map(|s| fold.hash_one(s)).collect(); + let (low, high) = distribution(&slot_hashes); + assert!( + low > 38_000 && high == 128, + "sequential slot indices: {low} buckets, {high} tags" + ); + + let base_copy = 0x7000_1234_5000usize; + let addr_hashes: Vec = (0..1u64 << 16) + .map(|i| { + fold.hash_one(( + base_copy, + 0x1_0000_0000 + 16 * i, + 0x1_0000_0100 + 16 * i, + false, + )) + }) + .collect(); + let (low, high) = distribution(&addr_hashes); + assert!( + low > 38_000 && high == 128, + "sequential buffer addresses: {low} buckets, {high} tags" + ); + + let copy_hashes: Vec = (0..1usize << 16) + .map(|i| fold.hash_one((base_copy + 0x140 * i, 0x1_0000_0000u64, 0x1_0000_0100u64, false))) + .collect(); + let (low, high) = distribution(©_hashes); + assert!( + low > 38_000 && high == 128, + "sequential copy pointers: {low} buckets, {high} tags" + ); + + // Permuting fields, flipping flags, or appending zero bytes must change the hash. + assert_ne!( + fold.hash_one((1usize, 2u64, 3u64, false)), + fold.hash_one((2usize, 1u64, 3u64, false)) + ); + assert_ne!( + fold.hash_one((1usize, 2u64, 3u64, false)), + fold.hash_one((1usize, 2u64, 3u64, true)) + ); + assert_ne!( + fold.hash_one([1u8, 2].as_slice()), + fold.hash_one([1u8, 2, 0].as_slice()) + ); + } + + #[test] + fn ranges_map_hash_matches_tree_under_randomized_workload() { + let mut rng = XorShift64(0x9E37_79B9_7F4A_7C15); + let mut tree_slots: HashMap = + HashMap::with_hasher(Hashing::new(false)); + let mut hash_slots: HashMap = + HashMap::with_hasher(Hashing::new(true)); + let mut tree_ranges: RangesMap = RangesMap::new(false); + let mut hash_ranges: RangesMap = RangesMap::new(true); + + assert!(!tree_ranges.is_hashed()); + assert!(hash_ranges.is_hashed()); + assert!(matches!(tree_ranges, RangesMap::Tree(_))); + assert!(matches!(hash_ranges, RangesMap::Hash(_))); + + let update = |ranges: &mut RangesMap, key: RangeKey, add: bool| { + let count = ranges.entry_or(key, || 0); + *count = if add { + *count + 1 + } else { + count.saturating_sub(1) + }; + if *count == 0 { + ranges.remove(&key); + } + }; + + for step in 0..150_000u64 { + let slot = (rng.next() % 4_096) as u32; + let next_range = (!step.is_multiple_of(7)).then(|| rng.range(32, 64)); + for (slots, ranges) in [ + (&mut tree_slots, &mut tree_ranges), + (&mut hash_slots, &mut hash_ranges), + ] { + if let Some(old) = slots.remove(&slot) { + update(ranges, old, false); + } + if let Some(range) = next_range { + update(ranges, range, true); + slots.insert(slot, range); + } + } + } + + assert_eq!(tree_ranges.len(), hash_ranges.len()); + assert!(tree_ranges.len() > 500); + + let collect_entries = |ranges: &RangesMap| { + let mut out: Vec<(RangeKey, u32)> = ranges.iter().map(|(&k, &v)| (k, v)).collect(); + out.sort_unstable(); + out + }; + let tree_entries = collect_entries(&tree_ranges); + let hash_entries = collect_entries(&hash_ranges); + assert_eq!(tree_entries, hash_entries); + + // Verify counts match exact slot occupancy. + let mut expected: BTreeMap = BTreeMap::new(); + for &range in hash_slots.values() { + *expected.entry(range).or_insert(0) += 1; + } + let expected_entries: Vec<(RangeKey, u32)> = expected.into_iter().collect(); + assert_eq!(hash_entries, expected_entries); + + let mut tree_keys: Vec = tree_ranges.keys().copied().collect(); + let mut hash_keys: Vec = hash_ranges.keys().copied().collect(); + tree_keys.sort_unstable(); + hash_keys.sort_unstable(); + assert_eq!(tree_keys, hash_keys); + } +} diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index ac79d42fe..4da3624af 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -12,6 +12,8 @@ use std::sync::atomic::{AtomicU64, Ordering}; use windows::Win32::Graphics::Direct3D12::*; use windows::Win32::Graphics::Dxgi::Common::*; +mod quick; + use super::paged::Paged; use super::{ VIEW_TAG, View, ViewPin, view_at, view_gen_current, views_at_batch, views_current_into, @@ -1517,6 +1519,18 @@ impl HostHeap { buf_start: u64, buf: &[u8], fast: bool, + ) { + self.sync_slots_bytes_mode(slots, start, step, (buf_start, buf), fast, quick::on()); + } + + fn sync_slots_bytes_mode( + &self, + slots: std::ops::Range, + start: u64, + step: u64, + (buf_start, buf): (u64, &[u8]), + fast: bool, + quick_views: bool, ) { let first = slots.start; let last = slots.end.min(self.count); @@ -1640,7 +1654,7 @@ impl HostHeap { } } if !stale.is_empty() { - self.mirror_synced_batch(&stale, at); + self.mirror_synced_batch(&stale, at, quick_views); } } else { let legacy_fast = sync_fast_enabled(); @@ -1725,7 +1739,12 @@ impl HostHeap { /// of `VIEWS`, `self.made`, `self.kept`, `self.viewed`, and `shadow::READS`, /// deduplicating `prepare` and descriptor creation via [`StagingHeap`] + /// `CopyDescriptorsSimple`. - fn mirror_synced_batch(&self, stale: &[(u32, [u32; 3])], at: impl Fn(u32) -> u64) { + /// + /// When `quick_views` is enabled on a view heap, each unique buffer-SRV or + /// CBV record in the page is resolved once outside `self.made` via + /// [`quick::resolve`], avoiding repeated shadow and bindless lookups under + /// `self.made`. + fn mirror_synced_batch(&self, stale: &[(u32, [u32; 3])], at: impl Fn(u32) -> u64, quick_views: bool) { let _making = MakeTimer(std::time::Instant::now(), stale.len() as u64); struct CachedTemplate { src: D3D12_CPU_DESCRIPTOR_HANDLE, @@ -1733,9 +1752,14 @@ impl HostHeap { mark: Option<(u32, u32)>, } + let use_quick = quick_views && !self.sampler; let mut unique_keys: Vec = Vec::new(); let mut key_counts: Vec = Vec::new(); - let mut key_to_idx: HashMap = HashMap::new(); + let mut key_to_idx: HashMap = + HashMap::with_capacity_and_hasher( + stale.len(), + crate::census_maps::Hashing::new(use_quick), + ); let mut slot_key_idx: Vec> = Vec::with_capacity(stale.len()); for &(_, [tag, view, generation]) in stale { @@ -1769,11 +1793,23 @@ impl HostHeap { let mut clock = std::time::Instant::now(); let at_once = placed_at_once(); let pins = views_at_batch(&unique_keys); + let mut resolved_bufs: Vec> = + Vec::with_capacity(if use_quick { unique_keys.len() } else { 0 }); let mut defer: Vec = Vec::with_capacity(unique_keys.len()); let mut is_tex: Vec = Vec::with_capacity(unique_keys.len()); let mut strides: Vec = Vec::with_capacity(unique_keys.len()); for pin in &pins { if let Some(view) = pin.as_deref() { + if use_quick && let Some(resolved_buf) = quick::resolve(view) { + strides.push(resolved_buf.stride); + defer.push(false); + is_tex.push(false); + resolved_bufs.push(Some(resolved_buf)); + continue; + } + if use_quick { + resolved_bufs.push(None); + } let later = defer_placed(view, at_once); if !later { prepare(view); @@ -1782,6 +1818,9 @@ impl HostHeap { is_tex.push(is_texture(view)); strides.push(view_stride(view) | view_kind(view)); } else { + if use_quick { + resolved_bufs.push(None); + } defer.push(false); is_tex.push(false); strides.push(0); @@ -1804,7 +1843,8 @@ impl HostHeap { let mut kept_updates: Vec<(u32, Kept)> = Vec::with_capacity(stale.len()); let mut copy_dsts: Vec = Vec::with_capacity(stale.len()); let mut copy_srcs: Vec = Vec::with_capacity(stale.len()); - let mut viewed_updates: Vec<(u32, Option<&View>, bool)> = if self.sampler { + let mut viewed_updates: Vec<(u32, crate::bindless::BatchUpdate<'_>)> = if self.sampler + { Vec::new() } else { Vec::with_capacity(stale.len()) @@ -1815,13 +1855,35 @@ impl HostHeap { let (mut unchanged, mut from_template, mut deferred, mut nulled) = (0u64, 0u64, 0u64, 0u64); let mut created: Vec = Vec::new(); let mut create_us = 0u64; - let mut make_marked = |view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE, key: u64| { + let make_marked = |view: &View, + at: D3D12_CPU_DESCRIPTOR_HANDLE, + key: u64, + create_us: &mut u64, + created: &mut Vec| { let started = std::time::Instant::now(); let made = make_marked(view, at); - create_us += started.elapsed().as_micros() as u64; + *create_us += started.elapsed().as_micros() as u64; created.push(key); made }; + let create_resolved = |h: &crate::host::Host, + resolved_buf: &quick::ResolvedBuffer, + at: D3D12_CPU_DESCRIPTOR_HANDLE, + key: u64, + create_us: &mut u64, + created: &mut Vec| { + let started = std::time::Instant::now(); + // SAFETY: live buffer held by `resolved_buf` and slot of our heap. + unsafe { + h.device.CreateShaderResourceView( + &resolved_buf.buffer, + Some(&resolved_buf.desc), + at, + ); + } + *create_us += started.elapsed().as_micros() as u64; + created.push(key); + }; let addr_data = self .addresses .get() @@ -1846,7 +1908,8 @@ impl HostHeap { let addr = at(index); // Re-read live title memory under `self.made`: if a title // thread overwrote the slot since the page snapshot (including - // during `prepare`), defer to `mirror` after dropping locks. + // during `prepare` or `quick::resolve`), defer to `mirror` + // after dropping locks. // SAFETY: the caller holds the heap alive until the sync completes. let mut raw = [0u8; 12]; if span_read { @@ -1897,7 +1960,8 @@ impl HostHeap { } kept_updates.push((index, None)); if !self.sampler { - viewed_updates.push((index, None, false)); + viewed_updates + .push((index, crate::bindless::BatchUpdate::Resolved(None))); } finalize.push((index, 0, 0)); } @@ -1907,13 +1971,18 @@ impl HostHeap { unchanged += 1; continue; } + let resolved_buf = resolved_bufs.get(kidx).and_then(Option::as_ref); self.ready[index as usize].store(0, Ordering::Relaxed); self.synced[index as usize].store(0, Ordering::Relaxed); self.write_stride(index, strides[kidx]); if let Some(data) = addr_data && index < addr_slots { - write_address(data, index as usize, Some(view)); + if let Some(resolved_buf) = resolved_buf { + write_buffer_address(data, index as usize, resolved_buf.address); + } else { + write_address(data, index as usize, Some(view)); + } } let later = defer[kidx]; let keep_old = @@ -1935,6 +2004,66 @@ impl HostHeap { } } (None, None) + } else if let Some(resolved_buf) = resolved_buf { + if key_counts[kidx] >= 2 + && let (Some(h), Some(st)) = (host, staging) + { + if let Some(tpl) = &templates[kidx] { + from_template += 1; + copy_dsts.push(self.cpu(index)); + copy_srcs.push(tpl.src); + (tpl.kept.clone(), None) + } else if next_template < st.count { + let t = next_template; + next_template += 1; + create_resolved( + h, + resolved_buf, + st.cpu(t), + key, + &mut create_us, + &mut created, + ); + let k = Some(Some((resolved_buf.buffer.clone(), resolved_buf.held()))); + let src = st.cpu(t); + copy_dsts.push(self.cpu(index)); + copy_srcs.push(src); + templates[kidx] = Some(CachedTemplate { + src, + kept: k.clone(), + mark: None, + }); + (k, None) + } else { + create_resolved( + h, + resolved_buf, + self.cpu(index), + key, + &mut create_us, + &mut created, + ); + ( + Some(Some((resolved_buf.buffer.clone(), resolved_buf.held()))), + None, + ) + } + } else if let Some(h) = host { + create_resolved( + h, + resolved_buf, + self.cpu(index), + key, + &mut create_us, + &mut created, + ); + ( + Some(Some((resolved_buf.buffer.clone(), resolved_buf.held()))), + None, + ) + } else { + (None, None) + } } else if key_counts[kidx] >= 2 && let (Some(_), Some(st)) = (host, staging) { @@ -1946,7 +2075,8 @@ impl HostHeap { } else if next_template < st.count { let t = next_template; next_template += 1; - let (k, m) = make_marked(view, st.cpu(t), key); + let (k, m) = + make_marked(view, st.cpu(t), key, &mut create_us, &mut created); let src = if k.is_none() && !self.sampler { st.cpu(null_slot_index(false, Some(view))) } else { @@ -1961,7 +2091,8 @@ impl HostHeap { }); (k, m) } else { - let (k, m) = make_marked(view, self.cpu(index), key); + let (k, m) = + make_marked(view, self.cpu(index), key, &mut create_us, &mut created); if k.is_none() && !self.sampler { let null_slot = null_slot_index(false, Some(view)); copy_dsts.push(self.cpu(index)); @@ -1970,7 +2101,8 @@ impl HostHeap { (k, m) } } else { - let (k, m) = make_marked(view, self.cpu(index), key); + let (k, m) = + make_marked(view, self.cpu(index), key, &mut create_us, &mut created); if k.is_none() && !self.sampler { if let (Some(_), Some(st)) = (host, staging) { let null_slot = null_slot_index(false, Some(view)); @@ -1987,7 +2119,17 @@ impl HostHeap { self.set_mark(index, mark); } if !self.sampler { - viewed_updates.push((index, Some(view), kept.is_some())); + if let Some(resolved_buf) = resolved_buf + && kept.is_some() + { + viewed_updates.push(( + index, + crate::bindless::BatchUpdate::Resolved(resolved_buf.seen.clone()), + )); + } else { + viewed_updates + .push((index, crate::bindless::BatchUpdate::View(view, kept.is_some()))); + } } let kept = kept.flatten(); let ready = if is_tex[kidx] && kept.is_none() { @@ -2040,7 +2182,7 @@ impl HostHeap { self.keep_batch(kept_updates, &mut retired); lap(S::KeepUs, &mut clock); if !self.sampler { - self.viewed.set_batch(&viewed_updates); + self.viewed.set_batch_resolved(&viewed_updates); } lap(S::ViewedUs, &mut clock); crate::shadow::forget_reads(&forgot_reads); @@ -2898,6 +3040,14 @@ fn write_address(data: usize, index: usize, view: Option<&View>) { unsafe { ((data + 16 * index) as *mut [u32; 4]).write_unaligned(words) }; } +/// Fast path of [`write_address`] for pre-resolved buffer views (never a texture). +fn write_buffer_address(data: usize, index: usize, address: u64) { + let words = [address as u32, (address >> 32) as u32 & 0xFFFF, 0, 0]; + // SAFETY: the mapped view addresses hold 16 bytes per title and dynamic + // slot (below `address_slots`). + unsafe { ((data + 16 * index) as *mut [u32; 4]).write_unaligned(words) }; +} + /// A texture view's console image descriptor dwords 0-3 as far as its size /// goes: width - 1 and height - 1 of the resource's level 0 (dword 1 bits /// 30-31, dword 2 bits 0-13 and 14-29), dword 3 an identity swizzle, the diff --git a/crates/victory-gpu/src/descriptor/host/quick.rs b/crates/victory-gpu/src/descriptor/host/quick.rs new file mode 100644 index 000000000..dfae81c04 --- /dev/null +++ b/crates/victory-gpu/src/descriptor/host/quick.rs @@ -0,0 +1,680 @@ +//! Per-page deduplicated buffer-SRV and CBV resolution for fast heap syncs +//! (`VICTORY_QUICK_SYNC=1` or `VICTORY_QUICK_SYNC=views`, off by default). +//! +//! During `HostHeap::mirror_synced_batch`, most stale title heap slots hold +//! buffer shader-resource views or constant buffer views, often repeated +//! across many slots in the same 64 KiB page. On the standard path, each +//! unique record resolves its host shadow copy three times (`prepare`, +//! `make_marked`/`buffer_srv`, and `bindless::seen`), with the latter two +//! running under `HostHeap::made`. +//! +//! When enabled, [`resolve`] resolves each unique buffer-SRV / CBV record once +//! per page outside `HostHeap::made` — computing the host buffer, final D3D12 +//! SRV descriptor (including 3-channel widening and `raw_structured` lowering), +//! held resource source, view-stride entry, view-address word, and +//! `bindless::Seen` entry. `mirror_synced_batch` then stamps every matching +//! slot through its `StagingHeap` templates, `keep_batch`, and +//! `Viewed::set_batch_resolved`. All non-buffer views, textures, UAVs, +//! samplers, placed textures, and refused/edge-case views return `None` and +//! stay on the standard `prepare` + `make_marked` path. + +use std::sync::Arc; + +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; + +use super::{ + HeldSource, element_size, in_buffer, raw_structured, srv_desc, view_kind, view_stride, + widened_format, widened_w, +}; +use crate::bindless::Seen; +use crate::descriptor::View; +use crate::shadow::{Shadow, Widened}; + +/// Whether per-page quick buffer-SRV / CBV resolution is enabled +/// (`VICTORY_QUICK_SYNC=1` or `=views`). +pub(super) fn on() -> bool { + crate::census_maps::quick_views() +} + +/// Pre-resolved host buffer view and side-table data for one unique buffer +/// SRV or CBV record within a synced page. +pub(super) struct ResolvedBuffer { + pub(super) buffer: ID3D12Resource, + pub(super) desc: D3D12_SHADER_RESOURCE_VIEW_DESC, + shadow: Arc, + own: bool, + widened: Option>, + pub(super) stride: u32, + /// Title address stored in `HostHeap::addresses` (`0` for `View::Constant`, + /// matching `write_address` / `buffer_range`). + pub(super) address: u64, + pub(super) seen: Option, +} + +impl ResolvedBuffer { + /// Returns the secondary lifetime handle held beside the host buffer in + /// `HostHeap::kept`, matching `buffer_srv`. + pub(super) fn held(&self) -> Option { + match &self.widened { + Some(widened) => Some(HeldSource::Widened(widened.clone(), self.shadow.clone())), + None => self.own.then(|| HeldSource::Shadow(self.shadow.clone())), + } + } +} + +#[cfg(test)] +fn run_resolve_hooks() { + super::tests::while_preparing(); + tests::run_local_resolve_hook(); +} + +/// Resolves a buffer SRV, placed buffer SRV, or constant buffer view outside +/// `HostHeap::made`, producing the exact host descriptor, held source, stride, +/// view address, and `bindless::Seen` entry that `make` + `buffer_srv` + +/// `bindless::seen` would produce. +/// +/// Returns `None` for any texture, UAV, sampler, placed texture, refused view, +/// or edge case (zero/unaligned CBV, unaligned structured view) so the caller +/// falls back to the standard path identically. +pub(super) fn resolve(view: &View) -> Option { + let (address, mut desc, constant, has_view_address) = match view { + &View::Constant(address, size) => { + let len = u64::from(size); + if size == 0 || !size.is_multiple_of(4) { + return None; + } + #[cfg(test)] + run_resolve_hooks(); + let shadow = crate::shadow::find(address, len)?; + if shadow.left(address) < len { + return None; + } + let desc = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R32_TYPELESS, + ViewDimension: D3D12_SRV_DIMENSION_BUFFER, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_SRV { + NumElements: size / 4, + Flags: D3D12_BUFFER_SRV_FLAG_RAW, + ..Default::default() + }, + }, + }; + (address, desc, Some(shadow), false) + } + View::Shader(resource, Some(words)) => { + let resource = *resource as crate::object::This; + let (data, _) = crate::resource::buffer_bytes(resource)?; + if crate::resource::made_copy(resource).is_some() { + return None; + } + let desc = srv_desc(words); + if desc.ViewDimension != D3D12_SRV_DIMENSION_BUFFER { + return None; + } + #[cfg(test)] + run_resolve_hooks(); + (data as u64, desc, None, true) + } + View::Placed(false, resource, words) if resource[0] == 1 => { + let desc = srv_desc(words[..10].try_into().ok()?); + if desc.ViewDimension != D3D12_SRV_DIMENSION_BUFFER { + return None; + } + let address = u64::from(words[10]) | u64::from(words[11]) << 32; + #[cfg(test)] + run_resolve_hooks(); + (address, desc, None, true) + } + _ => return None, + }; + + let element = element_size(&desc); + if element == 0 { + return None; + } + // SAFETY: `desc.ViewDimension == D3D12_SRV_DIMENSION_BUFFER` verified above. + let (first_elem, count, struct_stride) = unsafe { + let b = desc.Anonymous.Buffer; + (b.FirstElement, b.NumElements, u64::from(b.StructureByteStride)) + }; + let start = address.checked_add(first_elem.checked_mul(element)?)?; + let len = u64::from(count).checked_mul(element)?; + + let (shadow, own) = match &constant { + Some(found) if found.offset(start).is_multiple_of(element) => (found.clone(), false), + _ => crate::shadow::for_view(start, len, element)?, + }; + let first = shadow.offset(start) / element; + if !in_buffer(&shadow.buffer, first, count, element) { + return None; + } + + let widened = if crate::under_wine() + && matches!(desc.Format.0, 6..=8) + && let Some(w) = widened_w(desc.Format.0) + { + shadow.widened(start, u64::from(count) * 12, w) + } else { + None + }; + + let buffer = match &widened { + Some(widened) => { + desc.Format = widened_format(desc.Format.0)?; + desc.Anonymous.Buffer.FirstElement = 0; + desc.Anonymous.Buffer.NumElements = count; + widened.buffer.clone() + } + None => { + desc.Anonymous.Buffer.FirstElement = first; + if struct_stride > 0 && raw_structured() { + let (byte, dwords) = (first * struct_stride, u64::from(count) * struct_stride / 4); + let align = if crate::under_wine() { 4 } else { 16 }; + match u32::try_from(dwords) { + Ok(dwords) if byte.is_multiple_of(align) && struct_stride.is_multiple_of(4) => { + desc.Format = DXGI_FORMAT_R32_TYPELESS; + desc.Anonymous.Buffer = D3D12_BUFFER_SRV { + FirstElement: byte / 4, + NumElements: dwords, + StructureByteStride: 0, + Flags: D3D12_BUFFER_SRV_FLAG_RAW, + }; + } + // Fall back to `buffer_srv` for unaligned structured views and their warning. + _ => return None, + } + } + shadow.buffer.clone() + } + }; + + let seen = match constant { + Some(found) => Seen::shader_buffer(found, address, len), + None => Seen::shader_buffer(shadow.clone(), start, len), + }; + + Some(ResolvedBuffer { + buffer, + desc, + shadow, + own, + widened, + stride: view_stride(view) | view_kind(view), + address: if has_view_address { start } else { 0 }, + seen, + }) +} + +#[cfg(test)] +mod tests { + use std::sync::atomic::Ordering; + + use super::*; + use crate::backend::HostGpu; + use crate::bindless::Viewed; + use crate::descriptor::host::{HostHeap, host}; + + thread_local! { + static LOCAL_RESOLVE_HOOK: std::cell::RefCell>> = + const { std::cell::RefCell::new(None) }; + } + + pub(super) fn run_local_resolve_hook() { + let hook = LOCAL_RESOLVE_HOOK.with(|h| h.borrow_mut().take()); + if let Some(hook) = hook { + hook(); + } + } + + type SlotState = ( + bool, + bool, + u64, + u64, + u32, + (u32, u32), + Option, + Option, + ); + + fn slot_state(heap: &HostHeap, index: u32) -> SlotState { + let stride = heap.strides.as_ref().map_or(0, |(_, data)| { + // SAFETY: one dword per slot in the mapped stride table. + unsafe { (*data as *const u32).add(index as usize).read_volatile() } + }); + let mark = heap.marks.as_ref().map_or((0, 0), |(_, data)| { + // SAFETY: two dwords per slot in the mapped mark table. + unsafe { + let p = (*data as *const u32).add(2 * index as usize); + (p.read_volatile(), p.add(1).read_volatile()) + } + }); + let synced = heap.synced[index as usize].load(Ordering::Acquire); + let ready = heap.ready[index as usize].load(Ordering::Acquire); + ( + heap.made(index), + heap.kept(index), + synced, + ready, + stride, + mark, + heap.address_at(index), + heap.viewed.range_at(index), + ) + } + + fn normalize_writes(writes: &[(Arc, usize, usize)]) -> Vec<(usize, usize, usize)> { + let mut out: Vec<_> = writes + .iter() + .map(|(s, a, l)| (Arc::as_ptr(s) as usize, *a, *l)) + .collect(); + out.sort_unstable(); + out + } + + fn make_texture_resource() -> crate::object::This { + let desc: [u32; 14] = [3, 0, 0, 0, 4, 0, 1, 1 | 1 << 16, 28, 1, 0, 0x100, 0, 0]; + let properties = [1u32, 0, 0, 0, 0]; + let mut out = std::ptr::null(); + let iid = crate::object::guid( + 0x696442be, + 0xa72e, + 0x4059, + [0xbc, 0x79, 0x5b, 0x5c, 0x98, 0x04, 0x0f, 0xad], + ); + let hr = crate::resource::create_committed( + std::ptr::null(), + properties.as_ptr().cast(), + 0, + desc.as_ptr().cast(), + 0, + std::ptr::null(), + &iid, + &mut out, + ); + assert_eq!(hr, crate::object::S_OK); + out + } + + /// Compares `quick=true` (+ `VICTORY_CENSUS_FAST=1` + `quick_maps=true`) + /// against `quick=false` (standard maps) across CBVs, buffer SRVs, + /// structured SRVs, placed buffer SRVs, 3-channel widened SRVs, textures, + /// placed textures, UAVs, refused views, duplicates, overwrites, and clears. + #[test] + fn quick_sync_matches_standard_across_buffer_views_textures_uavs_and_duplicates() { + if host().is_none() { + return; // no host GPU here + } + let buf = crate::resource::test_buffer(4096); + let (buf_ptr, buf_len) = crate::resource::buffer_bytes(buf).expect("buffer bytes"); + crate::shadow::register(buf as usize, buf_ptr as u64, buf_len); + let memory = buf_ptr as u64; + + let tex = make_texture_resource(); + let placed_tex_mem = vec![0u8; 4096]; + let placed_tex_addr = placed_tex_mem.as_ptr() as u64; + + const SLOTS: u32 = 32; + let mut title_heap = vec![0u8; SLOTS as usize * 32]; + let start = title_heap.as_ptr() as u64; + let at = |i: u32| start + u64::from(i) * 32; + let null = std::ptr::null(); + + // 0..=2: duplicate typed R8_UINT buffer SRVs (tests StagingHeap template stamping). + let srv_r8 = [62u32, 1, 0x1688, 0, 0, 0, 256, 0, 0, 0]; + for i in 0..=2 { + crate::descriptor::create_srv(null, buf, &srv_r8, at(i)); + } + // 3: subrange typed R8_UINT buffer SRV. + crate::descriptor::create_srv(null, buf, &[62, 1, 0x1688, 0, 16, 0, 48, 0, 0, 0], at(3)); + // 4..=5: duplicate structured SRVs (16-byte stride, FirstElement=1, exercises raw_structured). + let srv_struct = [0u32, 1, 0x1688, 0, 1, 0, 8, 16, 0, 0]; + crate::descriptor::create_srv(null, buf, &srv_struct, at(4)); + crate::descriptor::create_srv(null, buf, &srv_struct, at(5)); + // 6: placed buffer SRV off element alignment (12-byte stride at +4B -> own exact shadow copy). + let mut placed_buf = [0u32; 16]; + placed_buf[..10].copy_from_slice(&[0, 1, 0x1688, 0, 0, 0, 8, 12, 0, 0]); + (placed_buf[10], placed_buf[11]) = ((memory + 4) as u32, ((memory + 4) >> 32) as u32); + let mut placed_buf_res = [0u32; 14]; + (placed_buf_res[0], placed_buf_res[4]) = (1, 256); + crate::descriptor::create_placed_srv(null, &placed_buf_res, &placed_buf, at(6)); + // 7..=8: duplicate constant buffers (aligned dword multiple). + let cbv = [memory as u32, (memory >> 32) as u32, 64, 0]; + crate::descriptor::create_cbv(null, &cbv, at(7)); + crate::descriptor::create_cbv(null, &cbv, at(8)); + // 9: unaligned-size CBV (falls back to standard path). + crate::descriptor::create_cbv(null, &[memory as u32, (memory >> 32) as u32, 62, 0], at(9)); + // 10..=11: duplicate 3-channel R32G32B32_FLOAT SRVs (widened under Wine). + let srv_rgb32f = [6u32, 1, 0x1688, 0, 0, 0, 8, 0, 0, 0]; + crate::descriptor::create_srv(null, buf, &srv_rgb32f, at(10)); + crate::descriptor::create_srv(null, buf, &srv_rgb32f, at(11)); + // 12: 3-channel R32G32B32_UINT SRV. + crate::descriptor::create_srv(null, buf, &[7, 1, 0x1688, 0, 0, 0, 8, 0, 0, 0], at(12)); + // 13: regular 2D texture SRV (standard path). + crate::descriptor::create_srv(null, tex, std::ptr::null(), at(13)); + // 14: placed 2D texture SRV (left null on sync, ready == 0). + let tex_res = [3u32, 0, 0, 0, 4, 0, 1, 1 | 1 << 16, 28, 1, 0, 0x100, 0, 0]; + let mut placed_tex = [0u32; 16]; + placed_tex[..6].copy_from_slice(&[28, 4, 0x1688, 0, 0, 1]); + (placed_tex[10], placed_tex[11]) = (placed_tex_addr as u32, (placed_tex_addr >> 32) as u32); + crate::descriptor::create_placed_srv(null, &tex_res, &placed_tex, at(14)); + // 15: raw buffer UAV (standard path, sets mark & enters UnorderedIndex). + crate::descriptor::create_uav(null, buf, null, &[39, 1, 0, 0, 64, 0, 0, 0, 1, 0], at(15)); + // 16: refused empty buffer SRV (NumElements == 0 -> standard path). + crate::descriptor::create_srv(null, buf, &[62, 1, 0x1688, 0, 0, 0, 0, 0, 0, 0], at(16)); + // 17..32: empty slots. + + // Verify quick::resolve classification explicitly. + for (slot, want_quick) in [ + (0, true), + (3, true), + (4, true), + (6, true), + (7, true), + (9, false), + (10, true), + (12, true), + (13, false), + (14, false), + (15, false), + (16, false), + ] { + let view = crate::descriptor::view(at(slot)).expect("recorded view"); + assert_eq!( + resolve(&view).is_some(), + want_quick, + "unexpected quick::resolve classification for slot {slot}" + ); + } + + let (Some(mut standard), Some(mut quick)) = + (HostHeap::new(false, SLOTS), HostHeap::new(false, SLOTS)) + else { + crate::object::release_ref(tex); + crate::object::release_ref(buf); + return; + }; + standard.viewed = Arc::new(Viewed::with_options(false, false)); + quick.viewed = Arc::new(Viewed::with_options(true, true)); + // Initialize view_addresses buffers before sync so write_buffer_address is verified too. + assert!(standard.view_addresses().is_some()); + assert!(quick.view_addresses().is_some()); + + standard.sync_slots_bytes_mode(0..SLOTS, start, 32, (start, &title_heap), true, false); + quick.sync_slots_bytes_mode(0..SLOTS, start, 32, (start, &title_heap), true, true); + + for i in 0..SLOTS { + assert_eq!( + slot_state(&quick, i), + slot_state(&standard, i), + "round 0 mismatch at slot {i}" + ); + } + assert_eq!( + quick.widened_buffers().len(), + standard.widened_buffers().len(), + "widened buffer count mismatch" + ); + if crate::under_wine() { + assert_eq!(quick.widened_buffers().len(), 2, "float + uint widened copies"); + } + + let check_uav_writes = |label: &str| { + let mut want = Vec::new(); + crate::bindless::widened_writes_into(&standard.viewed, &mut want); + let mut got_scan = Vec::new(); + crate::bindless::widened_writes_into(&quick.viewed, &mut got_scan); + let got_fast = crate::bindless::unordered_writes(&quick.viewed).expect("fast cache"); + assert_eq!( + normalize_writes(&got_scan), + normalize_writes(&want), + "{label}: widened_writes_into mismatch" + ); + assert_eq!( + normalize_writes(&got_fast), + normalize_writes(&want), + "{label}: unordered_writes mismatch" + ); + }; + check_uav_writes("round 0"); + + // Round 1: clear slots 1, 10, 15; overwrite slot 3 with CBV and slot 7 with subrange SRV. + title_heap[32..64].fill(0); + title_heap[10 * 32..11 * 32].fill(0); + title_heap[15 * 32..16 * 32].fill(0); + crate::descriptor::create_cbv(null, &cbv, at(3)); + crate::descriptor::create_srv(null, buf, &[62, 1, 0x1688, 0, 32, 0, 64, 0, 0, 0], at(7)); + + standard.sync_slots_bytes_mode(0..SLOTS, start, 32, (start, &title_heap), true, false); + quick.sync_slots_bytes_mode(0..SLOTS, start, 32, (start, &title_heap), true, true); + + for i in 0..SLOTS { + assert_eq!( + slot_state(&quick, i), + slot_state(&standard, i), + "round 1 mismatch at slot {i}" + ); + } + assert!(!quick.made(1) && !quick.made(10) && !quick.made(15)); + assert_eq!(quick.widened_buffers().len(), standard.widened_buffers().len()); + check_uav_writes("round 1"); + + // SAFETY: plain device health check. + assert!(unsafe { host().unwrap().device.GetDeviceRemovedReason() }.is_ok()); + + drop((standard, quick)); + crate::object::release_ref(tex); + crate::object::release_ref(buf); + let _ = placed_tex_mem.as_ptr(); + } + + /// End-to-end GPU read test comparing a heap synced via `quick=true` + /// against `quick=false` across CBV, typed SRV, structured SRV, placed + /// raw SRV, 3-channel widened SRV (4-channel on native D3D12), and a + /// duplicate template slot. + #[test] + fn quick_sync_gpu_reads_match_standard_for_cbv_typed_structured_placed_and_widened_srvs() { + const SHADER: &str = r#" +ByteAddressBuffer cbv_raw : register(t0); +Buffer typed_u32 : register(t1); +ByteAddressBuffer struct_raw : register(t2); +ByteAddressBuffer placed_raw : register(t3); +Buffer widened_u32 : register(t4); +Buffer dup_typed : register(t5); +RWByteAddressBuffer dst : register(u0); +[numthreads(1, 1, 1)] +void main(uint3 id : SV_DispatchThreadID) { + dst.Store(0, cbv_raw.Load(8)); + dst.Store(4, typed_u32[3]); + dst.Store(8, struct_raw.Load(4)); + dst.Store(12, placed_raw.Load(0)); + uint4 w = widened_u32[1]; + dst.Store(16, w.x); + dst.Store(20, w.y); + dst.Store(24, w.z); + dst.Store(28, dup_typed[3]); +} +"#; + let Some(host) = host() else { + return; + }; + let src = crate::resource::test_buffer(4096); + let dst = crate::resource::test_buffer(256); + let (src_ptr, src_len) = crate::resource::buffer_bytes(src).expect("src bytes"); + let (dst_ptr, dst_len) = crate::resource::buffer_bytes(dst).expect("dst bytes"); + // SAFETY: 4096 bytes of test buffer memory. + unsafe { + let words = std::slice::from_raw_parts_mut(src_ptr.cast::(), 1024); + for (i, w) in words.iter_mut().enumerate() { + *w = 0xA000_0000 + i as u32; + } + } + crate::shadow::register(src as usize, src_ptr as u64, src_len); + crate::shadow::register(dst as usize, dst_ptr as u64, dst_len); + let src_shadow = crate::shadow::find(src_ptr as u64, src_len).expect("src shadow"); + src_shadow.update(src_ptr as usize, src_len as usize); + let dst_shadow = crate::shadow::find(dst_ptr as u64, dst_len).expect("dst shadow"); + + const SLOTS: u32 = 8; + let mut title_heap = vec![0u8; SLOTS as usize * 32]; + let start = title_heap.as_mut_ptr() as u64; + let at = |i: u32| start + u64::from(i) * 32; + let null = std::ptr::null(); + let mem = src_ptr as u64; + // Native D3D12 (including WARP) requires 16-byte alignment on raw SRVs + // and does not run the Wine-only 3-channel widening pass. + let native = !crate::under_wine(); + let placed_at: u64 = if native { 32 } else { 28 }; + + // Slot 0: CBV starting at +16 bytes (dword 4), size 64. Load(8) -> dword 6. + crate::descriptor::create_cbv( + null, + &[(mem + 16) as u32, ((mem + 16) >> 32) as u32, 64, 0], + at(0), + ); + // Slot 1: typed R32_UINT SRV (format 42), FirstElement=2, NumElements=16. [3] -> dword 5. + let typed_desc = [42u32, 1, 0x1688, 0, 2, 0, 16, 0, 0, 0]; + crate::descriptor::create_srv(null, src, &typed_desc, at(1)); + // Slot 2: structured SRV (stride=16, FirstElement=1 -> +16B = dword 4). Load(4) -> dword 5. + // Only raw-accessible if raw_structured() is enabled; use a raw SRV otherwise so the shader matches. + let slot2_desc = if raw_structured() { + [0u32, 1, 0x1688, 0, 1, 0, 8, 16, 0, 0] + } else { + [39u32, 1, 0x1688, 0, 4, 0, 32, 0, 1, 0] + }; + crate::descriptor::create_srv(null, src, &slot2_desc, at(2)); + // Slot 3: placed raw buffer SRV starting at +32B (native, dword 8) or +28B (Wine, dword 7). + let mut placed_raw = [0u32; 16]; + placed_raw[..10].copy_from_slice(&[39, 1, 0x1688, 0, 0, 0, 16, 0, 1, 0]); + (placed_raw[10], placed_raw[11]) = ( + (mem + placed_at) as u32, + ((mem + placed_at) >> 32) as u32, + ); + let mut placed_res = [0u32; 14]; + (placed_res[0], placed_res[4]) = (1, 256); + crate::descriptor::create_placed_srv(null, &placed_res, &placed_raw, at(3)); + // Slot 4: R32G32B32A32_UINT (format 3) on native D3D12 ([1] -> dwords 4, 5, 6), or + // 3-channel R32G32B32_UINT (format 7, widened under Wine, [1] -> dwords 3, 4, 5). + let slot4_fmt: u32 = if native { 3 } else { 7 }; + crate::descriptor::create_srv(null, src, &[slot4_fmt, 1, 0x1688, 0, 0, 0, 8, 0, 0, 0], at(4)); + // Slot 5: duplicate of Slot 1 (exercises StagingHeap copy). [3] -> dword 5. + crate::descriptor::create_srv(null, src, &typed_desc, at(5)); + // Slot 6: output raw UAV. + crate::descriptor::create_uav(null, dst, null, &[39, 1, 0, 0, 16, 0, 0, 0, 1, 0], at(6)); + + use crate::compute::{Param, srv, uav}; + let params = &[Param::Table(&[srv(0, 6), uav(0, 1)])]; + let (root, pso) = + crate::compute::pipeline(SHADER, windows::core::s!("quick_sync_eq"), 0, params) + .expect("compute pipeline"); + + let run_mode = |quick: bool| -> [u32; 8] { + let mut heap = HostHeap::new(false, SLOTS).expect("host heap"); + heap.viewed = Arc::new(Viewed::with_options(quick, quick)); + heap.sync_slots_bytes_mode(0..SLOTS, start, 32, (start, &title_heap), true, quick); + let list = host.new_list().expect("list"); + // SAFETY: open list, live heap/root/pso. + unsafe { + list.list.SetDescriptorHeaps(&[Some(heap.heap.clone())]); + list.list.SetComputeRootSignature(&root); + list.list.SetComputeRootDescriptorTable(0, heap.gpu(0)); + list.list.SetPipelineState(&pso); + list.list.Dispatch(1, 1, 1); + } + list.defer_heap(&heap.viewed); + list.close(); + host.execute(&[&list]); + let words = dst_shadow.read_host(dst_ptr as u64, 8); + words.try_into().expect("8 dwords") + }; + + let standard_out = run_mode(false); + let quick_out = run_mode(true); + assert_eq!(quick_out, standard_out, "quick vs standard GPU output"); + let expected = if native { + [ + 0xA000_0006, // cbv_raw.Load(8) + 0xA000_0005, // typed_u32[3] + 0xA000_0005, // struct_raw.Load(4) + 0xA000_0008, // placed_raw.Load(0) at +32B + 0xA000_0004, // R32G32B32A32_UINT[1].x + 0xA000_0005, // R32G32B32A32_UINT[1].y + 0xA000_0006, // R32G32B32A32_UINT[1].z + 0xA000_0005, // dup_typed[3] + ] + } else { + [ + 0xA000_0006, // cbv_raw.Load(8) + 0xA000_0005, // typed_u32[3] + 0xA000_0005, // struct_raw.Load(4) + 0xA000_0007, // placed_raw.Load(0) at +28B + 0xA000_0003, // widened[1].x + 0xA000_0004, // widened[1].y + 0xA000_0005, // widened[1].z + 0xA000_0005, // dup_typed[3] + ] + }; + assert_eq!(quick_out, expected); + // SAFETY: plain device health check. + assert!(unsafe { host.device.GetDeviceRemovedReason() }.is_ok()); + + crate::object::release_ref(src); + crate::object::release_ref(dst); + } + + /// Concurrent title rewrite occurring while `quick::resolve` runs outside + /// `HostHeap::made` must be detected on the live re-read and land the + /// newer view cleanly. + #[test] + fn quick_sync_handles_concurrent_rewrite_during_resolve() { + let Some(mut heap) = HostHeap::new(false, 64) else { + return; + }; + heap.viewed = Arc::new(Viewed::with_options(true, true)); + let make_buf = || { + let b = crate::resource::test_buffer(256); + let (ptr, len) = crate::resource::buffer_bytes(b).expect("buffer bytes"); + crate::shadow::register(b as usize, ptr as u64, len); + b + }; + let buf_a = make_buf(); + let buf_b = make_buf(); + let mut title_heap = vec![0u8; 64 * 32]; + let start = title_heap.as_mut_ptr() as u64; + let slot_addr = start + 8 * 32; + let srv_desc = [62u32, 1, 0x1688, 0, 0, 0, 256, 0, 0, 0]; + crate::descriptor::create_srv(std::ptr::null(), buf_a, &srv_desc, slot_addr); + + let mut expected_b = [0u32; 4]; + crate::descriptor::create_srv( + std::ptr::null(), + buf_b, + &srv_desc, + expected_b.as_mut_ptr() as u64, + ); + let expected_b_key = u64::from(expected_b[2]) << 32 | u64::from(expected_b[1]); + let buf_b_raw = buf_b as usize; + LOCAL_RESOLVE_HOOK.with(|h| { + *h.borrow_mut() = Some(Box::new(move || { + crate::descriptor::create_srv( + std::ptr::null(), + buf_b_raw as crate::object::This, + &srv_desc, + slot_addr, + ); + })); + }); + + heap.sync_slots_bytes_mode(0..64, start, 32, (start, &title_heap), true, true); + assert!(LOCAL_RESOLVE_HOOK.with(|h| h.borrow().is_none())); + assert_eq!(heap.synced[8].load(Ordering::Acquire), expected_b_key); + assert!(heap.kept(8)); + + drop(heap); + crate::object::release_ref(buf_a); + crate::object::release_ref(buf_b); + } +} diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index 270cde8a5..21e330da6 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -41,6 +41,9 @@ mod caption; // Plain std, so its tests run everywhere. #[cfg(any(windows, test))] mod census_fast; +// Plain std, so its tests run everywhere. +#[cfg(any(windows, test))] +mod census_maps; #[cfg(windows)] mod composite; #[cfg(windows)]