From 229b60ab2442aa1099302a35e053eadd79655911 Mon Sep 17 00:00:00 2001 From: GDemay <7033942+GDemay@users.noreply.github.com> Date: Sat, 28 Nov 2026 11:29:27 +0100 Subject: [PATCH 1/7] perf(gpu): compose quick descriptor sync with disjoint spans Adapt VIctory-macOS #538 (75efbe49) to the page-bucketed hulls from #675. Revalidate the shadow lookup epoch before using a pre-resolved buffer or its descriptor template. Co-authored-by: gdemontalivet --- crates/victory-gpu/src/bindless.rs | 391 +++++++++- crates/victory-gpu/src/census_maps.rs | 519 +++++++++++++ crates/victory-gpu/src/descriptor/host.rs | 190 ++++- .../victory-gpu/src/descriptor/host/quick.rs | 689 ++++++++++++++++++ crates/victory-gpu/src/lib.rs | 3 + crates/victory-gpu/src/shadow.rs | 26 +- 6 files changed, 1762 insertions(+), 56 deletions(-) create mode 100644 crates/victory-gpu/src/census_maps.rs create mode 100644 crates/victory-gpu/src/descriptor/host/quick.rs diff --git a/crates/victory-gpu/src/bindless.rs b/crates/victory-gpu/src/bindless.rs index f03096cb2..d78bac558 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,28 @@ enum Seen { Left(#[cfg_attr(not(feature = "diagnostics"), allow(dead_code))] (usize, u64, u64)), } +#[cfg(windows)] +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,28 +69,40 @@ 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(), + crate::ranges::disjoint_spans_enabled(), + ) } } impl Viewed { - /// Creates a bindless registry, optionally enabling the fast UAV range - /// index and snapshot cache (`VICTORY_CENSUS_FAST=1`). + #[cfg(test)] pub(crate) fn new(fast: bool) -> Self { Self::with_disjoint_spans(fast, crate::ranges::disjoint_spans_enabled()) } - /// Creates a bindless registry with explicit `VICTORY_CENSUS_FAST` (`fast`) - /// and `VICTORY_DISJOINT_SPANS` (`disjoint_spans`) settings. + /// Creates a test registry with explicit census and disjoint-span settings. + #[cfg(test)] pub(crate) fn with_disjoint_spans(fast: bool, disjoint_spans: bool) -> Self { + Self::with_options(fast, crate::census_maps::quick_maps(), disjoint_spans) + } + + /// Map selection changes how slots and ranges are indexed. Each copy's + /// ordered endpoint and page indexes still determine its refresh spans. + pub(crate) fn with_options(fast: bool, quick_maps: bool, disjoint_spans: bool) -> Self { Viewed { - inner: Mutex::new(Inner::new(fast, disjoint_spans)), + inner: Mutex::new(Inner::new(fast, quick_maps, disjoint_spans)), fast: fast.then(SnapshotCache::default), hull_generation: AtomicU64::new(0), + quick_maps, } } @@ -120,7 +155,7 @@ impl Viewed { } } -type Range = (usize, u64, u64, bool); +pub(crate) type Range = (usize, u64, u64, bool); /// A coalesced refresh span: copy, start, bytes, unordered access, the copy's /// bit in the change tracker (`crate::watch::clean_bit`). @@ -396,8 +431,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>, @@ -406,7 +441,7 @@ struct Inner { /// `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, @@ -421,18 +456,18 @@ struct Inner { impl Default for Inner { fn default() -> Self { - Self::new(false, crate::ranges::disjoint_spans_enabled()) + Self::new(false, false, crate::ranges::disjoint_spans_enabled()) } } impl Inner { - fn new(fast: bool, disjoint_spans: bool) -> Self { + fn new(fast: bool, quick_maps: bool, disjoint_spans: 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(), unordered: fast.then(UnorderedIndex::new), @@ -558,7 +593,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; @@ -721,22 +756,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))) @@ -745,7 +798,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); @@ -780,6 +833,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)] @@ -1227,11 +1292,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) @@ -1239,6 +1303,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 @@ -1384,6 +1455,7 @@ pub(crate) fn log(frames: f64) { } let copies = { let mut c: Vec = inner.ranges.keys().map(|k| k.0).collect(); + c.sort_unstable(); c.dedup(); c.len() }; @@ -1945,6 +2017,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, crate::ranges::disjoint_spans_enabled()), + Viewed::with_options(false, true, crate::ranges::disjoint_spans_enabled()), + Viewed::with_options(true, false, crate::ranges::disjoint_spans_enabled()), + Viewed::with_options(true, true, crate::ranges::disjoint_spans_enabled()), + ]; + 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, crate::ranges::disjoint_spans_enabled()); + let hash = Viewed::with_options(false, true, crate::ranges::disjoint_spans_enabled()); + // 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 @@ -2189,8 +2514,10 @@ void main(uint3 id : SV_DispatchThreadID) { }; for (label, viewed) in [ - ("standard+disjoint", Viewed::with_disjoint_spans(false, true)), - ("census_fast+disjoint", Viewed::with_disjoint_spans(true, true)), + ("standard+disjoint", Viewed::with_options(false, false, true)), + ("census_fast+disjoint", Viewed::with_options(true, false, true)), + ("quick_maps+disjoint", Viewed::with_options(false, true, true)), + ("quick_maps+census_fast+disjoint", Viewed::with_options(true, true, true)), ] { viewed.set_buffer_slot(1, Some((©, at, 4096, false))); viewed.set_buffer_slot(2, Some((©, at + 32 * 1024, 4096, false))); 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..06dc5a0b2 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,17 +1739,28 @@ 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, kept: Option, mark: Option<(u32, u32)>, + quick: bool, } + 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 +1794,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 +1819,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 +1844,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 +1856,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 +1909,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 +1961,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 +1972,27 @@ impl HostHeap { unchanged += 1; continue; } + let resolved_buf = resolved_bufs + .get(kidx) + .and_then(Option::as_ref) + .filter(|buffer| buffer.current()); + if resolved_buf.is_none() && templates[kidx].as_ref().is_some_and(|t| t.quick) { + // The mapping changed since quick preparation. Previously + // queued copies still name their staging slot. Later copies + // need a new template made from the current mapping. + templates[kidx] = None; + } 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 +2014,67 @@ 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, + quick: true, + }); + (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 +2086,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 { @@ -1958,10 +2099,12 @@ impl HostHeap { src, kept: k.clone(), mark: m, + quick: false, }); (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 +2113,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 +2131,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 +2194,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 +3052,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..7a3628161 --- /dev/null +++ b/crates/victory-gpu/src/descriptor/host/quick.rs @@ -0,0 +1,689 @@ +//! 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, + epoch: u64, +} + +impl ResolvedBuffer { + pub(super) fn current(&self) -> bool { + self.epoch == crate::shadow::lookup_epoch() + } + + /// 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 { + // A lookup can itself register a shadow. That changes the epoch too; + // the caller can then use the warmed standard path for this first view. + let epoch = crate::shadow::lookup_epoch(); + 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, + epoch, + }) +} + +#[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, crate::ranges::disjoint_spans_enabled())); + quick.viewed = Arc::new(Viewed::with_options(true, true, crate::ranges::disjoint_spans_enabled())); + // 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, crate::ranges::disjoint_spans_enabled())); + 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, crate::ranges::disjoint_spans_enabled())); + 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)] diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 56b14fedd..417b8ecaa 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -1997,6 +1997,11 @@ pub(crate) fn generation() -> u64 { /// `BUFFERS`, `ALIASED`, or `LOOSE` (while holding that table's write lock). static LOOKUP_EPOCH: AtomicU64 = AtomicU64::new(1); +/// Validate a pre-resolved view against the same topology as the lookup cache. +pub(crate) fn lookup_epoch() -> u64 { + LOOKUP_EPOCH.load(Ordering::Acquire) +} + fn lookup_changed() { LOOKUP_EPOCH.fetch_add(1, std::sync::atomic::Ordering::Release); } @@ -2029,15 +2034,16 @@ pub(crate) fn register(resource: usize, start: u64, len: u64) { pub(crate) fn unregister(resource: usize, start: u64) { let removed = { let mut map = buffers(); - map.remove(&(start, resource)) - }; - if let Some(entry) = removed { - if let Some(shadow) = entry.shadow { - crate::bindless::forget_shadow(Arc::as_ptr(&shadow) as usize); - changed(); - } else { - lookup_changed(); + let removed = map.remove(&(start, resource)); + match &removed { + Some(Entry { shadow: Some(_), .. }) => changed(), + Some(_) => lookup_changed(), + None => {} } + removed + }; + if let Some(shadow) = removed.and_then(|entry| entry.shadow) { + crate::bindless::forget_shadow(Arc::as_ptr(&shadow) as usize); } } @@ -2099,12 +2105,12 @@ pub(crate) fn unregister_aliased(start: u64) -> bool { let removed = map.remove(&start); if removed.is_some() { ALIASED_COUNT.fetch_sub(1, Ordering::Release); + changed(); } removed }; if let Some(shadow) = removed { crate::bindless::forget_shadow(Arc::as_ptr(&shadow) as usize); - changed(); true } else { false @@ -2314,7 +2320,7 @@ pub(crate) fn find(address: u64, len: u64) -> Option> { shadow.touch(); return Some(shadow); } - let epoch = LOOKUP_EPOCH.load(Ordering::Acquire); + let epoch = lookup_epoch(); let hit = LOOKUP_CACHE.with(|cell| { let mut guard = cell.borrow_mut(); guard.as_mut().and_then(|cache| cache.get(epoch, address, end)) From 121713ea35dfe38d7ff8a805e882f31ffb1c85d6 Mon Sep 17 00:00:00 2001 From: GDemay <7033942+GDemay@users.noreply.github.com> Date: Sat, 28 Nov 2026 11:30:27 +0100 Subject: [PATCH 2/7] docs(macos): explain quick descriptor sync switches --- docs/macos.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/macos.md b/docs/macos.md index a28caccee..3d08975da 100644 --- a/docs/macos.md +++ b/docs/macos.md @@ -349,6 +349,7 @@ None of these changes the default, except `VICTORY_OUTPUT`, which sets the title | `VICTORY_RAM_LOW=`, `VICTORY_RAM_FREE=` | Set when host textures are given up for the computer's free memory, each as a share of its memory from 0 to 0.5: below `VICTORY_RAM_LOW` free (0.10 by default), until `VICTORY_RAM_FREE` is (0.15, or 0.05 above a `VICTORY_RAM_LOW` set alone). On a 24 GB Mac macOS was already compressing about 800 MB a second with 14 % free, and 0.20 and 0.26 brought the wired peak from 13.9 to 12.9 GB and a frame in the playable yard from 516 to about 490 ms. More textures are given up and made again (#454). | | `VICTORY_MAC_PRESSURE=0` | Stop reading the macOS kernel's memory pressure. By default, under Wine on macOS, host textures and idle host copies of title memory are also given up while the kernel warns of memory pressure, 1 % of the Mac's memory a frame (4 % while it is short), whatever Wine counts as free: Wine's free memory stayed above 17 % on a 24 GB Mac while macOS compressed 4 to 6 GB a second and swapped. | | `VICTORY_ASYNC_SUBMIT=1`, `VICTORY_FLIGHT1=0\|1` | Opt-in. The title's `ExecuteCommandLists`, queue `Signal` and `Wait` only queue their work, and the `victory-submit` thread prepares and submits it to the host GPU, joining up to 64 ready lists into one submission; the title's fences move once the work ran, as without it. One host submission is in flight at a time and the next is prepared only once it has landed (host copies of title memory are read by the GPU in place), so what overlaps is the title's own CPU time with host work, not preparing with the GPU. PresentX and our own read-backs wait for the queued work; a `CopyPageMappingsBatchX` behind work its queue holds (or while a host submission is in flight) is queued in that queue's order instead, as on the console, and the title's thread goes on. `VICTORY_ASYNC_SUBMIT=1` turns `VICTORY_FLIGHT1` on unless it is `0`; `VICTORY_FLIGHT1=1` alone keeps the work on the title's thread but returns before the GPU is done. The frame report's "threads held by host GPU work" line then counts the title's calls queuing, and PresentX (`presents`) and our read-backs (`our syncs`) waiting for the worker; a line "host submissions in flight per frame" gives the worker's time (waiting for the last submission to land, preparing, launching) and the host GPU's idle time before each submission, with nothing to run or while it was prepared; a line "queued host work drained per frame" counts what still drains it (presents, page mappings done at once or queued, and our own host work by the line that called it). | +| `VICTORY_QUICK_SYNC=1` | Off by default. Uses hash-backed bindless maps and resolves eligible buffer SRVs and constant-buffer views once per heap page before taking the heap's descriptor lock. Use `maps` or `views` to enable either part separately. Both parts can run with `VICTORY_DISJOINT_SPANS=1` and `VICTORY_CENSUS_FAST=1`. The `views` part requires batched heap synchronization (the default). | | `VICTORY_SYNC_EARLY=1` | Off by default; with `VICTORY_ASYNC_SUBMIT=1` (or `VICTORY_FLIGHT1=1`). Before the next host submission waits for the one on the GPU to land, the descriptors the title wrote into its heaps are mirrored while that one still runs, instead of after it landed: ~24 ms a frame in the world that the submit worker no longer adds to its wait. The preparation syncs again after the landing, which then has little left to do. A frame-report line counts these syncs and their time. | | `VICTORY_PREP_AHEAD=1` | Opt-in, with `VICTORY_ASYNC_SUBMIT=1` (or `VICTORY_FLIGHT1=1`). The next host submission is prepared while the one before is still on the GPU, and launched behind it (two in flight), when the one in flight is *quiet at landing*: nothing of it goes back to title memory (no ranges shaders write, no write marks, no read-backs, no work after it or bottom-of-pipe writes) and it had no uploads. Its host copies are refreshed in place meanwhile: the title does not change memory submitted work reads until that work's fence moves, which is when it lands, so the GPU reads the same bytes. The one in flight lands first, as without the switch, for what needs it: the frame's eviction pass, a view remake, the shared barrier lists, a heap fill, title copies (done on the CPU while preparing, by the GPU on the console), and, before the new one launches, its write marks. A frame-report line counts the submissions prepared and launched behind one in flight, and why the others landed it first; the flight line's "host GPU idle … preparing" shows what is left. | | `VICTORY_VIEW_PROBE=1` | Off by default. The "heap slots made again" line also counts the views a sync creates whose descriptor (view and generation) an earlier sync already created: the most a cache of views across syncs could save. | From 0178b36fd55db80ce13fc4166499ae6fd57917ad Mon Sep 17 00:00:00 2001 From: GDemay <7033942+GDemay@users.noreply.github.com> Date: Sat, 28 Nov 2026 11:33:12 +0100 Subject: [PATCH 3/7] fix(gpu): guard quick publication and retain displaced arena slices --- crates/victory-gpu/src/bindless.rs | 40 +++-- crates/victory-gpu/src/descriptor/host.rs | 78 ++++++-- .../victory-gpu/src/descriptor/host/quick.rs | 169 ++++++++++++++++-- crates/victory-gpu/src/host.rs | 4 +- 4 files changed, 250 insertions(+), 41 deletions(-) diff --git a/crates/victory-gpu/src/bindless.rs b/crates/victory-gpu/src/bindless.rs index d78bac558..6855b0b67 100644 --- a/crates/victory-gpu/src/bindless.rs +++ b/crates/victory-gpu/src/bindless.rs @@ -52,6 +52,8 @@ impl Seen { pub(crate) enum BatchUpdate<'a> { /// Already-resolved slot entry (or `None` to clear the slot). Resolved(Option), + /// Prepared buffer view, which must still name the current shadow. + Quick(Option, u64), /// View to resolve via [`seen`] or [`left_kind`] outside the registry lock. View(&'a View, bool), } @@ -765,7 +767,7 @@ impl Viewed { None => (index, BatchUpdate::Resolved(None)), }) .collect(); - self.set_batch_resolved(&converted); + self.set_batch_resolved(&converted, &mut Vec::new()); } /// Batched slot update accepting both pre-resolved [`Seen`] entries (from @@ -774,19 +776,24 @@ impl Viewed { /// `self.inner`). Applies all slot transitions under one hold of /// `self.inner`. #[cfg(windows)] - pub(crate) fn set_batch_resolved(&self, updates: &[(u32, BatchUpdate<'_>)]) { + pub(crate) fn set_batch_resolved( + &self, + updates: &[(u32, BatchUpdate<'_>)], + retry: &mut Vec, + ) { if updates.is_empty() { return; } 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, update) in updates { - let entry = match update { - BatchUpdate::Resolved(entry) => entry.clone(), + let mut entries = Vec::with_capacity(updates.len()); + for &(index, ref update) in updates { + let (entry, quick_epoch) = match update { + BatchUpdate::Resolved(entry) => (entry.clone(), None), + BatchUpdate::Quick(entry, epoch) => (entry.clone(), Some(*epoch)), BatchUpdate::View(v, made) => { let key = (std::ptr::from_ref(*v) as usize, *made); - cache + let entry = cache .entry(key) .or_insert_with(|| { if *made { @@ -795,14 +802,21 @@ impl Viewed { Some(Seen::Left(left_kind(v))) } }) - .clone() + .clone(); + (entry, None) } }; - entries.push((*index, entry)); + entries.push((index, entry, quick_epoch)); } let mut inner = self.inner.lock().unwrap_or_else(|e| e.into_inner()); let (mut unordered_changed, mut hulls_changed) = (false, false); - for (index, entry) in entries { + for (index, entry, quick_epoch) in entries { + // Unregister changes the epoch before acquiring this lock to evict + // the old copy. Do not reinsert an entry after its eviction. + if quick_epoch.is_some_and(|epoch| epoch != crate::shadow::lookup_epoch()) { + retry.push(index); + continue; + } if let Some(next) = &entry && inner .slots @@ -2119,7 +2133,7 @@ void main(uint3 id : SV_DispatchThreadID) { (3, BatchUpdate::View(&uav0, true)), (4, BatchUpdate::View(&uav1, true)), (5, BatchUpdate::View(&uav1, false)), - ]); + ], &mut Vec::new()); } else { v.set_batch(&[ (0, Some(&srv0), true), @@ -2141,7 +2155,7 @@ void main(uint3 id : SV_DispatchThreadID) { v.set_batch_resolved(&[ (6, BatchUpdate::Resolved(inner_srv.clone())), (7, BatchUpdate::View(&inner_uav, true)), - ]); + ], &mut Vec::new()); } for (idx, v) in variants.iter().enumerate() { assert_eq!( @@ -2155,7 +2169,7 @@ void main(uint3 id : SV_DispatchThreadID) { v.set_batch_resolved(&[ (6, BatchUpdate::Resolved(None)), (7, BatchUpdate::Resolved(None)), - ]); + ], &mut Vec::new()); } for (idx, v) in variants.iter().enumerate() { assert_eq!( diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 06dc5a0b2..39265568f 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -13,6 +13,8 @@ use windows::Win32::Graphics::Direct3D12::*; use windows::Win32::Graphics::Dxgi::Common::*; mod quick; +#[cfg(test)] +mod sync_acceptance; use super::paged::Paged; use super::{ @@ -1235,8 +1237,12 @@ impl HostHeap { // one of its shaders may hold the old descriptor (or read the // slot at an index from wrong data): what it views is freed // only once that work has run. - if let Some((old, _)) = old { - crate::host::retire(old); + if let Some((old, src)) = old { + if let Some(HeldSource::Shadow(slice)) = src { + crate::host::retire_any((old, slice)); + } else { + crate::host::retire(old); + } } } } @@ -1244,7 +1250,7 @@ impl HostHeap { /// Batched [`HostHeap::keep`]: applies all slot updates under one hold of /// `self.kept` and pushes displaced host resources into `retired` for the /// caller to retire outside locks. - fn keep_batch(&self, updates: Vec<(u32, Kept)>, retired: &mut Vec) { + fn keep_batch(&self, updates: Vec<(u32, Kept)>, retired: &mut Vec) { if updates.is_empty() { return; } @@ -1270,7 +1276,18 @@ impl HostHeap { }; if same_resource { if let (Some(cur), Some((_, new_src))) = (slot.as_mut(), resource) { - cur.1 = new_src; + let same_slice = matches!( + (&cur.1, &new_src), + (Some(HeldSource::Shadow(a)), Some(HeldSource::Shadow(b))) + if std::sync::Arc::ptr_eq(a, b) + ); + if !same_slice + && let Some(HeldSource::Shadow(slice)) = std::mem::replace(&mut cur.1, new_src) + { + // Different views can share one arena buffer. The + // old slice cannot be recycled until the GPU retires it. + retired.push((cur.0.clone(), Some(slice))); + } } continue; } @@ -1292,8 +1309,12 @@ impl HostHeap { left, ); } - if let Some((old, _)) = old { - retired.push(old); + if let Some((old, src)) = old { + let slice = match src { + Some(HeldSource::Shadow(slice)) => Some(slice), + _ => None, + }; + retired.push((old, slice)); } } } @@ -1828,13 +1849,17 @@ impl HostHeap { } } + #[cfg(test)] + if use_quick { + quick::run_topology_hook(false); + } lap(S::PrepareUs, &mut clock); // Initialize the staging heap before acquiring `self.made`. let staging = self.staging(); let host = host(); let mut again: Vec = Vec::new(); - let mut retired: Vec = Vec::new(); + let mut retired = Vec::new(); { let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner()); @@ -2136,7 +2161,10 @@ impl HostHeap { { viewed_updates.push(( index, - crate::bindless::BatchUpdate::Resolved(resolved_buf.seen.clone()), + crate::bindless::BatchUpdate::Quick( + resolved_buf.seen.clone(), + resolved_buf.epoch, + ), )); } else { viewed_updates @@ -2194,7 +2222,28 @@ impl HostHeap { self.keep_batch(kept_updates, &mut retired); lap(S::KeepUs, &mut clock); if !self.sampler { - self.viewed.set_batch_resolved(&viewed_updates); + #[cfg(test)] + if use_quick { + quick::run_topology_hook(true); + } + let retry_start = again.len(); + self.viewed.set_batch_resolved(&viewed_updates, &mut again); + let mut retry = again[retry_start..].iter().copied().peekable(); + if retry.peek().is_some() { + finalize.retain(|&(index, _, _)| { + if retry.peek() == Some(&index) { + retry.next(); + // A descriptor has already been copied and kept. + // Force the fallback to replace or clear it without + // ever publishing the unvalidated record as ready. + made[index as usize] = u64::MAX; + self.set_made_nonzero(index, true); + false + } else { + true + } + }); + } } lap(S::ViewedUs, &mut clock); crate::shadow::forget_reads(&forgot_reads); @@ -3203,6 +3252,9 @@ enum HeldSource { /// What a slot made by [`make`] holds, if anything. type Kept = Option; +/// An old descriptor's resource and any arena slice it still reads. +type RetiredView = (ID3D12Resource, Option>); + /// Buffer views refused so far (diagnostics: the first are logged). #[cfg(feature = "diagnostics")] static REFUSED: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); @@ -4328,12 +4380,12 @@ mod tests { } /// Sets the work the next `prepare` on this thread runs. - fn when_preparing(work: impl FnOnce() + Send + 'static) { + pub(super) fn when_preparing(work: impl FnOnce() + Send + 'static) { WHILE_PREPARING.set(Some(Box::new(work))); } /// Whether this thread's `prepare` ran the work set (or none was set). - fn prepared() -> bool { + pub(super) fn prepared() -> bool { WHILE_PREPARING.with_borrow(Option::is_none) } @@ -4916,7 +4968,7 @@ mod tests { unsafe { std::slice::from_raw_parts_mut(start as *mut u8, len) } } - fn placed_tex_desc(width: u64, height: u32, format: u32, flags: u32) -> [u32; 14] { + pub(super) fn placed_tex_desc(width: u64, height: u32, format: u32, flags: u32) -> [u32; 14] { [ 3, 0, @@ -4944,7 +4996,7 @@ mod tests { desc } - fn placed_tex_srv_desc(va: u64, view_format: u32) -> [u32; 16] { + pub(super) fn placed_tex_srv_desc(va: u64, view_format: u32) -> [u32; 16] { let mut desc = [0u32; 16]; desc[0] = view_format; desc[1] = 4; // D3D12_SRV_DIMENSION_TEXTURE2D diff --git a/crates/victory-gpu/src/descriptor/host/quick.rs b/crates/victory-gpu/src/descriptor/host/quick.rs index 7a3628161..e6612ce36 100644 --- a/crates/victory-gpu/src/descriptor/host/quick.rs +++ b/crates/victory-gpu/src/descriptor/host/quick.rs @@ -50,7 +50,7 @@ pub(super) struct ResolvedBuffer { /// matching `write_address` / `buffer_range`). pub(super) address: u64, pub(super) seen: Option, - epoch: u64, + pub(super) epoch: u64, } impl ResolvedBuffer { @@ -74,6 +74,11 @@ fn run_resolve_hooks() { tests::run_local_resolve_hook(); } +#[cfg(test)] +pub(super) fn run_topology_hook(publishing: bool) { + tests::run_topology_hook(publishing); +} + /// 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` + @@ -146,7 +151,11 @@ pub(super) fn resolve(view: &View) -> Option { // 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)) + ( + 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)?; @@ -229,6 +238,8 @@ mod tests { thread_local! { static LOCAL_RESOLVE_HOOK: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; + static TOPOLOGY_HOOK: std::cell::RefCell)>> = + const { std::cell::RefCell::new(None) }; } pub(super) fn run_local_resolve_hook() { @@ -238,6 +249,20 @@ mod tests { } } + pub(super) fn run_topology_hook(publishing: bool) { + let hook = TOPOLOGY_HOOK.with(|h| { + let mut hook = h.borrow_mut(); + if hook.as_ref().is_some_and(|(when, _)| *when == publishing) { + hook.take() + } else { + None + } + }); + if let Some((_, hook)) = hook { + hook(); + } + } + type SlotState = ( bool, bool, @@ -406,8 +431,16 @@ mod tests { crate::object::release_ref(buf); return; }; - standard.viewed = Arc::new(Viewed::with_options(false, false, crate::ranges::disjoint_spans_enabled())); - quick.viewed = Arc::new(Viewed::with_options(true, true, crate::ranges::disjoint_spans_enabled())); + standard.viewed = Arc::new(Viewed::with_options( + false, + false, + crate::ranges::disjoint_spans_enabled(), + )); + quick.viewed = Arc::new(Viewed::with_options( + true, + true, + crate::ranges::disjoint_spans_enabled(), + )); // 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()); @@ -428,7 +461,11 @@ mod tests { "widened buffer count mismatch" ); if crate::under_wine() { - assert_eq!(quick.widened_buffers().len(), 2, "float + uint widened copies"); + assert_eq!( + quick.widened_buffers().len(), + 2, + "float + uint widened copies" + ); } let check_uav_writes = |label: &str| { @@ -468,7 +505,10 @@ mod tests { ); } assert!(!quick.made(1) && !quick.made(10) && !quick.made(15)); - assert_eq!(quick.widened_buffers().len(), standard.widened_buffers().len()); + assert_eq!( + quick.widened_buffers().len(), + standard.widened_buffers().len() + ); check_uav_writes("round 1"); // SAFETY: plain device health check. @@ -558,17 +598,20 @@ void main(uint3 id : SV_DispatchThreadID) { // 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, - ); + (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)); + 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. @@ -582,7 +625,11 @@ void main(uint3 id : SV_DispatchThreadID) { 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, crate::ranges::disjoint_spans_enabled())); + heap.viewed = Arc::new(Viewed::with_options( + quick, + quick, + crate::ranges::disjoint_spans_enabled(), + )); 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. @@ -642,7 +689,11 @@ void main(uint3 id : SV_DispatchThreadID) { let Some(mut heap) = HostHeap::new(false, 64) else { return; }; - heap.viewed = Arc::new(Viewed::with_options(true, true, crate::ranges::disjoint_spans_enabled())); + heap.viewed = Arc::new(Viewed::with_options( + true, + true, + crate::ranges::disjoint_spans_enabled(), + )); let make_buf = || { let b = crate::resource::test_buffer(256); let (ptr, len) = crate::resource::buffer_bytes(b).expect("buffer bytes"); @@ -686,4 +737,96 @@ void main(uint3 id : SV_DispatchThreadID) { crate::object::release_ref(buf_a); crate::object::release_ref(buf_b); } + + #[test] + fn quick_sync_resolves_again_when_the_shadow_mapping_changes() { + for publishing in [false, true] { + shadow_mapping_change(publishing); + } + } + + fn shadow_mapping_change(publishing: bool) { + let Some(heap) = HostHeap::new(false, 4) else { + return; + }; + let resource = crate::resource::test_buffer(4096); + let (start, len) = crate::resource::buffer_bytes(resource).expect("buffer bytes"); + let start = start as u64; + crate::shadow::register(resource as usize, start, len); + let outer = crate::shadow::find(start, len).expect("outer shadow"); + let address = start + 256; + let mut records = [0u8; 4 * 32]; + let heap_start = records.as_mut_ptr() as u64; + for i in 0..2 { + crate::descriptor::create_cbv( + std::ptr::null(), + &[address as u32, (address >> 32) as u32, 64, 0], + heap_start + 32 * i, + ); + } + + // The record and its generation stay the same, but the innermost + // registered buffer changes after the quick candidate was prepared. + let inner_key = address as usize; + TOPOLOGY_HOOK.with(|hook| { + *hook.borrow_mut() = Some(( + publishing, + Box::new(move || { + crate::shadow::register(inner_key, address, 256); + }), + )); + }); + heap.sync_slots_bytes_mode(0..4, heap_start, 32, (heap_start, &records), true, true); + assert!(TOPOLOGY_HOOK.with(|hook| hook.borrow().is_none())); + let inner = crate::shadow::find(address, 64).expect("inner shadow"); + assert!(!Arc::ptr_eq(&inner, &outer)); + let expected = Some((Arc::as_ptr(&inner) as usize, address, 64, false)); + for index in 0..2 { + assert!(heap.kept(index)); + assert_eq!(heap.viewed.range_at(index), expected); + } + + drop(heap); + crate::shadow::unregister(inner_key, address); + crate::object::release_ref(resource); + } + + #[test] + fn rewriting_a_view_keeps_its_displaced_arena_slice_for_retirement() { + let Some(heap) = HostHeap::new(false, 4) else { + return; + }; + let resource = crate::resource::test_buffer(4096); + let (start, len) = crate::resource::buffer_bytes(resource).expect("buffer bytes"); + let start = start as u64; + crate::shadow::register(resource as usize, start, len); + let (old, old_own) = crate::shadow::for_view(start + 4, 80, 16).expect("old view copy"); + let (new, new_own) = crate::shadow::for_view(start + 20, 80, 16).expect("new view copy"); + assert!(old_own && new_own); + assert_eq!( + windows::core::Interface::as_raw(&old.buffer), + windows::core::Interface::as_raw(&new.buffer) + ); + let old = (old.buffer.clone(), HeldSource::Shadow(old)); + let new = (new.buffer.clone(), HeldSource::Shadow(new)); + let mut retired = Vec::new(); + + heap.keep_batch(vec![(0, Some((old.0, Some(old.1))))], &mut retired); + let duplicate = Some((new.0.clone(), Some(new.1.clone()))); + heap.keep_batch(vec![(0, Some((new.0, Some(new.1))))], &mut retired); + assert_eq!(retired.len(), 1); + let displaced = retired[0].1.as_ref().expect("old slice retained"); + assert!( + crate::shadow::for_view(start + 4, 80, 16) + .is_some_and(|(from_cache, _)| Arc::ptr_eq(displaced, &from_cache)) + ); + heap.keep_batch(vec![(0, duplicate)], &mut retired); + assert_eq!( + retired.len(), + 1, + "unchanged slice needs no duplicate retirement" + ); + drop(heap); + crate::object::release_ref(resource); + } } diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 97be7baed..b98792865 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -7360,8 +7360,8 @@ fn advance_retired(done_submission: u64) { release_later(Box::new(ready)); } -/// Batched [`retire`] under one hold of the retired-resources lock. -pub(crate) fn retire_all(resources: Vec) { +/// Batched [`retire_any`] under one hold of the retired-resources lock. +pub(crate) fn retire_all(resources: Vec) { if resources.is_empty() { return; } From e943e325cee328546c4f2042a25b06386815e614 Mon Sep 17 00:00:00 2001 From: GDemay <7033942+GDemay@users.noreply.github.com> Date: Sat, 28 Nov 2026 11:34:31 +0100 Subject: [PATCH 4/7] test(gpu): name the topology change hook type --- crates/victory-gpu/src/descriptor/host/quick.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/descriptor/host/quick.rs b/crates/victory-gpu/src/descriptor/host/quick.rs index e6612ce36..af64267f5 100644 --- a/crates/victory-gpu/src/descriptor/host/quick.rs +++ b/crates/victory-gpu/src/descriptor/host/quick.rs @@ -235,10 +235,12 @@ mod tests { use crate::bindless::Viewed; use crate::descriptor::host::{HostHeap, host}; + type TopologyHook = (bool, Box); + thread_local! { static LOCAL_RESOLVE_HOOK: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; - static TOPOLOGY_HOOK: std::cell::RefCell)>> = + static TOPOLOGY_HOOK: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; } From 8bd89b9e0e3b3810bcca0b0c865663d346481c7a Mon Sep 17 00:00:00 2001 From: GDemay <7033942+GDemay@users.noreply.github.com> Date: Sat, 28 Nov 2026 11:40:36 +0100 Subject: [PATCH 5/7] test(gpu): verify watched descriptor submissions on D3DMetal --- crates/victory-gpu/src/compute.rs | 15 +- crates/victory-gpu/src/descriptor/host.rs | 4 + .../src/descriptor/host/sync_acceptance.rs | 523 ++++++++++++++++++ 3 files changed, 541 insertions(+), 1 deletion(-) create mode 100644 crates/victory-gpu/src/descriptor/host/sync_acceptance.rs diff --git a/crates/victory-gpu/src/compute.rs b/crates/victory-gpu/src/compute.rs index 2e3150153..faf640ab5 100644 --- a/crates/victory-gpu/src/compute.rs +++ b/crates/victory-gpu/src/compute.rs @@ -33,6 +33,17 @@ pub(crate) struct Range { kind: D3D12_DESCRIPTOR_RANGE_TYPE, register: u32, count: u32, + flags: D3D12_DESCRIPTOR_RANGE_FLAGS, +} + +#[cfg(test)] +impl Range { + /// Allows the title's heap sync and deferred copies after list recording. + pub(crate) fn volatile(mut self) -> Self { + self.flags = D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE + | D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE; + self + } } /// `count` shader resource views from `t{register}`. @@ -41,6 +52,7 @@ pub(crate) const fn srv(register: u32, count: u32) -> Range { kind: D3D12_DESCRIPTOR_RANGE_TYPE_SRV, register, count, + flags: D3D12_DESCRIPTOR_RANGE_FLAG_NONE, } } @@ -50,6 +62,7 @@ pub(crate) const fn uav(register: u32, count: u32) -> Range { kind: D3D12_DESCRIPTOR_RANGE_TYPE_UAV, register, count, + flags: D3D12_DESCRIPTOR_RANGE_FLAG_NONE, } } @@ -125,7 +138,7 @@ pub(crate) fn root_signature(device: &ID3D12Device, params: &[Param]) -> Result< NumDescriptors: r.count, BaseShaderRegister: r.register, RegisterSpace: 0, - Flags: D3D12_DESCRIPTOR_RANGE_FLAG_NONE, + Flags: r.flags, OffsetInDescriptorsFromTableStart: D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND, }) .collect(), diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 39265568f..4dddd99ac 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -2245,6 +2245,10 @@ impl HostHeap { }); } } + #[cfg(test)] + if use_quick { + sync_acceptance::note_publication(&viewed_updates, &finalize); + } lap(S::ViewedUs, &mut clock); crate::shadow::forget_reads(&forgot_reads); // Coalesce `made_nonzero` bit updates per 64-slot word (stale indices diff --git a/crates/victory-gpu/src/descriptor/host/sync_acceptance.rs b/crates/victory-gpu/src/descriptor/host/sync_acceptance.rs new file mode 100644 index 000000000..b3dad8edb --- /dev/null +++ b/crates/victory-gpu/src/descriptor/host/sync_acceptance.rs @@ -0,0 +1,523 @@ +//! The title writes descriptor records as bytes, and the host consumes them +//! for the first time while preparing a real GPU submission. + +use super::tests::{placed_tex_desc, placed_tex_srv_desc, prepared, when_preparing}; +use super::*; +use crate::compute::{self, Param, srv, uav}; +use crate::descriptor::{create_cbv, create_heap, create_placed_srv, create_srv, create_uav, heap}; +use crate::object::{S_OK, This, release_ref}; +use std::ptr::null; + +const SOURCE: &str = r#" +ByteAddressBuffer raw_view : register(t0); +ByteAddressBuffer duplicate_view : register(t1); +Buffer typed_view : register(t2); +ByteAddressBuffer structured_view : register(t3); +ByteAddressBuffer constant_view : register(t4); +Buffer widened_view : register(t5); +Texture2D texture_view : register(t6); +ByteAddressBuffer far_view : register(t7); +RWByteAddressBuffer result : register(u0); +[numthreads(1, 1, 1)] +void main() { + result.Store(0, raw_view.Load(0)); + result.Store(4, duplicate_view.Load(0)); + result.Store(8, typed_view[0]); + result.Store(12, structured_view.Load(4)); + result.Store(16, constant_view.Load(0)); + result.Store4(20, widened_view[1]); + result.Store(36, asuint(texture_view.Load(int3(0, 0, 0)).x)); + result.Store(40, far_view.Load(0)); +} +"#; + +thread_local! { + static QUICK_PUBLICATION: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +pub(super) fn note_publication( + updates: &[(u32, crate::bindless::BatchUpdate<'_>)], + finalize: &[(u32, u64, u64)], +) { + QUICK_PUBLICATION.with(|published| { + if published.get() != Some(false) { + return; + } + published.set(Some(updates.iter().any(|(index, update)| { + matches!(update, crate::bindless::BatchUpdate::Quick(..)) + && finalize + .iter() + .any(|&(slot, _, ready)| slot == *index && ready != 0) + }))); + }); +} + +const FAR: usize = 512 << 10; +const LEN: usize = FAR + 4096; +const BENCH_WARMUP: usize = 3; +const BENCH_PASSES: usize = 23; +const RAW: [u32; 10] = [39, 1, 0x1688, 0, 0, 0, 4, 0, 1, 0]; + +fn locate(resource: This, len: usize) -> u64 { + let (address, size) = crate::resource::buffer_bytes(resource).expect("title buffer bytes"); + assert_eq!(size, len as u64); + address as u64 +} + +fn srv_record(resource: This, words: &[u32; 10]) -> [u32; 4] { + let mut record = [0u32; 4]; + create_srv(null(), resource, words, record.as_mut_ptr() as u64); + record +} + +fn write_slot(at: u64, record: [u32; 4]) { + // SAFETY: the caller supplies a slot in the test's tracked heap; the + // title writes these 16 bytes without using descriptor API copy calls. + unsafe { (at as *mut [u32; 4]).write_volatile(record) }; +} + +fn write_data(address: u64, offset: usize, value: u32) { + // SAFETY: the caller supplies a dword in a live test title buffer. + unsafe { (address as *mut u32).add(offset / 4).write_volatile(value) }; +} + +#[test] +#[ignore = "requires Wine with D3DMetal, a D3D12 device, and the HLSL compiler"] +fn watched_descriptor_records_reach_gpu_readback() { + run(false); +} + +#[test] +#[ignore = "measure in release mode under Wine with D3DMetal"] +fn bench_watched_descriptor_submissions() { + run(true); +} + +fn run(benchmark: bool) { + assert!( + crate::under_wine(), + "acceptance requires Wine with D3DMetal" + ); + assert!( + raw_structured(), + "acceptance expects structured SRVs lowered to raw" + ); + assert!(sync_fast_enabled(), "acceptance requires batched heap sync"); + let gpu = host().expect("acceptance requires a D3D12 device"); + let (root, pso) = compute::pipeline( + SOURCE, + windows::core::s!("watched_descriptor_records"), + 0, + &[ + Param::Table(&[srv(0, 8).volatile()]), + Param::Table(&[uav(0, 1).volatile()]), + ], + ) + .expect("acceptance compute pipeline"); + + let source = crate::resource::test_buffer(LEN as u64); + let other = crate::resource::test_buffer(256); + let output = crate::resource::test_buffer(256); + let a = locate(source, LEN); + let b = locate(other, 256); + let result = locate(output, 256); + for (offset, value) in (0..32).step_by(4).zip(101..109) { + write_data(a, offset, value); + } + write_data(a, 64, 210); + write_data(a, FAR, 301); + write_data(b, 0, 401); + let result_copy = crate::shadow::find(result, 256).expect("output shadow"); + // Populate the shadow registry before resolving descriptors, so its + // first insertions do not invalidate the page's prepared quick views. + assert!( + crate::shadow::find(a, LEN as u64).is_some(), + "source shadow" + ); + assert!(crate::shadow::find(b, 256).is_some(), "replacement shadow"); + + const BENCH_PAGES: usize = 32; + let pages = if benchmark { BENCH_PAGES } else { 1 }; + let slots = if benchmark { + pages * crate::watch::PAGE / 32 + } else { + 16 + }; + let page = crate::watch::tests::pool(pages); + let heap_desc = [ + 0u32, + slots as u32, + 1, + 0, + page as u32, + (page as u64 >> 32) as u32, + (slots * 32) as u32, + 0, + ]; + let iid = crate::object::guid( + 0x8efb471d, + 0x616c, + 0x4f49, + [0x90, 0xf7, 0x12, 0x7b, 0xb7, 0x63, 0xfa, 0x51], + ); + let mut title = null(); + assert_eq!( + create_heap(null(), heap_desc.as_ptr().cast(), &iid, &mut title), + S_OK + ); + let title_heap = heap(title); + assert_eq!(title_heap.start, page as u64); + let at = |slot| title_heap.handle(slot).expect("test descriptor slot"); + let h = title_heap.host().expect("acceptance host descriptor heap"); + + let raw = srv_record(source, &RAW); + let raw_other = srv_record(other, &RAW); + let typed = srv_record(source, &[42, 1, 0x1688, 0, 2, 0, 1, 0, 0, 0]); + // The translator reads this 16-byte structured view through a raw + // handle. A nonzero FirstElement makes the offset observable. + let structured = srv_record(source, &[0, 1, 0x1688, 0, 1, 0, 1, 16, 0, 0]); + let mut constant = [0u32; 4]; + let ca = a + 64; + create_cbv( + null(), + &[ca as u32, (ca >> 32) as u32, 16, 0], + constant.as_mut_ptr() as u64, + ); + let widened = srv_record(source, &[7, 1, 0x1688, 0, 0, 0, 2, 0, 0, 0]); + let pixels = crate::watch::tests::pool(1); + let mut tex_desc = placed_tex_desc(4, 1, 28, 0); + tex_desc[11] = 1; // Linear title texture memory. + let tex_view = placed_tex_srv_desc(pixels as u64, 28); + let mut texture = [0u32; 4]; + create_placed_srv(null(), &tex_desc, &tex_view, texture.as_mut_ptr() as u64); + let far = srv_record(source, &[39, 1, 0x1688, 0, FAR as u32 / 4, 0, 1, 0, 1, 0]); + let mut output_view = [0u32; 4]; + create_uav( + null(), + output, + null(), + &[39, 1, 0, 0, 64, 0, 0, 0, 1, 0], + output_view.as_mut_ptr() as u64, + ); + for (slot, record) in [ + raw, + raw, + typed, + structured, + constant, + widened, + texture, + far, + output_view, + ] + .into_iter() + .enumerate() + { + write_slot(at(slot as u32), record); + assert!( + !h.made(slot as u32), + "title byte write must not mirror slot {slot}" + ); + } + + let record_dispatch = |output_slot, copy_to_title: Option| { + let list = gpu.new_list().expect("acceptance command list"); + list.defer_heap(&h.viewed); + if let Some(offset) = copy_to_title { + list.defer_gpu_write(&result_copy, result as usize + offset, 44, false); + } + // SAFETY: live host heap, pipeline and command list. Used slots are + // populated by submission preparation before the list is executed. + unsafe { + list.list.SetDescriptorHeaps(&[Some(h.heap.clone())]); + list.list.SetComputeRootSignature(&root); + list.list.SetComputeRootDescriptorTable(0, h.gpu(0)); + list.list + .SetComputeRootDescriptorTable(1, h.gpu(output_slot)); + list.list.SetPipelineState(&pso); + list.list.Dispatch(1, 1, 1); + } + list.close(); + list + }; + let dispatch = |label: &str, expected: [u32; 11]| { + result_copy.write_host(result, &[0xa5; 44]); + let list = record_dispatch(8, None); + let started = std::time::Instant::now(); + gpu.execute_with_barriers(&[&list], &[]); + let elapsed = started.elapsed(); + // SAFETY: plain device health query after the fence completes. + assert!(unsafe { gpu.device.GetDeviceRemovedReason() }.is_ok()); + let got = result_copy.read_host(result, expected.len()); + assert_eq!(got, expected, "GPU readback after {label}"); + if !benchmark { + eprintln!("dispatch=1 stage={label} checked={got:?}"); + } + elapsed + }; + + let initial = [101, 101, 103, 106, 210, 104, 105, 106, 1, 0, 301]; + if !benchmark { + QUICK_PUBLICATION.set(Some(false)); + } + dispatch("initial_and_duplicate", initial); + if !benchmark { + let used = QUICK_PUBLICATION + .replace(None) + .expect("publication tracking"); + assert_eq!( + used, + quick::on(), + "binding a quick view must publish its live descriptor" + ); + eprintln!("quick_resolved_published={used}"); + } + assert!( + h.made(6) && !h.kept(6), + "placed texture bound with the null texture fallback" + ); + assert!(h.kept(8), "UAV fallback created a real output descriptor"); + if benchmark { + let views = [0, 64].map(|start| { + (start..start + 60) + .map(|first| { + let mut words = RAW; + words[4] = first; + words[6] = 1; + srv_record(source, &words) + }) + .collect::>() + }); + let clear = [0; 4]; + let snapshot = || { + crate::descriptor::SYNC_STATS + .each_ref() + .map(|counter| counter.load(Ordering::Relaxed)) + }; + let mut elapsed = std::time::Duration::ZERO; + let mut before = snapshot(); + for pass in 0..BENCH_WARMUP + BENCH_PASSES { + if pass == BENCH_WARMUP { + before = snapshot(); + } + let toggle = (pass + 1) & 1; + // Dirty all 32 pages. The unused first slot on each later page + // stays zero, so the scanner sees the real unchanged-page work. + for i in 1..32 { + write_slot(at(i * 2048), clear); + } + for i in 0..740 { + let table = &views[toggle]; + write_slot(at(4096 + i), table[i as usize % table.len()]); + } + for i in 0..960 { + write_slot(at(6144 + i), if toggle == 0 { texture } else { clear }); + } + write_slot(at(0), if toggle == 0 { raw } else { raw_other }); + let mut expected = initial; + expected[0] = if toggle == 0 { 101 } else { 401 }; + let time = dispatch("benchmark", expected); + if pass >= BENCH_WARMUP { + elapsed += time; + } + } + use crate::descriptor::SyncStat as S; + let after = snapshot(); + let stat = |i: S| after[i as usize] - before[i as usize]; + let heap_sync_us = stat(S::TakeUs) + stat(S::ReadUs) + stat(S::CheckUs); + assert_eq!(stat(S::Syncs), BENCH_PASSES as u64); + assert_eq!(stat(S::Slots), 32 * 2048 * BENCH_PASSES as u64); + assert!(stat(S::Created) > 0 && stat(S::FromTemplate) > 0); + eprintln!( + "bench_watched_descriptor_submissions: submissions={BENCH_PASSES} slots={} total_us={} heap_sync_parts_us={heap_sync_us} made={} creations={} template_copies={} readback_words={}", + stat(S::Slots), + elapsed.as_micros(), + stat(S::Made), + stat(S::Created), + stat(S::FromTemplate), + BENCH_PASSES * initial.len(), + ); + } + + let before = h.viewed.hull_generation(); + write_slot(at(0), raw); + dispatch("unchanged_record", initial); + assert_eq!(h.viewed.hull_generation(), before); + + // A writer changes a candidate after taking the page snapshot, during + // preparation of the first slot. Only this writer accesses title heap + // bytes while the syncing thread waits in the test hook. + write_slot(at(0), raw_other); + let race_slot = at(0); + when_preparing(move || { + std::thread::spawn(move || write_slot(race_slot, raw)) + .join() + .expect("title writer"); + }); + dispatch("concurrent_rewrite", initial); + assert!(prepared(), "rewrite hook ran during the page batch"); + + write_slot(at(0), raw_other); + write_slot(at(9), raw_other); + write_data(a, 16, 555); + write_data(a, FAR, 302); + let changed = [401, 101, 103, 106, 210, 104, 555, 106, 1, 0, 302]; + dispatch("changed_record_and_widened_source", changed); + + assert!(h.kept(9), "the old resource is live in two duplicate slots"); + assert_eq!(release_ref(other), 0); + assert!( + crate::descriptor::view(at(0)).is_none(), + "removed resource's view is stale" + ); + let replacement = crate::resource::test_buffer(256); + let replacement_address = locate(replacement, 256); + write_data(replacement_address, 0, 501); + let replacement_raw = srv_record(replacement, &RAW); + assert_eq!( + raw_other[1], replacement_raw[1], + "the view index was reused" + ); + assert_ne!( + raw_other[2], replacement_raw[2], + "the reused index received a new generation" + ); + assert!( + !crate::descriptor::view_gen_current(raw_other[1], raw_other[2]), + "old record remains stale after reusing the view table", + ); + // Slot 6 is consumed as a texture (the generic null slot is a null 2D + // SRV). Slot 9 is unread by the shader and can hold a stale raw record. + write_slot(at(6), [0; 4]); + write_slot(at(9), raw_other); + write_slot(at(0), replacement_raw); + let mut replaced = changed; + replaced[0] = 501; + dispatch("cleared_texture_and_replaced_resource", replaced); + assert!( + !h.made(6) && !h.kept(6), + "cleared texture descriptor is no longer retained" + ); + assert!( + !h.made(9) && !h.kept(9), + "old generation was not republished" + ); + let mut submissions = if benchmark { + BENCH_PASSES + BENCH_WARMUP + 5 + } else { + 5 + }; + if !benchmark { + // A placed texture that a draw first reads leaves the null fallback. + // Its host upload and the following read still run through submission. + write_data(pixels as u64, 0, 255); + write_slot(at(6), texture); + assert!(h.mirror(6, at(6), true).is_some() && h.kept(6)); + replaced[9] = 1f32.to_bits(); + dispatch("texture_made_for_draw", replaced); + submissions += 1; + + // The placed buffer uses a GPU-backed alias of the title mapping. + // A subsequent CPU edit reaches the same host SRV without rewriting + // its record. Use a separate pool from the watched descriptor heap. + let alias = crate::watch::tests::pool(1); + write_data(alias as u64, 0, 601); + assert!( + crate::alias::alias_region(alias, crate::watch::PAGE, true), + "GPU memory alias" + ); + let placed_buffer = [1, 0, 0, 0, 16, 0, 1, 1 | 1 << 16, 0, 1, 0, 1, 0, 0]; + let mut alias_desc = [0; 16]; + alias_desc[..10].copy_from_slice(&RAW); + alias_desc[10] = alias as u32; + alias_desc[11] = (alias as u64 >> 32) as u32; + let mut alias_record = [0; 4]; + create_placed_srv( + null(), + &placed_buffer, + &alias_desc, + alias_record.as_mut_ptr() as u64, + ); + write_slot(at(0), alias_record); + replaced[0] = 601; + dispatch("aliased_placed_buffer", replaced); + write_data(alias as u64, 0, 602); + replaced[0] = 602; + dispatch("unchanged_alias_descriptor", replaced); + submissions += 2; + + if crate::switch::on("VICTORY_SYNC_EARLY") { + assert!( + crate::host::flight1_enabled(), + "early sync requires VICTORY_FLIGHT1=1" + ); + assert!( + !matches!( + std::env::var("VICTORY_PREP_AHEAD").as_deref(), + Ok("1" | "ranges") + ), + "early sync uses wait-before-prep" + ); + // Use separate UAV ranges, and update slots outside flight 1's + // live descriptor set while the GPU queue still waits on a gate. + let mut second_output = [0; 4]; + create_uav( + null(), + output, + null(), + &[39, 1, 16, 0, 48, 0, 0, 0, 1, 0], + second_output.as_mut_ptr() as u64, + ); + result_copy.write_host(result, &[0xa5; 128]); + let first = std::sync::Arc::new(record_dispatch(8, Some(0))); + let second = std::sync::Arc::new(record_dispatch(10, Some(64))); + let mut gate = crate::host::Gate::hold(gpu); + gpu.execute_flight1(vec![first], vec![]); + assert!( + gpu.has_in_flight(), + "first dispatch is held on the GPU queue" + ); + write_slot(at(9), raw); + write_slot(at(10), second_output); + when_preparing(move || { + assert!( + gpu.has_in_flight(), + "second heap update occurs before first landing" + ); + gate.open(); + }); + gpu.execute_flight1(vec![second], vec![]); + gpu.finish_flight_now(); + assert!(prepared()); + for offset in [0, 64] { + // SAFETY: both lists landed, and the title buffer holds both + // output ranges. Landing copied the writes back to the title. + let got = unsafe { ((result + offset) as *const [u32; 11]).read_volatile() }; + assert_eq!( + got, replaced, + "early-sync GPU output at byte offset {offset}" + ); + eprintln!("dispatch=1 stage=early_sync_output_{offset} checked={got:?}"); + } + submissions += 2; + } + + // The final completed submission leaves the alias unused from now on. + assert!(crate::alias::unalias_region(alias)); + crate::watch::tests::free(alias); + } + + // SAFETY: the device remains live after the submissions. + let adapter = unsafe { gpu.device.GetAdapterLuid() }; + eprintln!( + "backend=Wine/D3D12 adapter_luid={:08x}:{:08x} submissions={submissions} dispatches={submissions} record_generations={}->{}", + adapter.HighPart, adapter.LowPart, raw_other[2], replacement_raw[2], + ); + + release_ref(title); + for resource in [source, replacement, output] { + assert_eq!(release_ref(resource), 0); + } + crate::watch::tests::free(page); + crate::watch::tests::free(pixels); +} From 578a18dfba33c418953075be8adfa0431e6aeb8a Mon Sep 17 00:00:00 2001 From: GDemay <7033942+GDemay@users.noreply.github.com> Date: Sat, 28 Nov 2026 11:41:01 +0100 Subject: [PATCH 6/7] perf(gpu): keep standard heap sync scratch compact --- crates/victory-gpu/src/bindless.rs | 105 ++++++++++++---------- crates/victory-gpu/src/descriptor/host.rs | 105 +++++++++++++--------- 2 files changed, 122 insertions(+), 88 deletions(-) diff --git a/crates/victory-gpu/src/bindless.rs b/crates/victory-gpu/src/bindless.rs index 6855b0b67..e397817ad 100644 --- a/crates/victory-gpu/src/bindless.rs +++ b/crates/victory-gpu/src/bindless.rs @@ -51,9 +51,11 @@ impl Seen { #[cfg(windows)] pub(crate) enum BatchUpdate<'a> { /// Already-resolved slot entry (or `None` to clear the slot). - Resolved(Option), + Clear, /// Prepared buffer view, which must still name the current shadow. - Quick(Option, u64), + Quick(&'a Option, u64), + #[cfg(test)] + TestResolved(&'a Option), /// View to resolve via [`seen`] or [`left_kind`] outside the registry lock. View(&'a View, bool), } @@ -764,19 +766,17 @@ impl Viewed { .iter() .map(|&(index, view, made)| match view { Some(v) => (index, BatchUpdate::View(v, made)), - None => (index, BatchUpdate::Resolved(None)), + None => (index, BatchUpdate::Clear), }) .collect(); - self.set_batch_resolved(&converted, &mut Vec::new()); + self.set_batch_resolved::(&converted, &mut Vec::new()); } - /// 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`. + /// Batched slot update accepting pre-resolved entries and view references. + /// Resolves the latter once per unique view, then applies all transitions + /// under one hold of `self.inner`. #[cfg(windows)] - pub(crate) fn set_batch_resolved( + pub(crate) fn set_batch_resolved( &self, updates: &[(u32, BatchUpdate<'_>)], retry: &mut Vec, @@ -784,36 +784,20 @@ impl Viewed { if updates.is_empty() { return; } - let mut cache: HashMap<(usize, bool), Option, Hashing> = - HashMap::with_hasher(Hashing::new(self.quick_maps)); - let mut entries = Vec::with_capacity(updates.len()); - for &(index, ref update) in updates { - let (entry, quick_epoch) = match update { - BatchUpdate::Resolved(entry) => (entry.clone(), None), - BatchUpdate::Quick(entry, epoch) => (entry.clone(), Some(*epoch)), - BatchUpdate::View(v, made) => { - let key = (std::ptr::from_ref(*v) as usize, *made); - let entry = cache - .entry(key) - .or_insert_with(|| { - if *made { - seen(v) - } else { - Some(Seen::Left(left_kind(v))) - } - }) - .clone(); - (entry, None) - } - }; - entries.push((index, entry, quick_epoch)); - } + let entries = if self.quick_maps { + resolve_updates(updates, Hashing::Fold) + } else { + resolve_updates(updates, std::hash::RandomState::new()) + }; let mut inner = self.inner.lock().unwrap_or_else(|e| e.into_inner()); let (mut unordered_changed, mut hulls_changed) = (false, false); - for (index, entry, quick_epoch) in entries { + for (&(index, ref update), entry) in updates.iter().zip(entries) { // Unregister changes the epoch before acquiring this lock to evict // the old copy. Do not reinsert an entry after its eviction. - if quick_epoch.is_some_and(|epoch| epoch != crate::shadow::lookup_epoch()) { + if QUICK + && let BatchUpdate::Quick(_, epoch) = update + && *epoch != crate::shadow::lookup_epoch() + { retry.push(index); continue; } @@ -927,6 +911,37 @@ impl Viewed { } } +/// Resolve each unresolved view once. Quick entries borrow the page's +/// prepared data so each slot needs just one reference for the register. +fn resolve_updates( + updates: &[(u32, BatchUpdate<'_>)], + hasher: impl std::hash::BuildHasher, +) -> Vec> { + let mut cache = HashMap::with_hasher(hasher); + updates + .iter() + .map(|(_, update)| match update { + BatchUpdate::Clear => None, + BatchUpdate::Quick(entry, _) => (*entry).clone(), + #[cfg(test)] + BatchUpdate::TestResolved(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 { + seen(v) + } else { + Some(Seen::Left(left_kind(v))) + } + }) + .clone() + } + }) + .collect() +} + /// What a made view reads that title memory feeds. fn seen(view: &View) -> Option { let placed = crate::descriptor::host::placed_texture(view); @@ -2126,10 +2141,10 @@ void main(uint3 id : SV_DispatchThreadID) { // 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())), + v.set_batch_resolved::(&[ + (0, BatchUpdate::TestResolved(&resolved_srv0)), + (1, BatchUpdate::TestResolved(&resolved_srv0)), + (2, BatchUpdate::TestResolved(&resolved_srv1)), (3, BatchUpdate::View(&uav0, true)), (4, BatchUpdate::View(&uav1, true)), (5, BatchUpdate::View(&uav1, false)), @@ -2152,8 +2167,8 @@ void main(uint3 id : SV_DispatchThreadID) { 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())), + v.set_batch_resolved::(&[ + (6, BatchUpdate::TestResolved(&inner_srv)), (7, BatchUpdate::View(&inner_uav, true)), ], &mut Vec::new()); } @@ -2166,9 +2181,9 @@ void main(uint3 id : SV_DispatchThreadID) { } assert_all_equal("after interior set_batch_resolved"); for v in &variants { - v.set_batch_resolved(&[ - (6, BatchUpdate::Resolved(None)), - (7, BatchUpdate::Resolved(None)), + v.set_batch_resolved::(&[ + (6, BatchUpdate::Clear), + (7, BatchUpdate::Clear), ], &mut Vec::new()); } for (idx, v) in variants.iter().enumerate() { diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 4dddd99ac..fd1bded2f 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -1675,7 +1675,11 @@ impl HostHeap { } } if !stale.is_empty() { - self.mirror_synced_batch(&stale, at, quick_views); + if quick_views && !self.sampler { + self.mirror_synced_batch::(&stale, at); + } else { + self.mirror_synced_batch::(&stale, at); + } } } else { let legacy_fast = sync_fast_enabled(); @@ -1761,11 +1765,15 @@ impl HostHeap { /// deduplicating `prepare` and descriptor creation via [`StagingHeap`] + /// `CopyDescriptorsSimple`. /// - /// When `quick_views` is enabled on a view heap, each unique buffer-SRV or + /// When quick sync 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) { + fn mirror_synced_batch( + &self, + stale: &[(u32, [u32; 3])], + at: impl Fn(u32) -> u64, + ) { let _making = MakeTimer(std::time::Instant::now(), stale.len() as u64); struct CachedTemplate { src: D3D12_CPU_DESCRIPTOR_HANDLE, @@ -1774,38 +1782,49 @@ impl HostHeap { quick: bool, } - 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::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 { - if tag == VIEW_TAG && generation != 0 { - let key = u64::from(generation) << 32 | u64::from(view); - let idx = match key_to_idx.get(&key) { - Some(&idx) => { - key_counts[idx] += 1; - idx - } - None => { - let idx = unique_keys.len(); - unique_keys.push(key); - key_counts.push(1); - key_to_idx.insert(key, idx); - idx - } - }; - slot_key_idx.push(Some(idx)); - } else { - slot_key_idx.push(None); + type KeyIndex = (Vec, Vec, Vec>); + + fn key_index( + stale: &[(u32, [u32; 3])], + mut key_to_idx: HashMap, + ) -> KeyIndex { + let mut unique_keys: Vec = Vec::new(); + let mut key_counts: Vec = Vec::new(); + let mut slot_key_idx: Vec> = Vec::with_capacity(stale.len()); + for &(_, [tag, view, generation]) in stale { + if tag == VIEW_TAG && generation != 0 { + let key = u64::from(generation) << 32 | u64::from(view); + let idx = match key_to_idx.get(&key) { + Some(&idx) => { + key_counts[idx] += 1; + idx + } + None => { + let idx = unique_keys.len(); + unique_keys.push(key); + key_counts.push(1); + key_to_idx.insert(key, idx); + idx + } + }; + slot_key_idx.push(Some(idx)); + } else { + slot_key_idx.push(None); + } } + + (unique_keys, key_counts, slot_key_idx) } + let (unique_keys, key_counts, slot_key_idx) = if QUICK { + key_index( + stale, + HashMap::with_capacity_and_hasher(stale.len(), crate::census_maps::Hashing::Fold), + ) + } else { + key_index(stale, HashMap::new()) + }; + use crate::descriptor::{SyncStat as S, sync_stat}; let lap = |stat: S, since: &mut std::time::Instant| { let now = std::time::Instant::now(); @@ -1816,20 +1835,20 @@ impl HostHeap { 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 }); + Vec::with_capacity(if 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) { + if 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 { + if QUICK { resolved_bufs.push(None); } let later = defer_placed(view, at_once); @@ -1840,7 +1859,7 @@ impl HostHeap { is_tex.push(is_texture(view)); strides.push(view_stride(view) | view_kind(view)); } else { - if use_quick { + if QUICK { resolved_bufs.push(None); } defer.push(false); @@ -1850,7 +1869,7 @@ impl HostHeap { } #[cfg(test)] - if use_quick { + if QUICK { quick::run_topology_hook(false); } lap(S::PrepareUs, &mut clock); @@ -1987,7 +2006,7 @@ impl HostHeap { kept_updates.push((index, None)); if !self.sampler { viewed_updates - .push((index, crate::bindless::BatchUpdate::Resolved(None))); + .push((index, crate::bindless::BatchUpdate::Clear)); } finalize.push((index, 0, 0)); } @@ -2162,7 +2181,7 @@ impl HostHeap { viewed_updates.push(( index, crate::bindless::BatchUpdate::Quick( - resolved_buf.seen.clone(), + &resolved_buf.seen, resolved_buf.epoch, ), )); @@ -2223,13 +2242,13 @@ impl HostHeap { lap(S::KeepUs, &mut clock); if !self.sampler { #[cfg(test)] - if use_quick { + if QUICK { quick::run_topology_hook(true); } let retry_start = again.len(); - self.viewed.set_batch_resolved(&viewed_updates, &mut again); + self.viewed.set_batch_resolved::(&viewed_updates, &mut again); let mut retry = again[retry_start..].iter().copied().peekable(); - if retry.peek().is_some() { + if QUICK && retry.peek().is_some() { finalize.retain(|&(index, _, _)| { if retry.peek() == Some(&index) { retry.next(); @@ -2246,7 +2265,7 @@ impl HostHeap { } } #[cfg(test)] - if use_quick { + if QUICK { sync_acceptance::note_publication(&viewed_updates, &finalize); } lap(S::ViewedUs, &mut clock); From 39ef2c0807d1aebe059dc5fa1a5ad29ad84dc569 Mon Sep 17 00:00:00 2001 From: GDemay <7033942+GDemay@users.noreply.github.com> Date: Sat, 28 Nov 2026 11:44:30 +0100 Subject: [PATCH 7/7] test(gpu): wait for retired descriptor slices before checking release --- crates/victory-gpu/src/bindless.rs | 2 +- crates/victory-gpu/src/census_maps.rs | 14 ++++++++++++-- crates/victory-gpu/src/draw.rs | 12 +++++++++--- 3 files changed, 22 insertions(+), 6 deletions(-) diff --git a/crates/victory-gpu/src/bindless.rs b/crates/victory-gpu/src/bindless.rs index e397817ad..c79aa9076 100644 --- a/crates/victory-gpu/src/bindless.rs +++ b/crates/victory-gpu/src/bindless.rs @@ -50,7 +50,7 @@ impl Seen { /// 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). + /// Clear a slot's previous entry. Clear, /// Prepared buffer view, which must still name the current shadow. Quick(&'a Option, u64), diff --git a/crates/victory-gpu/src/census_maps.rs b/crates/victory-gpu/src/census_maps.rs index c3409ff83..a84d193d7 100644 --- a/crates/victory-gpu/src/census_maps.rs +++ b/crates/victory-gpu/src/census_maps.rs @@ -386,7 +386,10 @@ mod tests { } 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")); + assert_eq!( + hashing.hash_one(b"sample-key"), + state.hash_one(b"sample-key") + ); } #[test] @@ -423,7 +426,14 @@ mod tests { ); let copy_hashes: Vec = (0..1usize << 16) - .map(|i| fold.hash_one((base_copy + 0x140 * i, 0x1_0000_0000u64, 0x1_0000_0100u64, false))) + .map(|i| { + fold.hash_one(( + base_copy + 0x140 * i, + 0x1_0000_0000u64, + 0x1_0000_0100u64, + false, + )) + }) .collect(); let (low, high) = distribution(©_hashes); assert!( diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 86b3ad6b4..730540641 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -6175,7 +6175,7 @@ void main(uint3 id : SV_DispatchThreadID) { drop(copy); // A slot made from the view holds its copy: after more than a // thousand other views' copies, draws still find (and refresh) the - // copy the slot shows; rewritten, the slot lets it go. + // copy the slot shows; rewritten, the old copy retires after GPU work. let null = std::ptr::null(); let heap_desc: [u32; 8] = [0, 8, 1, 0, 0, 0, 0, 0]; let mut heap = null; @@ -6192,8 +6192,14 @@ void main(uint3 id : SV_DispatchThreadID) { let found = crate::descriptor::host::view_copy(&view(start + 100)).unwrap().0; assert!(shown.upgrade().is_some_and(|s| std::sync::Arc::ptr_eq(&s, &found)), "the slot's copy"); drop(found); - slots.make_null(0); - assert!(shown.upgrade().is_none(), "released with the slot"); + let list = host.new_list().expect("retirement submission"); + list.close(); + crate::host::with_bury_lag(0, || { + slots.make_null(0); + host.execute(&[&list]); + }); + crate::host::wait_for_releases(); + assert!(shown.upgrade().is_none(), "released after retirement"); } #[test]