From bd9b273b1e6e33cee8a5a88e1babf4538d6557eb Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 02:54:11 +0100 Subject: [PATCH 01/83] GPU: a draw dropped because a root view cannot be bound says why `bind()` returned false without a reason when a root view's address lay in no host copy, was not set by the title, sat 4 GiB or more into its copy, had no host view heap or found no dynamic slot. The drop ranking then showed such draws as dropped "()": in the intro cutscene about 310 dispatches a frame (run mk3), almost all compute programs of the BVH builder whose root view address is in no host copy. Every such return now records its reason through `not_run`. Co-Authored-By: Claude Fable 5.2 --- crates/victory-gpu/src/draw.rs | 25 ++++++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 3172caf810..90fb3fc63b 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -648,7 +648,10 @@ impl State { }; match offset { Some(offset) => offset, - None => return false, + None => { + not_run("a root view's offset: no root view, or outside title buffers"); + return false; + } } } None if is_root_view(u) => { @@ -790,10 +793,17 @@ impl State { fn root_view(&mut self, list: &HostList, compute: bool, slot: u8, uav: bool) -> Option<(u32, u32)> { let Some(&Root::View(address)) = self.roots_ref(compute).get(usize::from(slot)) else { once!(slot, "a shader reads a root view the title did not set: dropped"); + not_run("a root view the title did not set"); + return None; + }; + let Some(shadow) = crate::shadow::find(address, 1) else { + not_run("a root view outside title buffers"); + return None; + }; + let Some(offset) = u32::try_from(shadow.offset(address)).ok() else { + not_run("a root view 4 GiB or more into its copy"); return None; }; - let shadow = crate::shadow::find(address, 1)?; - let offset = u32::try_from(shadow.offset(address)).ok()?; shadow.refresh(list, address, shadow.left(address)); if uav { // Writes through the view are marked wherever they land in the @@ -802,12 +812,16 @@ impl State { shadow.gpu_writes(list, address, len, true); } let (key, host) = match self.heaps[0] { - 0 => (MEMORY_HEAP, crate::memory::heap()?), + 0 => (MEMORY_HEAP, crate::memory::heap()), h => ( std::ptr::from_ref(crate::descriptor::heap(h as This)) as usize, - crate::descriptor::heap(h as This).host()?, + crate::descriptor::heap(h as This).host(), ), }; + let Some(host) = host else { + not_run("a root view without a host view heap"); + return None; + }; let copy = std::sync::Arc::as_ptr(&shadow) as usize; if let Some(&index) = self.root_slots.get(&(key, copy, uav)) { return Some((index, offset)); @@ -816,6 +830,7 @@ impl State { if run_heap != key || next >= end { let Some(first) = host.dynamic(ROOT_VIEW_RUN) else { once!("no dynamic slots for root views: dropped"); + not_run("no dynamic slots for root views"); return None; }; self.dynamic.push((key, first, ROOT_VIEW_RUN)); From 1365fe11e5b2952f4f62fdccc28b9bbce791bbe8 Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 03:12:00 +0100 Subject: [PATCH 02/83] GPU: diagnostics for the frame's cost: heap sync time, video memory, GPU time per pipeline The fps line left a share of "preparing" and of the GPU time unexplained. Three diagnostics (diagnostics builds only): * copystat: time making the descriptors the title copies into its heaps as bytes (`sync_heaps`, start of every submission). Run perf1 (intro cutscene, DRED off): 120-180 ms a frame, 13 % of the submitting thread's time, unattributed before. * A "video memory" line: use and budget on the card and in system memory (`QueryVideoMemoryInfo`), to tell whether the memory manager pages at submissions. * With `VICTORY_GPU_TIMING`: GPU time per kind of command and pipeline over each stats window (the 25 costliest), and the lists' wall time against the sum of their commands'. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/copystat.rs | 11 +++- crates/victory-gpu/src/descriptor.rs | 5 ++ crates/victory-gpu/src/host.rs | 90 ++++++++++++++++++++++++++++ 3 files changed, 104 insertions(+), 2 deletions(-) diff --git a/crates/victory-gpu/src/copystat.rs b/crates/victory-gpu/src/copystat.rs index 74cd932b65..f9d15c04da 100644 --- a/crates/victory-gpu/src/copystat.rs +++ b/crates/victory-gpu/src/copystat.rs @@ -94,8 +94,13 @@ pub(crate) enum C { MarkedUs, MarkedKept, SavedPages, + /// Preparing submissions: descriptors the title copied into its heaps + /// as bytes, made on the host first. + SyncHeapsUs, + /// Of those: heap slots looked at (every slot of each page written). + SyncSlots, } -const COUNTERS: usize = 57; +const COUNTERS: usize = 59; static COUNT: [AtomicU64; COUNTERS] = [const { AtomicU64::new(0) }; COUNTERS]; pub(crate) fn add(c: C, n: u64) { @@ -224,7 +229,7 @@ pub(crate) fn log(frames: f64) { asking for other mappings, {:.1} ms waiting for the guard lock; preparing: {:.1} ms in \ refresh batches, steps (each with the batch it flushes): refresh {:.1} ms, copy {:.1} ms, \ work {:.1} ms, GPU writes {:.1} ms, textures {:.1} ms, heaps {:.1} ms, title memory {:.1} ms; \ - heap texture uploads {:.1} ms, state preludes {:.1} ms; copying back compared {:.1} MB in {:.1} ms; marked pages: {:.0} compared, {:.1} MB written back in {:.1} ms, {:.0} kept the title's, {:.0} saved; working set {:.0} MB, \ + heap texture uploads {:.1} ms, state preludes {:.1} ms, heap slots the title copied {:.1} ms ({:.0} slots); copying back compared {:.1} MB in {:.1} ms; marked pages: {:.0} compared, {:.1} MB written back in {:.1} ms, {:.0} kept the title's, {:.0} saved; working set {:.0} MB, \ {:.0} hard faults", c[C::Submissions as usize], c[C::Copies as usize], @@ -277,6 +282,8 @@ pub(crate) fn log(frames: f64) { ms(c[C::StepMemoryUs as usize]), ms(c[C::UploadsUs as usize]), ms(c[C::PreludeUs as usize]), + ms(c[C::SyncHeapsUs as usize]), + c[C::SyncSlots as usize], mb(c[C::CompareBytes as usize]), ms(c[C::CompareUs as usize]), c[C::MarkedPages as usize], diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 22ea4a7efb..8ba5cb7588 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -181,6 +181,11 @@ pub(crate) fn sync_heaps() { continue; } let (first, last) = ((page as u64 - start) / step, (end as u64 - start).div_ceil(step)); + #[cfg(feature = "diagnostics")] + crate::copystat::add( + crate::copystat::C::SyncSlots, + last.min(u64::from(heap.desc.count)).saturating_sub(first), + ); for index in first..last.min(u64::from(heap.desc.count)) { host.mirror(index as u32, start + index * step, false); } diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 09314c377c..8affb6cf39 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -280,6 +280,79 @@ fn warp_adapter() -> windows::core::Result { } } +/// Diagnostics, `VICTORY_GPU_TIMING`: GPU time per kind of command and +/// pipeline (ms, commands) and lists' wall time against the sum of their +/// commands' (ms), since the last frame-rate line. +#[cfg(feature = "diagnostics")] +type GpuTimes = (std::collections::HashMap, f64, f64); +#[cfg(feature = "diagnostics")] +static GPU_TIMES: Mutex> = Mutex::new(None); + +/// Adds a timed list's commands (from [`HostList::slowest`]) to [`GPU_TIMES`], +/// by the command's kind and pipeline: its note before the first ` | `, +/// without counts and addresses. +#[cfg(feature = "diagnostics")] +fn gpu_times(wall: Duration, commands: &[(f64, String)]) { + let mut times = GPU_TIMES.lock().unwrap_or_else(|e| e.into_inner()); + let (by, wall_ms, sum) = times.get_or_insert_with(Default::default); + *wall_ms += wall.as_secs_f64() * 1e3; + for (ms, note) in commands { + let head = note.split(" | ").next().unwrap_or_default(); + let key: Vec<&str> = head + .split(' ') + .filter(|w| !w.starts_with(|c: char| c.is_ascii_digit()) && !w.starts_with("0x")) + .collect(); + let e = by.entry(key.join(" ")).or_default(); + (e.0, e.1) = (e.0 + ms, e.1 + 1); + *sum += ms; + } +} + +/// Logs [`GPU_TIMES`] per frame over `frames` frames: the 25 costliest. +#[cfg(feature = "diagnostics")] +fn log_gpu_times(frames: f64) { + let Some((by, wall, sum)) = GPU_TIMES.lock().unwrap_or_else(|e| e.into_inner()).take() else { + return; + }; + tracing::info!( + "GPU timing: lists {:.1} ms/frame of wall time, their commands {:.1} ms/frame", + wall / frames, + sum / frames + ); + let mut by: Vec<_> = by.into_iter().collect(); + by.sort_by(|a, b| b.1.0.total_cmp(&a.1.0)); + for (key, (ms, n)) in by.iter().take(25) { + tracing::info!(" GPU {:.2} ms/frame in {:.1} commands/frame: {key}", ms / frames, *n as f64 / frames); + } +} + +/// Diagnostics: the host device's video memory use and budget, in MB, local +/// (on the card) and non-local (system memory the GPU reads), as the +/// system's memory manager sees them: use over budget makes it page +/// allocations at submissions. +#[cfg(feature = "diagnostics")] +fn video_memory() -> Option<[(f64, f64); 2]> { + static ADAPTER: OnceLock> = OnceLock::new(); + let adapter = ADAPTER + .get_or_init(|| { + let device = &host()?.device; + // SAFETY: plain device and DXGI queries. + unsafe { + let luid = device.GetAdapterLuid(); + let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).ok()?; + factory.EnumAdapterByLuid(luid).ok() + } + }) + .as_ref()?; + let info = |group| { + let mut info = DXGI_QUERY_VIDEO_MEMORY_INFO::default(); + // SAFETY: a valid out pointer. + unsafe { adapter.QueryVideoMemoryInfo(0, group, &mut info) }.ok()?; + Some((info.CurrentUsage as f64 / 1e6, info.Budget as f64 / 1e6)) + }; + Some([info(DXGI_MEMORY_SEGMENT_GROUP_LOCAL)?, info(DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL)?]) +} + #[cfg(test)] mod tests { #[test] @@ -809,7 +882,11 @@ impl Host { crate::copystat::add(crate::copystat::C::Submissions, 1); // Descriptors the title copied into its heaps itself, before the // heaps' views are brought up to date below. + #[cfg(feature = "diagnostics")] + let syncing = crate::watch::Timed(std::time::Instant::now(), crate::copystat::C::SyncHeapsUs); crate::descriptor::sync_heaps(); + #[cfg(feature = "diagnostics")] + drop(syncing); // Textures heap-indexing shaders may read, uploaded first by a list // of ours where their title memory changed. let heaps: Vec> = runs @@ -912,6 +989,12 @@ impl Host { #[cfg(feature = "diagnostics")] crate::resource::life::note(0, crate::resource::life::RAN, *submitted, 0); #[cfg(feature = "diagnostics")] + if groups.len() > 1 { + // SAFETY: a plain query. + let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1); + gpu_times(started.elapsed(), &runs[i].slowest(frequency, usize::MAX)); + } + #[cfg(feature = "diagnostics")] if groups.len() > 1 && started.elapsed() > std::time::Duration::from_millis(50) { // SAFETY: a plain query. let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1); @@ -2398,7 +2481,14 @@ impl Meter { ); #[cfg(feature = "diagnostics")] { + if let Some([(local, budget), (system, system_budget)]) = video_memory() { + tracing::info!( + "video memory: {local:.0} MB of a {budget:.0} MB budget on the card, \ + {system:.0} MB of {system_budget:.0} MB in system memory" + ); + } let copy_frames = std::mem::take(&mut self.copy_stats_frames) as f64; + log_gpu_times(copy_frames); crate::copystat::log(copy_frames); crate::bindless::log(copy_frames); crate::shadow::log_views(copy_frames); From 19533398f17c819574fb41aa9b3c0a888b11a8ea Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 03:12:26 +0100 Subject: [PATCH 03/83] GPU: a submission skips host copies the title has not written since they took it Every world submission asks for every host copy its heaps' views and page tables reach (~9,000 copies) to be brought up to date, and almost none changed: run perf1 (intro cutscene) made 140-240k change checks a frame, each taking two locks, a set range query and allocations, plus per-copy timing and statistics: ~18 % of the submitting thread's time (refresh batches 195-405 ms a frame in all, the copying itself ~12 %). Each tracker now keeps a flag "some page changed since taken", set where pages are marked changed and cleared where they are taken, all under the tracker's lock, read without one. A batch leaves out clean copies and `Shadow::update` returns at once for them: the same result as before (a take finds nothing), minus the work. A write racing the flag is found by the next submission, as one racing a take always was. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/host.rs | 5 +++++ crates/victory-gpu/src/shadow.rs | 9 +++++++++ crates/victory-gpu/src/watch.rs | 32 +++++++++++++++++++++++++++----- 3 files changed, 41 insertions(+), 5 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 8affb6cf39..c64e18da32 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -1992,6 +1992,11 @@ struct Batch { impl Batch { fn add(&mut self, shadow: &std::sync::Arc, address: usize, len: usize) { + // Nothing to copy: a world submission asks for every copy its heaps' + // views and page tables reach (~9,000), a few of them written. + if shadow.clean() { + return; + } let (key, end) = (std::sync::Arc::as_ptr(shadow) as usize, address + len); if self.current.get(&key).is_some_and(|&(_, a, b)| a <= address && end <= b) { return; diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 7c29f8112d..74eedc94f4 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -479,10 +479,19 @@ impl Shadow { written.map_or(0, |_| n) } + /// Whether the title wrote none of the copy's memory since the copy took + /// it (tracked memory only): [`Shadow::update`] would copy nothing. + pub(crate) fn clean(&self) -> bool { + self.tracked.as_ref().is_some_and(crate::watch::Tracked::clean) + } + /// At submission: copies what changed of `[address, address + len)` /// since it was last copied (all of it if the memory is not /// write-watched). Returns the bytes copied. pub(crate) fn update(&self, address: usize, len: usize) -> usize { + if self.clean() { + return 0; + } let (start, end) = (self.start as usize, (self.start + self.len) as usize); let (from, to) = (address.max(start), (address + len).min(end)); if from >= to { diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index df74cc0cb7..24052d9246 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -35,6 +35,7 @@ //! and allocated again while a tracker holds it is not seen. use std::collections::{BTreeMap, BTreeSet}; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; /// The unit tracked and copied: 64 KiB, the console's page. Finer units @@ -42,9 +43,10 @@ use std::sync::{Arc, Mutex}; /// they saved. pub(crate) const PAGE: usize = 64 << 10; -/// The pages a tracker has not taken since they changed, and what it saves -/// of pages it armed. -struct Changed(Mutex>, Mutex); +/// The pages a tracker has not taken since they changed, what it saves of +/// pages it armed, and whether the first holds any (set and cleared under +/// its lock, read without: [`Tracked::clean`]). +struct Changed(Mutex>, Mutex, AtomicBool); /// Pages (page numbers) whose bytes a tracker keeps when they are first /// written after it took them, and those bytes: while shaders may be @@ -214,7 +216,7 @@ pub(crate) fn track(start: usize, len: usize, views: bool) -> Option { install(); let end = start + len; let pages = start / PAGE..end.div_ceil(PAGE); - let changed = Arc::new(Changed(Mutex::new(pages.clone().collect()), Mutex::default())); + let changed = Arc::new(Changed(Mutex::new(pages.clone().collect()), Mutex::default(), AtomicBool::new(true))); let mut g = guards(); for page in pages { g.holders.entry(page).or_default().push(changed.clone()); @@ -328,6 +330,7 @@ impl Tracked { changed.remove(&page); self.changed.taken(page); } + self.changed.2.store(!changed.is_empty(), Ordering::Release); drop(changed); drop(g); let mut runs: Vec<(usize, usize)> = Vec::new(); @@ -361,6 +364,14 @@ impl Tracked { changed.remove(&page); self.changed.taken(page); } + self.changed.2.store(!changed.is_empty(), Ordering::Release); + } + + /// Whether no page changed since it was taken: then [`Tracked::take`] + /// finds nothing, and asking costs no lock. A write racing this answer + /// is found by the next asking, as one racing a take. + pub(crate) fn clean(&self) -> bool { + !self.changed.2.load(Ordering::Acquire) } /// Shaders may write the copy's bytes `[from, to)` until [`Tracked::disarm`]: @@ -482,7 +493,11 @@ fn changed_here(g: &mut Guards, first: usize, last: usize, save: bool) -> bool { } for (&page, holders) in g.holders.range(first..last) { for c in holders { - let first_write = c.0.lock().unwrap_or_else(|e| e.into_inner()).insert(page); + let first_write = { + let mut set = c.0.lock().unwrap_or_else(|e| e.into_inner()); + c.2.store(true, Ordering::Release); + set.insert(page) + }; if first_write && save { c.save(page); } @@ -684,16 +699,21 @@ pub(crate) mod tests { let p = pool(4); let a = track(p, 4 * PAGE, true).expect("pool memory is tracked"); let b = track(p + PAGE, 2 * PAGE, true).expect("tracked"); + assert!(!a.clean() && !b.clean(), "changed at first"); assert_eq!(a.take(p, p + 4 * PAGE), [(p, p + 4 * PAGE)]); + assert!(a.clean() && !b.clean()); assert_eq!(b.take(p, p + 4 * PAGE), [(p + PAGE, p + 3 * PAGE)]); assert!(a.take(p, p + 4 * PAGE).is_empty() && b.take(p, p + 4 * PAGE).is_empty()); + assert!(a.clean() && b.clean()); // SAFETY: committed pages of ours, now read-only: the handler opens // the block; the second write needs no fault. unsafe { ((p + PAGE + 8) as *mut u8).write_volatile(1); ((p + PAGE + 9) as *mut u8).write_volatile(2); } + assert!(!a.clean() && !b.clean(), "a write is seen by every tracker"); assert_eq!(a.take(p, p + 4 * PAGE), [(p + PAGE, p + 2 * PAGE)]); + assert!(a.clean()); // `a` guarded it again; `b` still has it changed. assert!(b.changed(p / PAGE + 1)); assert_eq!(b.take(p, p + 4 * PAGE), [(p + PAGE, p + 2 * PAGE)]); @@ -717,8 +737,10 @@ pub(crate) mod tests { let t = track(p + 100, 2 * PAGE, true).expect("tracked"); assert_eq!(t.take(p + 100, p + PAGE + 10), [(p + 100, p + PAGE + 10)]); assert!(!t.changed(p / PAGE) && t.changed(p / PAGE + 1)); + assert!(!t.clean(), "a page taken in part stays changed"); assert_eq!(t.take(p, p + 3 * PAGE), [(p + PAGE, p + 2 * PAGE + 100)]); assert!(t.take(p, p + 3 * PAGE).is_empty()); + assert!(t.clean()); drop(t); free(p); } From 3e10052cbe1df6aceba600da2d31cc71ffc75ec4 Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 03:12:31 +0100 Subject: [PATCH 04/83] GPU: D3D12 objects freed after a submission are released on a thread of their own Releasing a resource is a kernel call. In run perf1 (intro cutscene) ~5 % of the title's submitting thread went into releases inside the submission: resources retired while the GPU ran, host copies whose last holder was the submission's own bookkeeping, and (diagnostics) a read-back buffer made and freed at every present for the black-frame probe. Retired resources and the submission's batch, copy-back list and heap list now go to a `victory-release` thread once the submission has run (nothing in flight uses them); the probe keeps one buffer (presents are waited for one by one). Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/capture.rs | 35 ++++++++++++++--------- crates/victory-gpu/src/descriptor/host.rs | 5 ++++ crates/victory-gpu/src/host.rs | 25 ++++++++++++++-- 3 files changed, 50 insertions(+), 15 deletions(-) diff --git a/crates/victory-gpu/src/capture.rs b/crates/victory-gpu/src/capture.rs index cd56afdec0..4e5d228362 100644 --- a/crates/victory-gpu/src/capture.rs +++ b/crates/victory-gpu/src/capture.rs @@ -747,20 +747,29 @@ pub(crate) fn probe( Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }; - let mut buffer: Option = None; - // SAFETY: plain creation; an open list; locations naming live resources. - unsafe { - device - .CreateCommittedResource( - &heap, - D3D12_HEAP_FLAG_NONE, - &desc, - D3D12_RESOURCE_STATE_COPY_DEST, - None, - &mut buffer, - ) + // One buffer for every present: each is waited for before the next + // (made and released per present, it cost a kernel call per frame). + static BUFFER: std::sync::OnceLock> = std::sync::OnceLock::new(); + let buffer = BUFFER + .get_or_init(|| { + let mut buffer: Option = None; + // SAFETY: plain creation. + unsafe { + device.CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut buffer, + ) + } .ok()?; - let buffer = buffer?; + buffer + }) + .clone()?; + // SAFETY: an open list; locations naming live resources. + unsafe { for i in 0..GRID * GRID { let (x, y) = ( (2 * (i % GRID) + 1) * d.Width as u32 / (2 * GRID), diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 8b1867ad8d..aa93ec9b5f 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -1525,6 +1525,11 @@ mod tests { heap.make_null(slot); assert!(references(&buffer) >= 2, "the slot's, retired"); crate::host::release_retired(); + // Released on a thread of its own. + let since = std::time::Instant::now(); + while references(&buffer) > 1 && since.elapsed() < std::time::Duration::from_secs(5) { + std::thread::yield_now(); + } assert_eq!(references(&buffer), 1, "ours"); } let a = heap.dynamic(heap.dynamic - 100).unwrap(); diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index c64e18da32..357ef400fb 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -1092,8 +1092,10 @@ impl Host { what.write(at as *mut u8, bytes); } } - // The submission has run and the next waits for our lock. + // The submission has run and the next waits for our lock. Host + // copies the title gave up meanwhile may have their last holder here. release_retired(); + release_later(Box::new((batch, back, withheld, heaps))); self.log_messages(); // A listed frame: what this submission's lists drew, as it is now // (the dumps submit lists of their own). @@ -2801,7 +2803,26 @@ pub(crate) fn retire(resource: ID3D12Resource) { /// After a submission has run, with none running: the retired resources go. pub(crate) fn release_retired() { let retired = std::mem::take(&mut *RETIRED.lock().unwrap_or_else(|e| e.into_inner())); - drop(retired); + if !retired.is_empty() { + release_later(Box::new(retired)); + } +} + +/// Drops `what` on a thread of its own: releasing a D3D12 resource is a +/// kernel call (~5 % of a world frame on the title's submitting thread, +/// run perf1). Only for objects no GPU work in flight uses. +fn release_later(what: Box) { + type Release = std::sync::mpsc::Sender>; + static RELEASE: OnceLock = OnceLock::new(); + let release = RELEASE.get_or_init(|| { + let (tx, rx) = std::sync::mpsc::channel::>(); + // Without the thread the receiver is gone: sends fail and drop here. + let _ = std::thread::Builder::new() + .name("victory-release".into()) + .spawn(move || rx.into_iter().for_each(drop)); + tx + }); + let _ = release.send(what); } /// Diagnostics: a noted command running a shader `VICTORY_TRACE_SHADERS` From 0086ccbc3621a830762f9d41bab888a4f6993eab Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 03:26:22 +0100 Subject: [PATCH 05/83] GPU: traced shaders' indirect records are logged in every frame VICTORY_TRACE_SHADERS now also reads back the records of every indirect execution whose pipeline holds a listed shader, in every frame, not only in dumped capture frames, and the line names the frame. Traced commands are logged without the 500 cap in listed capture frames. Why: whether the tiled-lighting draws get instances could only be seen in frames with VICTORY_DUMP_TARGETS, which cost ~40 s each and at today's speeds never reached a cutscene shot with geometry. Run light2 (traced VS_TiledLighting 25ebc92075b62822): 2,760 executions over world frames 1678-1723, 10-16 of the 60 per frame with an instance in cutscene shots, 2 in sky shots. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- crates/victory-gpu/src/capture.rs | 6 ++++-- crates/victory-gpu/src/draw.rs | 15 ++++++++++----- crates/victory-gpu/src/host.rs | 31 +++++++++++++++++++++++-------- 4 files changed, 38 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index 4010879d7c..53e79748b1 100644 --- a/README.md +++ b/README.md @@ -184,7 +184,7 @@ The on/off switches below (`...=1`) are off when unset or set to `0`. | `VICTORY_D3D12_DRED=1` | on a GPU failure, the allocation hit and the commands in flight | | `VICTORY_SKIP_PIPELINES=,...` | omit draws and dispatches, including indirect ones, whose pipeline contains a listed 16-digit shader hash | | `VICTORY_GPU_TIMING=1` | with the above, each list of a submission run and timed on its own; slow lists logged with their slowest commands; a device removal names the list it happened in and lists all its commands | -| `VICTORY_TRACE_SHADERS=,...` | with `VICTORY_D3D12_DRED`, every draw and dispatch of a listed shader logged with what it binds (user data, heap slots, root views and their first dwords; the first 500) | +| `VICTORY_TRACE_SHADERS=,...` | with `VICTORY_D3D12_DRED`, every draw and dispatch of a listed shader logged with what it binds (user data, heap slots, root views and their first dwords; the first 500, and all of them in listed capture frames); the records of its indirect executions are read back and logged in every frame (records with work, the first four, the frame) | | `VICTORY_D3D12_WARP=1` | host device on the software adapter (slow; cannot reset the driver) | | `VICTORY_PIPELINE_LOG=` | a line per title pipeline created (key, shaders, state), first used, and made or loaded (library name); `translate --cache --pipelines` writes the last kind too | | `VICTORY_PREBUILD_KEYS=` | `translate --cache --pipelines` makes nothing and lists each pack record's key, shaders and state (or why it is skipped) | diff --git a/crates/victory-gpu/src/capture.rs b/crates/victory-gpu/src/capture.rs index 4e5d228362..c0f2b7f9df 100644 --- a/crates/victory-gpu/src/capture.rs +++ b/crates/victory-gpu/src/capture.rs @@ -434,6 +434,7 @@ pub(crate) fn read_indirect( count: Option<(&ID3D12Resource, u64)>, (kind, stride, max): (u32, u32, u32), name: String, + always: bool, ) { struct Readback(ID3D12Resource); // SAFETY: D3D12 objects are free-threaded. @@ -488,7 +489,8 @@ pub(crate) fn read_indirect( let counted = count.is_some(); list.defer_after(move || { // Recorded ahead: logged if the frame running it is listed. - if !listed(crate::queue::presented() + 1) { + let frame = crate::queue::presented() + 1; + if !always && !listed(frame) { return; } let mut data = std::ptr::null_mut(); @@ -513,7 +515,7 @@ pub(crate) fn read_indirect( let shown: Vec<&[u32]> = (0..records.min(4)).map(first).collect(); tracing::info!( target: "victory_gpu::trace", - "indirect kind {kind} max {max} count {n:?}: {busy} of {records} records with work, {total} in all; first {shown:?} {name}" + "indirect kind {kind} max {max} count {n:?}: {busy} of {records} records with work, {total} in all; first {shown:?} {name} frame {frame}" ); buffer.0.Unmap(0, None); }); diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 90fb3fc63b..4cf4fbe299 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -1658,12 +1658,17 @@ impl State { counter.as_ref().map_or(0, |(s, at)| s.offset(*at)), ) }; - // A listed frame: what the records held (after the clamp). + // A listed frame, or any frame for a traced shader: what the records + // held (after the clamp). #[cfg(feature = "diagnostics")] - if crate::capture::dump_on() { - let count = counter.as_ref().map(|(s, at)| (&s.buffer, s.offset(*at))); - let name = crate::pipeline::shaders_of(pipeline); - crate::capture::read_indirect(list, (&args.buffer, args.offset(arguments)), count, (kind, stride, max), name); + { + let always = !crate::host::traced_shaders().is_empty() + && crate::host::is_traced(&crate::pipeline::shaders_of(pipeline)); + if always || crate::capture::dump_on() { + let count = counter.as_ref().map(|(s, at)| (&s.buffer, s.offset(*at))); + let name = crate::pipeline::shaders_of(pipeline); + crate::capture::read_indirect(list, (&args.buffer, args.offset(arguments)), count, (kind, stride, max), name, always); + } } crate::indirect::done(list, &args.buffer); if kind == DISPATCH { diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 357ef400fb..bffec23c9e 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -2826,21 +2826,36 @@ fn release_later(what: Box) { } /// Diagnostics: a noted command running a shader `VICTORY_TRACE_SHADERS` -/// names (hashes, comma-separated) is logged with what it binds, the first -/// 500. +/// names (hashes, comma-separated) is logged with what it binds: all of +/// them in listed capture frames, the first 500 elsewhere. #[cfg(feature = "diagnostics")] fn traced(what: &str) { - static HASHES: OnceLock> = OnceLock::new(); static LOGGED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); - let hashes = HASHES.get_or_init(|| { - let v = std::env::var("VICTORY_TRACE_SHADERS").unwrap_or_default(); - v.split(',').map(str::trim).filter(|h| !h.is_empty()).map(str::to_owned).collect() - }); - if hashes.iter().any(|h| what.contains(h.as_str())) && LOGGED.fetch_add(1, Ordering::Relaxed) < 500 { + if is_traced(what) + && (crate::capture::listed(crate::queue::presented() + 1) + || LOGGED.fetch_add(1, Ordering::Relaxed) < 500) + { tracing::info!("traced command: {what}"); } } +/// The shader hashes `VICTORY_TRACE_SHADERS` lists (comma-separated; +/// diagnostics). +#[cfg(feature = "diagnostics")] +pub(crate) fn traced_shaders() -> &'static [String] { + static HASHES: OnceLock> = OnceLock::new(); + HASHES.get_or_init(|| { + let v = std::env::var("VICTORY_TRACE_SHADERS").unwrap_or_default(); + v.split(',').map(str::trim).filter(|h| !h.is_empty()).map(str::to_owned).collect() + }) +} + +/// Whether `what` names a shader [`traced_shaders`] lists. +#[cfg(feature = "diagnostics")] +pub(crate) fn is_traced(what: &str) -> bool { + traced_shaders().iter().any(|h| what.contains(h.as_str())) +} + /// Diagnostics, `VICTORY_GPU_TIMING`: every command of the list during /// whose run (each list alone) the device was found removed. fn removed_during(runs: &[&HostList], list: Option) -> String { From eddde73437a721aa7523adf05fece68099f17b28 Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 03:27:34 +0100 Subject: [PATCH 06/83] HLE: DirectStorage reads into physical pages wait for the title's Submit A request into the engine's physical pool carries as its page list a pointer into the engine's own page-number table (sub_144ffd8c0), and Grand Theft Auto VI fills that table for a batch's pages only in its submit path, right before Submit (sub_1400e88f0 runs the batch's page mappings, sub_140f2c470 -> sub_1455aa6a0, then EnqueueStatus and Submit). A queue that submitted itself at half capacity started such reads early: they found page 0 and failed after the 8 ms retry (93-498 requests a run, every one with an all-zero page list in shards2), or found the page's previous number and wrote the data into a page that now belongs to something else, silently. A half-full queue still submits itself, but its reads into physical pages, and the status entries behind them, now wait for the title's Submit; a full queue submits everything, so a title that never submits cannot deadlock. The page list is still read when the data is written. The failure warning names the list, options, file and offset, and an info line counts self-submits (capacity, reads held). Measured: shards2 (before) 33 failed page writes, all with an all-zero page list, and 5 written late; shards3 (after, same build otherwise) 0 and 0, to the 200 s time-out. Self-submits in shards3: 2 by the world's start, the second holding 2,079 reads into physical pages (capacity 4,159): the title's streaming batch is larger than half its queue. Co-Authored-By: Claude Opus 5.5 --- crates/victory-hle/src/modules/dstorage.rs | 173 ++++++++++++++++++++- crates/victory-hle/src/modules/xmem.rs | 7 + 2 files changed, 174 insertions(+), 6 deletions(-) diff --git a/crates/victory-hle/src/modules/dstorage.rs b/crates/victory-hle/src/modules/dstorage.rs index 83a7a81ae2..9cef4f09a1 100644 --- a/crates/victory-hle/src/modules/dstorage.rs +++ b/crates/victory-hle/src/modules/dstorage.rs @@ -144,7 +144,7 @@ extern "system" fn open_file(_: Factory, path: *const u16, iid: *const Guid, out tracing::info!(path = name, iid = iid_text(iid), "dstorage: file opened"); // SAFETY: a handle we just opened and nobody else owns. let file = unsafe { std::fs::File::from_raw_handle(handle) }; - let file = Instance::create(Object::new("dstorage file", &FILE_VTABLE), File { file }); + let file = Instance::create(Object::new("dstorage file", &FILE_VTABLE), File { file, path: name }); put(out, file) } @@ -258,6 +258,8 @@ static FACTORY_VTABLE: Methods<16> = Methods([ struct File { file: std::fs::File, + /// As the title named it (diagnostics). + path: String, } static FILE_VTABLE: Methods<8> = Methods([ @@ -368,6 +370,9 @@ struct Lane { clock: u64, /// Enqueued, not yet submitted. unsubmitted: Vec, + /// Left out when the queue submitted itself, until the title's Submit: + /// reads into physical pages and the status entries behind them. + held: Vec, /// Submitted, by sequence number: reads not started, status entries /// not written, reads running, and failures not yet reported. reads: VecDeque<(u64, Request)>, @@ -547,8 +552,20 @@ impl Lanes { } } - /// Moves a queue's enqueued commands to the workers. + /// Moves a queue's enqueued commands to the workers (the title's + /// Submit). fn submit(&mut self, id: u64) { + self.submit_as(id, true); + } + + /// As [`Lanes::submit`]; `explicit` false when a half-full queue submits + /// itself, which leaves reads into physical pages for the title's + /// Submit: their page lists point into the title's page table, which + /// Grand Theft Auto VI fills for the batch in its own submit path, right + /// before Submit (`sub_1400e88f0`), so until then they name no page or a + /// page that now holds something else. A status entry behind a held + /// read waits with it. + fn submit_as(&mut self, id: u64, explicit: bool) { let Some(class) = self.lanes.get(&id).map(|l| l.class) else { return; }; @@ -567,7 +584,18 @@ impl Lanes { if lane.reads.is_empty() { lane.clock = lane.clock.max(self.lane_now[class]); } - for command in std::mem::take(&mut lane.unsubmitted) { + let mut commands = if explicit { std::mem::take(&mut lane.held) } else { Vec::new() }; + commands.append(&mut lane.unsubmitted); + for command in commands { + let hold = !explicit + && match &command { + Command::Read(r) => r.options & PAGE_DESTINATION != 0, + Command::Status(_) => !lane.held.is_empty(), + }; + if hold { + lane.held.push(command); + continue; + } let seq = self.next_seq; self.next_seq += 1; match command { @@ -586,6 +614,7 @@ impl Lane { capacity: usize::from(capacity), clock: 0, unsubmitted: Vec::new(), + held: Vec::new(), reads: VecDeque::new(), statuses: VecDeque::new(), running: BTreeSet::new(), @@ -596,7 +625,11 @@ impl Lane { /// Requests and status entries held, submitted or not. fn entries(&self) -> usize { - self.unsubmitted.len() + self.reads.len() + self.statuses.len() + self.running.len() + self.unsubmitted.len() + + self.held.len() + + self.reads.len() + + self.statuses.len() + + self.running.len() } /// Writes the status entries whose earlier reads have all finished. @@ -644,6 +677,7 @@ fn close_lane(id: u64) { }; lane.closed = true; lane.unsubmitted.clear(); + lane.held.clear(); lane.reads.clear(); lane.statuses.clear(); // releases their arrays while lanes.lanes.get(&id).is_some_and(|l| !l.running.is_empty()) { @@ -755,6 +789,16 @@ fn queue(this: QueueRef, command: Command) { if lane.entries() + 1 < lane.capacity.max(2) { break; } + // Full with reads held for a Submit the title cannot make while it + // waits here: they go now, page lists as they are. + if !lane.held.is_empty() { + static WARNED: AtomicBool = AtomicBool::new(false); + if !WARNED.swap(true, Ordering::Relaxed) { + tracing::warn!("dstorage: a full queue's reads into physical pages start before the title's Submit"); + } + lanes.submit(id); + scheduler.work.notify_all(); + } lanes = scheduler .finished .wait(lanes) @@ -765,8 +809,19 @@ fn queue(this: QueueRef, command: Command) { }; lane.unsubmitted.push(command); if lane.unsubmitted.len() >= (lane.capacity / 2).max(1) { - lanes.submit(id); + let capacity = lane.capacity; + lanes.submit_as(id, false); scheduler.work.notify_all(); + let held = lanes.lanes.get(&id).map_or(0, |l| l.held.len()); + let n = AUTO_SUBMITS.fetch_add(1, Ordering::Relaxed) + 1; + if n.is_power_of_two() { + tracing::info!( + n, + capacity, + held, + "dstorage: a queue half full submitted itself; reads into physical pages wait for the title's Submit" + ); + } } } @@ -777,7 +832,7 @@ extern "system" fn submit(this: QueueRef) { return; }; let mut lanes = scheduler.lock(); - let pending = lanes.lanes.get(&id).map_or(0, |l| l.unsubmitted.len()); + let pending = lanes.lanes.get(&id).map_or(0, |l| l.unsubmitted.len() + l.held.len()); tracing::debug!(commands = pending, "dstorage: submit"); lanes.submit(id); scheduler.work.notify_all(); @@ -1012,11 +1067,28 @@ fn into_destination( offset, len, pages = pages.len(), + unknown = super::xmem::unknown_pages(pages), + list = format_args!("{:x?}", &pages[..pages.len().min(8)]), + options = format_args!("{:#x}", request.options), + file = source_name(request), + file_offset = request.offset, "dstorage: a destination's physical pages could not be written; its request fails" ); Err(E_INVALIDARG) } +/// The file a request reads, as the title named it, or "memory". +fn source_name(request: &Request) -> &str { + if request.options & MEMORY_SOURCE != 0 { + return "memory"; + } + // SAFETY: a file object we created; the title keeps it open. + &unsafe { &*request.source.cast::>() }.state.path +} + +/// Queues that submitted themselves, half full (diagnostics). +static AUTO_SUBMITS: AtomicU32 = AtomicU32::new(0); + /// Milliseconds a page list naming page 0 is read again for. const LATE_LIST_TRIES: u32 = 8; /// Page lists filled after their request started (written late). @@ -1573,6 +1645,95 @@ mod tests { let seen = unsafe { std::slice::from_raw_parts(mapped.cast::(), plain.len()) }; assert_eq!(seen, plain); } + #[test] + fn a_queue_that_submits_itself_holds_reads_into_pages() { + let mut l = lanes(STAGING); + l.lanes.insert(0, Lane::new(0, 64)); + let array = status_array(1).cast::>(); + read(&mut l, 0, PAGE_DESTINATION, 16); + read(&mut l, 0, 0, 16); + add_ref_instance(array); + l.lanes.get_mut(&0).unwrap().unsubmitted.push(Command::Status(Status { array, index: 0 })); + l.submit_as(0, false); + // Only the plain read starts; the status waits behind the held one. + let plain = l.start().unwrap(); + assert_eq!(plain.request.options, 0); + assert!(l.start().is_none()); + l.finish(&plain, Ok(())); + assert_eq!(l.lanes[&0].held.len(), 2); + l.submit(0); + let paged = l.start().unwrap(); + assert_eq!(paged.request.options, PAGE_DESTINATION); + assert!(l.lanes[&0].held.is_empty()); + assert!(!l.lanes[&0].statuses.is_empty()); + l.finish(&paged, Ok(())); + assert!(l.lanes[&0].statuses.is_empty()); + } + + #[test] + fn a_page_list_the_title_changes_before_its_submit() { + use crate::modules::xmem; + let (mut given, mut pages) = (2usize, [0usize; 2]); + assert_eq!( + xmem::XMemAllocatePhysicalPages(0, &mut given, pages.as_mut_ptr()), + 1 + ); + let mapped = xmem::XMemVirtualAlloc( + std::ptr::null_mut(), + 2 * PAGE, + 0x2000 | 0x2040_0000, // reserve, 64 KiB pages + 0, + 0x04, + ); + assert!(!mapped.is_null()); + assert_eq!(xmem::XMemMapPhysicalPages(mapped, 2, pages.as_ptr()), mapped); + // The title's page table: still the page's previous owner when the + // request is enqueued, the right page by its Submit. + let mut list = [pages[0]]; + let plain = pattern(4096); + let create: extern "system" fn(*mut c_void, *const QueueDesc, *const Guid, Out) -> HRESULT = + call(factory(), 0x50); + let desc = QueueDesc { + source_type: 0, + capacity: 4, + priority: 1, + name: c"pages".as_ptr(), + unknown: 1, + }; + let mut queue = std::ptr::null_mut(); + assert_eq!(create(factory(), &desc, std::ptr::null(), &mut queue), S_OK); + let array = status_array(1); + let r = request( + PAGE_DESTINATION | MEMORY_SOURCE, + list.as_mut_ptr().cast(), + plain.len(), + plain.as_ptr().cast(), + 0, + plain.len(), + ); + enqueue(queue, &r); + let mut out = [0u8; 16]; + enqueue(queue, &request(MEMORY_SOURCE, out.as_mut_ptr().cast(), 16, plain.as_ptr().cast(), 0, 16)); + // Half of four: the queue submitted itself. Time for a read started + // then to land in the old page. + std::thread::sleep(std::time::Duration::from_millis(50)); + // SAFETY: the list outlives the request, which reads it when it runs. + unsafe { std::ptr::write_volatile(list.as_mut_ptr(), pages[1]) }; + enqueue_status(queue, array, 0); + void(queue, 0x30); + assert_eq!(wait(array, 0), S_OK); + assert_eq!(out, plain[..16]); + // SAFETY: both pages are mapped read-write. + let (first, second) = unsafe { + ( + std::slice::from_raw_parts(mapped.cast::(), plain.len()), + std::slice::from_raw_parts(mapped.cast::().add(PAGE), plain.len()), + ) + }; + assert_eq!(second, plain); + assert!(first.iter().all(|&b| b == 0), "the old page was written"); + } + #[test] fn zlib_into_pages_in_place_and_across_allocations() { use crate::modules::xmem; diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index 83c96132cf..495da2858f 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -523,6 +523,13 @@ pub extern "system" fn XMemAllocatePhysicalPages( /// them with `<< 4` (128 GiB of pages at most). const FRAMES: usize = PAGE >> 12; +/// How many of `pages` are no allocated page (diagnostics: a DirectStorage +/// destination that could not be written). +pub(crate) fn unknown_pages(pages: &[usize]) -> usize { + let physical = physical(); + pages.iter().filter(|p| !physical.pages.contains_key(p)).count() +} + /// Pages still mapped stay readable through their views until unmapped. pub extern "system" fn XMemFreePhysicalPages(n: usize, pages: *const usize) -> BOOL { if pages.is_null() { From f1c55a8281bd81706828f4a79ba9aab7d11bb155 Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 03:13:00 +0100 Subject: [PATCH 07/83] GPU: a placed texture's slot left null is not made again at every heap sync `HostHeap::mirror` left a placed texture's view null until a draw reads it through a table, and recorded its slot as never made, so every heap sync (one per submission, over every page the title wrote) processed the slot again: a null view written and the heap census updated each time. `perf`'s profile of run perf1 put `sync_heaps` at 120-180 ms a frame (13 % of the frame thread), most of it these slots (9,000-16,000 placed-texture slots left null in the cutscene, run textures1). The slot's record is now noted like any other; a draw's mirror still makes it (its slot holds no host view yet). Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor/host.rs | 50 ++++++++++++++++++++++- 1 file changed, 48 insertions(+), 2 deletions(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index aa93ec9b5f..f1d7f6c56b 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -662,7 +662,15 @@ impl HostHeap { } return None; }; - if made[index as usize] != key { + // A placed texture's view left null below is made when a draw reads + // the slot through a table; until then the slot is not made again + // (heap syncs revisit it at every submission). + let lazy = || { + for_draw + && is_placed_texture(&view) + && self.kept.lock().unwrap_or_else(|e| e.into_inner())[index as usize].is_none() + }; + if made[index as usize] != key || lazy() { self.set_stride(index, Some(&view)); self.note_address(index, Some(&view)); // Shaders index the heap itself (`crate::bindless`): buffer views @@ -672,7 +680,7 @@ impl HostHeap { // staging copy) for each of the ~20,000 the title has views of // ran the host out of memory (run b2). let later = !for_draw && is_placed_texture(&view); - made[index as usize] = if later { 0 } else { key }; + made[index as usize] = key; let (kept, mark) = if later { (None, None) } else { @@ -716,6 +724,12 @@ impl HostHeap { pub(crate) fn made(&self, index: u32) -> bool { self.made.lock().unwrap_or_else(|e| e.into_inner())[index as usize] != 0 } + + /// Whether slot `index` holds a host view of a resource (tests). + #[cfg(test)] + pub(crate) fn kept(&self, index: u32) -> bool { + self.kept.lock().unwrap_or_else(|e| e.into_inner())[index as usize].is_some() + } } /// Logs `what` the first time it happens. @@ -1428,6 +1442,38 @@ fn null_view(at: D3D12_CPU_DESCRIPTOR_HANDLE) { mod tests { use super::*; + /// A placed texture's view the title writes into a heap is left null + /// and noted once: heap syncs (every submission) pass it by, a draw + /// reading it through a table makes it. + #[test] + fn a_placed_texture_slot_left_null_is_made_once_a_draw_reads_it() { + if host().is_none() { + return; // no host GPU here + } + let null = std::ptr::null(); + let heap_desc: [u32; 8] = [0, 4, 1, 0, 0, 0, 0, 0]; + let mut heap = null; + let iid = crate::object::guid(0x8efb471d, 0x616c, 0x4f49, [0x90, 0xf7, 0x12, 0x7b, 0xb7, 0x63, 0xfa, 0x51]); + assert_eq!(crate::descriptor::create_heap(null, heap_desc.as_ptr().cast(), &iid, &mut heap), 0); + let title_heap = crate::descriptor::heap(heap); + // A 4x1 RGBA8 texture, linear, in memory of its own, and a 2D view. + let memory = vec![0u8; 1 << 16]; + let address = memory.as_ptr() as u64; + let words: [u32; 14] = [3, 0, 0, 0, 4, 0, 1, 1 | 1 << 16, 28, 1, 0, 0x100, 0, 0]; + let mut view = [0u32; 16]; + view[..6].copy_from_slice(&[28, 4, 0x1688, 0, 0, 1]); + (view[10], view[11]) = (address as u32, (address >> 32) as u32); + crate::descriptor::create_placed_srv(null, &words, &view, title_heap.start); + let host = title_heap.host().expect("a host view heap"); + for _ in 0..2 { + assert!(host.mirror(0, title_heap.start, false).is_some()); + assert!(host.made(0), "the record is noted"); + assert!(!host.kept(0), "no host texture for it yet"); + } + assert!(host.mirror(0, title_heap.start, true).is_some()); + assert!(host.kept(0), "made for the draw"); + } + /// The world's 16-byte view of 0 elements removed the device. #[test] fn empty_and_overlong_buffer_views_are_refused() { From 67e330a68672316e7d8c6cae2cd2dcf6a8540f5b Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 03:14:21 +0100 Subject: [PATCH 08/83] GPU: process memory and a host texture census in the statistics Diagnostics builds, every 5 s: the video-memory line also gives the process's private commit and working set, texture staging bytes (upload buffers and title memory read for them) and the console bytes of placed textures made; a second line gives host texture bytes by writer (the GPU: render target, depth or unordered access; or title memory) and by reach (used by a list, only viewed by a heap slot, neither). The heap census also names the placed textures left null: distinct addresses and bytes. Run textures1 (cutscene, with a since-dropped eager step for small placed textures): card 12.3-12.4 GB used of a 10.78 GB budget, system 6.8-7.1 of 16.3 GB; GPU-written 2.29 GB used by lists, 2.10 GB only viewed, 0 neither; from title memory 1.63 GB used, 0.43 viewed, 4.8 GB neither; placed textures left null 12-16k slots at ~12.5k addresses, 8.4-8.9 GB. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/bindless.rs | 33 ++++++++++++++++------ crates/victory-gpu/src/descriptor/host.rs | 2 ++ crates/victory-gpu/src/host.rs | 28 ++++++++++++++++++- crates/victory-gpu/src/resource.rs | 34 +++++++++++++++++++++++ crates/victory-gpu/src/texture.rs | 14 ++++++++++ 5 files changed, 101 insertions(+), 10 deletions(-) diff --git a/crates/victory-gpu/src/bindless.rs b/crates/victory-gpu/src/bindless.rs index e4c08be57a..f50fcda243 100644 --- a/crates/victory-gpu/src/bindless.rs +++ b/crates/victory-gpu/src/bindless.rs @@ -26,8 +26,9 @@ enum Seen { /// A title texture (resource object) whose contents the title writes. Texture(usize), /// A view left without a host view (textures the title placed itself), - /// by kind (diagnostics: `KINDS`). - Left(#[cfg_attr(not(feature = "diagnostics"), allow(dead_code))] usize), + /// by kind (diagnostics: `KINDS`), with a placed texture's address and + /// console bytes. + Left(#[cfg_attr(not(feature = "diagnostics"), allow(dead_code))] (usize, u64, u64)), } /// Kinds of views left without a host view, for the census. @@ -173,12 +174,15 @@ fn seen(view: &View) -> Option { Some(Seen::Buffer(shadow, address, len, uav)) } -fn left_kind(view: &View) -> usize { +fn left_kind(view: &View) -> (usize, u64, u64) { match view { - View::Placed(_, resource, _) if resource[0] != 1 => 2, - View::Unordered(..) | View::Placed(true, ..) => 1, - View::Shader(..) | View::Placed(false, ..) | View::Constant(..) => 0, - _ => 3, + View::Placed(_, resource, desc) if resource[0] != 1 => { + let address = u64::from(desc[10]) | u64::from(desc[11]) << 32; + (2, address, crate::resource::placed_size(resource).unwrap_or(0)) + } + View::Unordered(..) | View::Placed(true, ..) => (1, 0, 0), + View::Shader(..) | View::Placed(false, ..) | View::Constant(..) => (0, 0, 0), + _ => (3, 0, 0), } } @@ -305,13 +309,22 @@ pub(crate) fn log(frames: f64) { let inner = viewed.inner.lock().unwrap_or_else(|e| e.into_inner()); let mut left = [0u32; KINDS.len()]; let (mut buffers, mut textures) = (0u32, 0u32); + // Placed textures left null: the largest at each address. + let mut placed = HashMap::new(); for seen in inner.slots.values() { match seen { Seen::Buffer(..) => buffers += 1, Seen::Texture(_) => textures += 1, - Seen::Left(k) => left[*k] += 1, + Seen::Left((k, address, bytes)) => { + left[*k] += 1; + if *k == 2 { + let b = placed.entry(*address).or_insert(0u64); + *b = (*b).max(*bytes); + } + } } } + let placed_mb = placed.values().sum::() as f64 / 1e6; let bytes: u64 = inner.ranges.keys().map(|&(_, a, b, _)| b - a).sum(); drop(inner); let hulls = viewed.ranges(); @@ -330,11 +343,13 @@ pub(crate) fn log(frames: f64) { "heap views: {draws:.0} draws/frame index the heap ({writes:.0} writing through it), \ {uploaded:.0} textures uploaded/frame; slots: {buffers} buffer views ({} ranges, \ {:.1} MB, {copies} copies), {textures} title-written textures ({} distinct); \ - left null: {}; host copies of title memory: {} ({:.1} MB); hulls {:.1} MB, unordered {:.1} MB", + left null: {} (placed textures at {} addresses, {placed_mb:.0} MB); \ + host copies of title memory: {} ({:.1} MB); hulls {:.1} MB, unordered {:.1} MB", inner.ranges.len(), bytes as f64 / 1e6, inner.textures.len(), left.join(", "), + placed.len(), all.len(), all_bytes as f64 / 1e6, all_hulls as f64 / 1e6, diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index f1d7f6c56b..dd41940623 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -1151,6 +1151,7 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option { View::Shader(resource, desc) => { let resource = *resource as crate::object::This; if let Some(copy) = crate::resource::host_copy(resource) { + copy.viewed.store(true, std::sync::atomic::Ordering::Relaxed); let texture = ©.texture; let mut desc = desc.as_ref().map(srv_desc); if desc.is_none() && !default_view(resource) { @@ -1186,6 +1187,7 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option { _ => None, }; }; + copy.viewed.store(true, std::sync::atomic::Ordering::Relaxed); let texture = ©.texture; // A depth texture's unordered views write its twin. // SAFETY: a live resource. diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index bffec23c9e..6b8dc3068d 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -258,6 +258,20 @@ fn create() -> windows::core::Result { } } +/// Diagnostics: our process's private commit and working set, bytes. +#[cfg(feature = "diagnostics")] +fn process_memory() -> (u64, u64) { + use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS}; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + let mut c = PROCESS_MEMORY_COUNTERS { + cb: size_of::() as u32, + ..Default::default() + }; + // SAFETY: our own process and a sized structure. + unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb) }; + (c.PagefileUsage as u64, c.WorkingSetSize as u64) +} + /// DXGI may return hardware for `EnumWarpAdapter` (notably under Proton). /// Reject it before creating a device in diagnostics' software-only mode. fn warp_adapter() -> windows::core::Result { @@ -2489,11 +2503,23 @@ impl Meter { #[cfg(feature = "diagnostics")] { if let Some([(local, budget), (system, system_budget)]) = video_memory() { + let (commit, working_set) = process_memory(); tracing::info!( "video memory: {local:.0} MB of a {budget:.0} MB budget on the card, \ - {system:.0} MB of {system_budget:.0} MB in system memory" + {system:.0} MB of {system_budget:.0} MB in system memory; process commit {:.0} MB, \ + working set {:.0} MB; texture staging {:.0} MB; placed textures made {:.0} MB", + commit as f64 / 1e6, + working_set as f64 / 1e6, + crate::texture::STAGING_BYTES.load(Ordering::Relaxed) as f64 / 1e6, + crate::resource::PLACED_BYTES.load(Ordering::Relaxed) as f64 / 1e6, ); } + let [gpu, title] = crate::resource::texture_census().map(|r| r.map(|b| b as f64 / 1e6)); + tracing::info!( + "host texture MB (used by lists, viewed by heap slots only, neither): GPU-written {:.0} {:.0} {:.0}, \ + from title memory {:.0} {:.0} {:.0}", + gpu[0], gpu[1], gpu[2], title[0], title[1], title[2] + ); let copy_frames = std::mem::take(&mut self.copy_stats_frames) as f64; log_gpu_times(copy_frames); crate::copystat::log(copy_frames); diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index 89417d1d2f..801bd21485 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -786,6 +786,8 @@ pub(crate) struct HostTexture { bytes: u64, /// A list used it (counted once). used: std::sync::atomic::AtomicBool, + /// A shader-visible heap slot viewed it (diagnostics: [`texture_census`]). + pub(crate) viewed: std::sync::atomic::AtomicBool, } #[cfg(windows)] @@ -811,6 +813,7 @@ impl HostTexture { twin: std::sync::OnceLock::new(), bytes, used: false.into(), + viewed: false.into(), } } @@ -854,6 +857,23 @@ pub(crate) fn texture_counts() -> (u64, u64, u64, u64, u64, u64) { (TEXTURES.load(Relaxed), TEXTURE_BYTES.load(Relaxed), USED.load(Relaxed), shared.0, shared.1, shared.2) } +/// Bytes of the live host textures of title textures by what wrote them +/// (index 0 the GPU: render target, depth or unordered access; 1 title +/// memory) and how they were reached (0 by lists, 1 only by heap slots, 2 +/// neither). +#[cfg(all(windows, feature = "diagnostics"))] +pub(crate) fn texture_census() -> [[u64; 3]; 2] { + use std::sync::atomic::Ordering::Relaxed; + let mut bytes = [[0; 3]; 2]; + let map = MEMORY.lock().unwrap_or_else(|e| e.into_inner()); + for t in map.iter().flat_map(|m| m.values()).filter_map(std::sync::Weak::upgrade) { + let gpu = usize::from(!crate::texture::title_written(&t.texture)); + let reach = if t.used.load(Relaxed) { 0 } else if t.viewed.load(Relaxed) { 1 } else { 2 }; + bytes[1 - gpu][reach] += t.bytes; + } + bytes +} + #[cfg(windows)] impl Drop for HostTexture { fn drop(&mut self) { @@ -1598,6 +1618,19 @@ pub(crate) extern "system" fn create_at_address( static PLACED_TEXTURES: std::sync::Mutex> = std::sync::Mutex::new(std::collections::BTreeMap::new()); +/// Console bytes of the placed textures [`texture_at`] made (they are never +/// released). +#[cfg(windows)] +pub(crate) static PLACED_BYTES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// Console bytes of a texture of resource description `desc` (as words). +#[cfg(windows)] +pub(crate) fn placed_size(desc: &[u32; 14]) -> Option { + // SAFETY: 56 bytes in the description's layout. + let d = unsafe { desc.as_ptr().cast::().read_unaligned() }; + (d.dimension != BUFFER).then(|| footprint(&d).map(|f| f.size)).flatten() +} + /// The resource for a texture placed at `address` with the resource /// description `desc` (as words), made on first use. #[cfg(windows)] @@ -1634,6 +1667,7 @@ pub(crate) fn texture_at(address: u64, desc: &[u32; 14]) -> Option { if made != S_OK { return None; } + PLACED_BYTES.fetch_add(placed_size(desc).unwrap_or(0), std::sync::atomic::Ordering::Relaxed); map.insert((address, *desc), out as usize); resource(out).host.is_some().then_some(out) } diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 9b3d38e6db..f6f14d43b1 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -60,6 +60,17 @@ struct Last { read: Vec, } +/// Bytes of live staging buffers and of title memory read for them (the +/// fps line's companion). +pub(crate) static STAGING_BYTES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +impl Drop for Staging { + fn drop(&mut self) { + let read = self.last.get_mut().map_or(0, |l| l.read.capacity()) as u64; + STAGING_BYTES.fetch_sub(self.size + read, std::sync::atomic::Ordering::Relaxed); + } +} + // SAFETY: the staging mapping is written only at submission, under // `last`'s lock; the title memory is only read. unsafe impl Send for Staging {} @@ -308,7 +319,9 @@ impl Staging { } // Read through the copy, which stands unmapped pages: memory of // big pools is too slow to ask page by page. + let had = last.read.capacity(); last.read.resize(size, 0); + STAGING_BYTES.fetch_add((last.read.capacity() - had) as u64, std::sync::atomic::Ordering::Relaxed); crate::host::copy_mapped(last.read.as_mut_ptr(), self.memory, size, false); self.detile(&last.read); #[cfg(feature = "diagnostics")] @@ -466,6 +479,7 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option> { ) }); tracing::debug!(?desc, total, "texture contents uploaded from title memory"); + STAGING_BYTES.fetch_add(total, std::sync::atomic::Ordering::Relaxed); let layout_size = layout.size as usize; let s = Arc::new(Staging { buffer, From a7381ed606cb41cc78aef314a3df66260af8d9ef Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 03:16:36 +0100 Subject: [PATCH 09/83] GPU: host textures made on first use Every title texture got a host texture (VRAM) when the title created it. Run textures1's census in the intro cutscene: of 11.6 GB of host textures, 4.8 GB were textures fed from title memory that no list ever used and no heap slot ever viewed, and the card's usage was 12.3-12.4 GB against a 10.78 GB budget. A title texture's host texture is now made the first time anything asks for it: a list's barrier, binding, copy or upload, a heap slot's view. As textures of one memory can now be made in any order, the first one made takes the uses (render target, depth, unordered access) of every title texture of that memory, so a later one with more uses shares it instead of replacing it (which had left the first one's views on a texture the GPU never writes). The creation's state and clear value are kept for it. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/resource.rs | 98 ++++++++++++++++++++++++------ 1 file changed, 79 insertions(+), 19 deletions(-) diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index 801bd21485..b5f196703a 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -751,10 +751,13 @@ struct Resource { heap: HeapProperties, heap_flags: u32, backing: Backing, - /// Textures also live on the host GPU (decision 0007); buffers do not - /// yet. + /// Textures also live on the host GPU (decision 0007), made on first use + /// ([`Resource::host`]); buffers do not yet. #[cfg(windows)] - host: Option>, + host: std::sync::OnceLock>>, + /// The creation's initial state and clear value, for the host texture. + #[cfg(windows)] + made_with: (u32, Option<[u32; 5]>), } /// A title texture's host copy and the state it is in. The title's barriers @@ -985,7 +988,7 @@ pub(crate) mod life { #[cfg(windows)] pub(crate) fn host_transition(this: This, wanted: u32) -> Option<(*mut c_void, u32)> { use windows::core::Interface; - let host = resource(this).host.as_ref()?; + let host = resource(this).host()?; let before = host .state .swap(wanted, std::sync::atomic::Ordering::Relaxed); @@ -1000,7 +1003,7 @@ pub(crate) fn host_resource<'a>( if this.is_null() { return None; } - resource(this).host.as_deref().map(|h| &h.texture) + resource(this).host().map(|h| &h.texture) } /// A title texture's host copy, shared, for a list to hold. @@ -1009,7 +1012,7 @@ pub(crate) fn host_copy(this: This) -> Option> { if this.is_null() { return None; } - resource(this).host.clone() + resource(this).host().cloned() } /// The host description of a title texture: the same, without the @@ -1141,6 +1144,17 @@ fn shared_texture( } return live; } + // Host textures are made on first use, in any order: the new one takes + // the uses of every title texture of the memory, so none replaces it. + let mut d = d; + if let Some(k) = key { + let at = TEXTURES_AT.lock().unwrap_or_else(|e| e.into_inner()); + for r in at.get(&address).into_iter().flatten().map(|&r| resource(r as This)) { + if memory_key(address, &r.desc) == Some(k) { + d.flags |= host_desc(&r.desc).map_or(0, |h| h.flags & USES); + } + } + } // shortcut: title textures of a replaced host texture keep it (placed // views move to the new one, `texture_at`); copies (`alias_source`) // bridge the two where the shapes allow. @@ -1176,7 +1190,7 @@ fn takes(t: &HostTexture, d: &ResourceDesc) -> bool { #[cfg(windows)] fn current(this: This) -> bool { let r = resource(this); - let (Some(h), Some(k)) = (&r.host, memory_key(r.data() as u64, &r.desc)) else { + let (Some(Some(h)), Some(k)) = (r.host.get(), memory_key(r.data() as u64, &r.desc)) else { return true; }; let map = MEMORY.lock().unwrap_or_else(|e| e.into_inner()); @@ -1306,6 +1320,21 @@ pub(crate) fn buffer_bytes(this: This) -> Option<(*mut u8, u64)> { } impl Resource { + /// Its host texture, made the first time it is asked for: a list uses + /// the texture, a heap slot views it, a copy or upload reaches it. Most + /// of the title's textures are never used (decision 0007, "Host + /// textures made on first use"). + #[cfg(windows)] + fn host(&self) -> Option<&std::sync::Arc> { + self.host + .get_or_init(|| { + let (state, clear) = self.made_with; + let clear = clear.as_ref().map_or(std::ptr::null(), |c| std::ptr::from_ref(c).cast()); + shared_texture(self.data() as u64, &self.desc, state, clear) + }) + .as_ref() + } + fn data(&self) -> *mut u8 { match self.backing { Backing::Committed(ref memory) => memory.ptr.as_ptr(), @@ -1341,25 +1370,25 @@ fn hand_out_resource( ) -> HRESULT { #[cfg(not(windows))] let _ = (state, clear); - #[allow(unused_mut)] // the host texture is set on Windows only - let mut resource = Box::new(Resource { + let resource = Box::new(Resource { object: Object::new(&RESOURCE_FUNCTIONS), desc, heap, heap_flags, backing, #[cfg(windows)] - host: None, + host: std::sync::OnceLock::new(), + // The clear value names the format too: format, then color or + // depth and stencil (5 words), kept for when the texture is made. + #[cfg(windows)] + // SAFETY: the title passes a whole clear value (or null). + made_with: (state, (!clear.is_null()).then(|| unsafe { clear.cast::<[u32; 5]>().read_unaligned() })), }); #[cfg(windows)] - { - resource.host = shared_texture(resource.data() as u64, &desc, state, clear); - } - #[cfg(windows)] if desc.dimension == BUFFER { let at = std::ptr::from_ref::(&resource) as usize; crate::shadow::register(at, resource.data() as u64, desc.width); - } else if resource.host.is_some() { + } else if host_desc(&desc).is_some() { let at = std::ptr::from_ref::(&resource) as usize; let mut map = TEXTURES_AT.lock().unwrap_or_else(|e| e.into_inner()); map.entry(resource.data() as u64).or_default().push(at); @@ -1404,7 +1433,7 @@ pub(crate) fn alias_source(placed: This) -> Option { let a = resource(r); a.desc.flags & WRITTEN != 0 && bytes(&a.desc) == Some(want) - && matches!((&a.host, &b.host), (Some(x), Some(y)) if !std::sync::Arc::ptr_eq(x, y)) + && matches!((a.host.get(), b.host.get()), (Some(Some(x)), Some(Some(y))) if !std::sync::Arc::ptr_eq(x, y)) }) } @@ -1414,7 +1443,8 @@ impl Drop for Resource { #[cfg(feature = "diagnostics")] if self .host - .as_ref() + .get() + .and_then(Option::as_ref) .is_some_and(|h| std::sync::Arc::strong_count(h) > 1) { // Before lists held their textures, this freed a texture that @@ -1430,7 +1460,7 @@ impl Drop for Resource { } } #[cfg(feature = "diagnostics")] - if let Some(h) = &self.host { + if let Some(Some(h)) = self.host.get() { use windows::core::Interface; life::note(h.texture.as_raw() as usize, life::RELEASED, 0, life::holders(&h.texture)); } @@ -1669,7 +1699,7 @@ pub(crate) fn texture_at(address: u64, desc: &[u32; 14]) -> Option { } PLACED_BYTES.fetch_add(placed_size(desc).unwrap_or(0), std::sync::atomic::Ordering::Relaxed); map.insert((address, *desc), out as usize); - resource(out).host.is_some().then_some(out) + resource(out).host().is_some().then_some(out) } pub(crate) extern "system" fn create_placed( @@ -1957,6 +1987,36 @@ mod tests { heap } + /// A title texture's host texture is made when first asked for, and a + /// texture of the same memory made later with more uses (unordered + /// access) shares it: the first one made takes every use the memory's + /// title textures have. + #[cfg(windows)] + #[test] + fn host_textures_are_made_on_first_use_with_every_use_of_their_memory() { + if crate::host::host().is_none() { + return; // no host GPU here + } + let null = std::ptr::null(); + let h = heap(1 << 20); + let place = |desc: &ResourceDesc| { + let mut out = null; + assert_eq!(create_placed(null, h, 0, desc, 0, null.cast(), &RESOURCE_IIDS[0], &mut out), S_OK); + out + }; + let read = place(&texture(64, 64, 28, 1)); + let written = place(&ResourceDesc { flags: UNORDERED, ..texture(64, 64, 28, 1) }); + assert!(resource(read).host.get().is_none() && resource(written).host.get().is_none(), "made at creation"); + let first = host_copy(read).expect("a host texture"); + // SAFETY: a live resource. + assert_ne!(unsafe { first.texture.GetDesc() }.Flags.0 as u32 & UNORDERED, 0, "the memory's uses"); + assert!(std::sync::Arc::ptr_eq(&first, &host_copy(written).unwrap()), "shared"); + for r in [read, written] { + assert_eq!(slot::(r, 0x10)(r), 0); + } + assert_eq!(slot::(h, 0x10)(h), 0); + } + /// Title textures of one memory share a key in any format of the same /// element; another address, shape, element size or a depth texture is /// another memory. The library's own layout pick resolves as spelled. From 5622159f29e8e4c7b5a14f63733a217de3a0e6a9 Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 03:24:52 +0100 Subject: [PATCH 10/83] GPU: debug lines for sampled texture uploads At `victory_gpu::texture=debug` (diagnostics builds): every detiling of a sampled texture says whether its memory was all zero, and a sampled texture that keeps what the host copied into it (never uploaded from title memory again) is named once. For the terrain's mesh-stage texture that `shards` found holding zeros (run shards2). Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/texture.rs | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index f6f14d43b1..b38f586403 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -207,7 +207,20 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) // even if the title later writes its memory too. // Once per list for each host texture, however many title textures of // its memory the list samples. - if is_host_written(resource) || !list.first_use(texture.as_raw() as usize) { + if is_host_written(resource) { + #[cfg(feature = "diagnostics")] + { + static SEEN: Mutex>> = Mutex::new(None); + if SEEN.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_default().insert(resource as usize) { + let memory = crate::resource::texture_memory(resource).map(|(m, _)| m); + // SAFETY: a live resource. + let desc = unsafe { texture.GetDesc() }; + tracing::debug!(?resource, ?memory, ?desc, "a sampled texture keeps what the host copied into it: not uploaded from title memory"); + } + } + return; + } + if !list.first_use(texture.as_raw() as usize) { return; } let Some(staging) = staging(resource, texture) else { @@ -362,6 +375,8 @@ impl Staging { desc = ?self.layout.desc, "a sampled texture's memory is all zero (not streamed yet, or a failed BCPack read)" ); + } else { + tracing::debug!(memory = ?self.memory, desc = ?self.layout.desc, "a sampled texture detiled"); } for (i, (footprint, &rows)) in self.footprints.iter().zip(&self.rows).enumerate() { let (mip, slice) = (i as u32 % self.mips, i as u32 / self.mips); From 5cb63d8b28b950a2f4d25bef1c341de133771c24 Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 04:13:46 +0100 Subject: [PATCH 11/83] GPU: texture to buffer copies read back into the title's buffer The title reads textures back from the world's first frame on (CopyTextureRegion, texture to a placed footprint in a buffer) and VIctory dropped every such copy ("texture to buffer copies not implemented", TODO.md since 2026-11-23): whatever the title computes from those bytes on the CPU used stale memory. The region is now copied on the host into readback memory laid out as the title's footprint (offset 0, the title's 256-byte pitch), and once the list has run, before its bottom-of-pipe writes and so before the title can see its fence, each row of the region goes into the title's buffer (watch::writing + write_mapped, as copy-backs do). Refused with a reason, once: depth or stencil textures, pitches not a multiple of 256, regions outside the footprint. Diagnostics: the first read back of each (texture, buffer) pair is logged with the texture's memory, size and format, and every 5 s "texture read backs: N/frame, KB/frame". Measured (run shards5, this on 5622159f): the title reads back two textures from the world's first frame on, each into one of two buffers it alternates between: a 5x1 R32G32B32A32_FLOAT (80 bytes, written by avgLuminanceCompute:LuminanceMinMaxDownsampleFinalCS) and a 1x1 R32G32B32A32_FLOAT (16 bytes, written by ComputeAverageDepthWeightedLuminanceFromHistogramCS): the auto-exposure values its CPU side adapts with, so far read stale. 4.0 read backs a frame, 0.2 KB a frame; nothing refused. Tests: a footprint's row ranges, and a round trip through the title's API (a texture filled from a buffer through our list's copy slot, a region of it read back into a second title buffer through the same slot, run by our queue; the region's rows land at the footprint's offset and pitch, the rest of the buffer is untouched). The round trip caught a first version whose readback memory ended at the region's last row: the host copies into a footprint only in a buffer that holds all of it, so the list failed and the process ended. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/host.rs | 29 ++++++- crates/victory-gpu/src/list.rs | 121 ++++++++++++++++++++++++++++- crates/victory-gpu/src/resource.rs | 112 ++++++++++++++++++++++++-- 3 files changed, 250 insertions(+), 12 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 6b8dc3068d..8156d8b8c3 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -1794,6 +1794,15 @@ impl HostList { Some((buffer, data)) } + /// A mapped readback buffer of `size` bytes, alive until the list is + /// reset. + pub(crate) fn readback(&self, host: &Host, size: u64) -> Option<(ID3D12Resource, *mut u8)> { + let (buffer, data) = host.mapped_buffer(size, true)?; + name(&buffer, || format!("list readback {size:#x}")); + self.deferred().uploads.push(buffer.clone()); + Some((buffer, data)) + } + /// `len` bytes of upload memory (256-byte aligned) until the list is /// reset: the host GPU address and the CPU pointer. pub(crate) fn scratch(&self, len: u64) -> Option<(u64, *mut u8)> { @@ -2317,8 +2326,14 @@ impl Host { } pub(crate) fn upload_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> { + self.mapped_buffer(size, false) + } + + /// A mapped buffer of `size` bytes: upload memory, or (`readback`) + /// readback memory in the copy-destination state. + fn mapped_buffer(&self, size: u64, readback: bool) -> Option<(ID3D12Resource, *mut u8)> { let heap = D3D12_HEAP_PROPERTIES { - Type: D3D12_HEAP_TYPE_UPLOAD, + Type: if readback { D3D12_HEAP_TYPE_READBACK } else { D3D12_HEAP_TYPE_UPLOAD }, ..Default::default() }; let desc = D3D12_RESOURCE_DESC { @@ -2343,7 +2358,7 @@ impl Host { &heap, D3D12_HEAP_FLAG_NONE, &desc, - D3D12_RESOURCE_STATE_GENERIC_READ, + if readback { D3D12_RESOURCE_STATE_COPY_DEST } else { D3D12_RESOURCE_STATE_GENERIC_READ }, None, &mut buffer, ) @@ -2355,7 +2370,7 @@ impl Host { match made { Ok(()) => Some((buffer?, data.cast())), Err(e) => { - tracing::warn!(error = %e, size, "no upload buffer"); + tracing::warn!(error = %e, size, readback, "no mapped buffer"); None } } @@ -2525,6 +2540,14 @@ impl Meter { crate::copystat::log(copy_frames); crate::bindless::log(copy_frames); crate::shadow::log_views(copy_frames); + let [n, bytes] = [0, 1].map(|i| crate::list::READ_BACKS[i].swap(0, Ordering::Relaxed)); + if n > 0 { + tracing::info!( + "texture read backs: {:.1}/frame, {:.1} KB/frame", + n as f64 / frames, + bytes as f64 / frames / 1e3 + ); + } for (why, n) in drops.iter().take(40) { tracing::info!( "dropped {:.1}/frame without a host pipeline: {why}", diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index edcebb866e..8df296f96c 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -497,8 +497,8 @@ pub(crate) struct CopyLocation { } /// Texture to texture on the GPU; buffer to texture through an upload -/// buffer filled at submission. Texture to buffer (read back) is not done -/// yet. +/// buffer filled at submission; texture to buffer through readback memory +/// ([`read_back`]). extern "system" fn copy_texture_region( this: This, dst: *const CopyLocation, @@ -522,8 +522,9 @@ extern "system" fn copy_texture_region( return; }; let Some(to) = crate::resource::host_resource(dst.resource) else { - static ONCE: std::sync::Once = std::sync::Once::new(); - ONCE.call_once(|| tracing::warn!("texture to buffer copies not implemented")); + if dst.kind == FOOTPRINT && src.kind != FOOTPRINT { + read_back(list, &dst, [x, y, z], &src, source_box); + } return; }; let mut from = src; @@ -607,6 +608,118 @@ extern "system" fn copy_texture_region( let _ = (this, dst, x, y, z, src, source_box); } +/// Texture read backs since the last frame-rate line: how many, bytes +/// (diagnostics). +#[cfg(feature = "diagnostics")] +pub(crate) static READ_BACKS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// (texture, buffer) pairs read back so far, each logged once (diagnostics). +#[cfg(feature = "diagnostics")] +static READ_BACK_PAIRS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + +/// Texture to buffer (a read back): the region is copied on the host into +/// readback memory laid out as the title's footprint, and once the list has +/// run its rows go into the title's buffer (the title reads them on the CPU +/// after its fence). +#[cfg(windows)] +fn read_back(list: &crate::host::HostList, dst: &CopyLocation, at: [u32; 3], src: &CopyLocation, source_box: *const [u32; 6]) { + use windows::Win32::Graphics::Direct3D12::{ + D3D12_BOX, D3D12_RESOURCE_DIMENSION_TEXTURE3D, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, + }; + use windows::core::Interface; + macro_rules! refused { + ($why:literal) => {{ + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::warn!(concat!("texture to buffer copy refused: ", $why))); + return; + }}; + } + let (Some(host), Some(texture)) = (crate::host::host(), crate::resource::host_resource(src.resource)) else { + refused!("no host texture"); + }; + // SAFETY: the title's box (same layout as the host's) or null; a live texture. + let (b, desc) = unsafe { (source_box.cast::().as_ref(), texture.GetDesc()) }; + let size = match b { + Some(b) => [b.right.saturating_sub(b.left), b.bottom.saturating_sub(b.top), b.back.saturating_sub(b.front)], + None => { + // A subresource index shares the footprint's first dword. + let mip = src.footprint.offset as u32 % u32::from(desc.MipLevels.max(1)); + let depth = if desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D { u32::from(desc.DepthOrArraySize) } else { 1 }; + [((desc.Width >> mip) as u32).max(1), (desc.Height >> mip).max(1), (depth >> mip).max(1)] + } + }; + // The host takes footprints of 256-byte pitches only (as the console). + if !dst.footprint.row_pitch.is_multiple_of(256) { + refused!("a row pitch not a multiple of 256"); + } + // shortcut: depth and stencil planes copy out in typeless formats of + // their own; refused until a title is seen reading one back. + if desc.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL.0 != 0 { + refused!("a depth or stencil texture"); + } + // The host copies into a footprint only within a buffer that holds all + // of it, so readback memory spans the footprint, not just the region. + let (Some(rows), Some(len)) = (dst.footprint.rows(at, size), dst.footprint.bytes()) else { + refused!("a region outside its footprint"); + }; + let (Some(title), Some((buffer, data))) = (buffer_range(dst.resource, dst.footprint.offset, len), list.readback(host, len)) else { + return; + }; + if crate::texture::title_written(texture) { + crate::texture::upload(list, src.resource, texture); + } + ensure_state(list, src.resource, COPY_SOURCE); + let (mut to, mut from) = (*dst, *src); + to.resource = buffer.as_raw().cast_const().cast(); + to.footprint.offset = 0; + from.resource = texture.as_raw().cast_const().cast(); + #[cfg(feature = "diagnostics")] + { + let text = || { + let mem = crate::resource::texture_memory(src.resource).map_or(0, |(at, _)| at as usize); + format!( + "read back {:?} (mem {mem:#x}, {}x{} f{} sub {}) {size:?} at {at:?} into {:?}+{:#x}, {len} bytes", + src.resource, + desc.Width, + desc.Height, + desc.Format.0, + src.footprint.offset as u32, + dst.resource, + dst.footprint.offset + ) + }; + READ_BACKS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + READ_BACKS[1].fetch_add(len, std::sync::atomic::Ordering::Relaxed); + let pair = (src.resource as usize, dst.resource as usize); + let mut seen = READ_BACK_PAIRS.lock().unwrap_or_else(|e| e.into_inner()); + if !seen.contains(&pair) { + seen.push(pair); + tracing::info!("a texture read back (first of this pair): {}", text()); + } + list.note_op(text); + } + // SAFETY: an open list; both locations in the host's layout, naming live + // resources; the region lies in the footprint (checked). + unsafe { + list.list.CopyTextureRegion( + (&raw const to).cast(), + at[0], + at[1], + at[2], + (&raw const from).cast(), + b.map(std::ptr::from_ref), + ) + }; + let (data, title) = (data as usize, title as usize); + list.defer_after(move || { + for &(at, n) in &rows { + let (at, n) = (at as usize, n as usize); + let _writing = crate::watch::writing(title + at, n); + crate::host::write_mapped((title + at) as *mut u8, (data + at) as *const u8, n); + } + }); +} + #[allow(clippy::too_many_arguments)] // the method's own arguments extern "system" fn copy_texture_region_x( this: This, diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index b5f196703a..dcc0ab1924 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -316,11 +316,11 @@ fn mip_count(desc: &ResourceDesc) -> u32 { #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) struct PlacedFootprint { pub(crate) offset: u64, - format: u32, - width: u32, - height: u32, - depth: u32, - row_pitch: u32, + pub(crate) format: u32, + pub(crate) width: u32, + pub(crate) height: u32, + pub(crate) depth: u32, + pub(crate) row_pitch: u32, } impl PlacedFootprint { @@ -331,6 +331,27 @@ impl PlacedFootprint { let last = u64::from(self.width).div_ceil(block) * element; Some(u64::from(self.row_pitch) * lines.saturating_sub(1) + last) } + + /// The byte ranges (from the footprint's start) that a `size` texel + /// region at texel `at` covers: one per row of blocks; `None` if the + /// format has no size or the region leaves the footprint. + pub(crate) fn rows(&self, at: [u32; 3], size: [u32; 3]) -> Option> { + let (element, block) = element(self.format)?; + let blocks = |texels: u32| u64::from(texels).div_ceil(block); + let [x, y, z] = at.map(u64::from); + let (w, h, d) = (blocks(size[0]), blocks(size[1]), u64::from(size[2])); + let (x, y) = (x / block, y / block); + if x + w > blocks(self.width) || y + h > blocks(self.height) || z + d > u64::from(self.depth) { + return None; + } + let pitch = u64::from(self.row_pitch); + let slice = pitch * blocks(self.height); + Some( + (z..z + d) + .flat_map(|k| (y..y + h).map(move |r| (k * slice + r * pitch + x * element, w * element))) + .collect(), + ) + } } const _: () = assert!(size_of::() == 32); @@ -1914,6 +1935,17 @@ pub(crate) fn test_buffer(width: u64) -> This { #[cfg(test)] mod tests { use super::*; + + #[test] + fn a_regions_rows_in_a_footprint() { + // R32_FLOAT (41) 100x8x1, pitch 512. + let f = PlacedFootprint { offset: 4096, format: 41, width: 100, height: 8, depth: 1, row_pitch: 512 }; + assert_eq!(f.rows([2, 3, 0], [10, 2, 1]), Some(vec![(3 * 512 + 8, 40), (4 * 512 + 8, 40)])); + assert_eq!(f.rows([95, 0, 0], [10, 1, 1]), None, "past the width"); + // BC1 (71) 16x16, 8 bytes a 4x4 block, pitch 256: a block row per 4 texel rows. + let bc = PlacedFootprint { offset: 0, format: 71, width: 16, height: 16, depth: 1, row_pitch: 256 }; + assert_eq!(bc.rows([4, 4, 0], [8, 8, 1]), Some(vec![(256 + 8, 16), (2 * 256 + 8, 16)])); + } use crate::object::slot; #[test] @@ -2477,6 +2509,76 @@ mod tests { } } + /// A texture region copied into a title buffer through our list and + /// queue: once the list has run, its rows are in the buffer at the + /// footprint's offset and pitch, and nothing else of the buffer moved. + #[cfg(windows)] + #[test] + fn a_texture_read_back_reaches_the_title_buffer() { + if crate::host::host().is_none() { + return; // no host GPU here + } + let null = std::ptr::null(); + let iid = &RESOURCE_IIDS[0]; + const COPY_DEST: u32 = 0x400; + let (mut image, mut source, mut target) = (null, null, null); + let created = |desc: &ResourceDesc, state, out: &mut This| { + assert_eq!(create_committed(null, &PROPERTIES, 0, desc, state, null.cast(), iid, out), S_OK); + }; + created(&texture(4, 4, 28, 1), COPY_DEST, &mut image); + created(&buffer(1024), 0, &mut source); + created(&buffer(4096), 0, &mut target); + let (data, _) = buffer_bytes(source).unwrap(); + // SAFETY: the buffer holds 1024 bytes. + let bytes = unsafe { std::slice::from_raw_parts_mut(data, 1024) }; + for (i, b) in bytes.iter_mut().enumerate() { + *b = (i % 251) as u8; + } + let (out, _) = buffer_bytes(target).unwrap(); + // SAFETY: the buffer holds 4096 bytes. + unsafe { std::ptr::write_bytes(out, 0xEE, 4096) }; + let (mut queue, mut allocator, mut list) = (null, null, null); + let queue_desc = [0u32; 4]; + assert_eq!( + crate::queue::create(null, queue_desc.as_ptr().cast(), &guid(0x0ec870a6, 0x5d7e, 0x4c22, [0x8c, 0xfc, 0x5b, 0xaa, 0xe0, 0x76, 0x16, 0xed]), &mut queue), + S_OK + ); + assert_eq!( + crate::list::create_allocator(null, 0, &guid(0x6102dee4, 0xaf59, 0x4b09, [0xb9, 0x99, 0xb4, 0x4d, 0x73, 0xf0, 0x9b, 0x24]), &mut allocator), + S_OK + ); + assert_eq!( + crate::list::create_list(null, 0, 0, allocator, null, &guid(0x5b160d0f, 0xac1b, 0x4185, [0x8b, 0xa8, 0xb3, 0xae, 0x42, 0xa5, 0xa4, 0x55]), &mut list), + S_OK + ); + #[repr(C)] + struct Location { + resource: This, + kind: u32, + footprint: PlacedFootprint, + } + let rows = PlacedFootprint { offset: 0, format: 28, width: 4, height: 4, depth: 1, row_pitch: 256 }; + let image_at = Location { resource: image, kind: 0, footprint: rows }; + let from_source = Location { resource: source, kind: 1, footprint: rows }; + // Texels (1..3, 1..3) into the target's footprint at 512, at texel (2, 1). + let into_target = Location { resource: target, kind: 1, footprint: PlacedFootprint { offset: 512, ..rows } }; + let region: [u32; 6] = [1, 1, 0, 3, 3, 1]; + type Copy = extern "system" fn(This, *const Location, u32, u32, u32, *const Location, *const u8); + let copy = slot::(list, 0x80); + copy(list, &image_at, 0, 0, 0, &from_source, null.cast()); + copy(list, &into_target, 2, 1, 0, &image_at, region.as_ptr().cast()); + slot:: HRESULT>(list, 0x48)(list); + slot::(queue, 0x50)(queue, 1, &list); + // SAFETY: the buffer holds 4096 bytes; the submission has run. + let read = unsafe { std::slice::from_raw_parts(out, 4096) }; + let mut want = vec![0xEEu8; 4096]; + for row in 0..2 { + let (to, from) = (512 + (1 + row) * 256 + 2 * 4, (1 + row) * 256 + 4); + want[to..to + 8].copy_from_slice(&bytes[from..from + 8]); + } + assert!(read == want.as_slice(), "the region's rows, and nothing else"); + } + #[test] fn committed_and_placed_resources_map_at_their_gpu_address() { let null = std::ptr::null(); From 97721d1d2ca04c1c79dd96759c647c7b0bbeb7f7 Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 04:19:00 +0100 Subject: [PATCH 12/83] GPU: the title memory read to detile a tracked texture is not kept A journal-tracked texture's detiling read its title memory into a buffer the texture's staging kept for its whole life: each such texture took its size once more in system memory, besides its upload buffer. The read is now a temporary. Texture staging in the cutscene: 414 MB (run textures2, read buffers kept) against 195 MB (run textures3, not kept). Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/texture.rs | 20 ++++++++------------ 1 file changed, 8 insertions(+), 12 deletions(-) diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index b38f586403..cfac0d8982 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -53,21 +53,18 @@ pub(crate) struct Staging { } /// What a texture's staging buffer holds: the hash of the memory detiled -/// (memory not tracked), with room to read tracked memory into. +/// (memory not tracked). #[derive(Default)] struct Last { hash: Option, - read: Vec, } -/// Bytes of live staging buffers and of title memory read for them (the -/// fps line's companion). +/// Bytes of live staging buffers (the fps line's companion). pub(crate) static STAGING_BYTES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); impl Drop for Staging { fn drop(&mut self) { - let read = self.last.get_mut().map_or(0, |l| l.read.capacity()) as u64; - STAGING_BYTES.fetch_sub(self.size + read, std::sync::atomic::Ordering::Relaxed); + STAGING_BYTES.fetch_sub(self.size, std::sync::atomic::Ordering::Relaxed); } } @@ -331,12 +328,11 @@ impl Staging { return (0, false); } // Read through the copy, which stands unmapped pages: memory of - // big pools is too slow to ask page by page. - let had = last.read.capacity(); - last.read.resize(size, 0); - STAGING_BYTES.fetch_add((last.read.capacity() - had) as u64, std::sync::atomic::Ordering::Relaxed); - crate::host::copy_mapped(last.read.as_mut_ptr(), self.memory, size, false); - self.detile(&last.read); + // big pools is too slow to ask page by page. Not kept: it would + // double each texture's system memory. + let mut read = vec![0u8; size]; + crate::host::copy_mapped(read.as_mut_ptr(), self.memory, size, false); + self.detile(&read); #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexWatched, size as u64); return (size, true); From 743398874f9866c408d5a28b926f760d683e9a93 Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 04:21:58 +0100 Subject: [PATCH 13/83] GPU: 8-bit RGBA dumps log their alpha range and zero counts The dumps write 8-bit colour as is and drop alpha; a line per dump now gives each channel's range and how many texels hold zero there (the grass trail map's alpha, for the missing ground). Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/capture.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/crates/victory-gpu/src/capture.rs b/crates/victory-gpu/src/capture.rs index c0f2b7f9df..88adb536bb 100644 --- a/crates/victory-gpu/src/capture.rs +++ b/crates/victory-gpu/src/capture.rs @@ -630,12 +630,20 @@ fn to_rgba(format: u32, w: usize, h: usize, pitch: usize, rows: &[u8]) -> Option type Decode = Box [f32; 3]>; let (n, decode): (usize, Decode) = match format { 27..=32 => { + // The PNG drops alpha: its range and how many texels have each + // channel zero are logged. + let (mut low, mut high, mut zero) = ([255u8; 4], [0u8; 4], [0usize; 4]); for y in 0..h { for x in 0..w { let p = px(x, y, 4); + for c in 0..4 { + (low[c], high[c]) = (low[c].min(p[c]), high[c].max(p[c])); + zero[c] += usize::from(p[c] == 0); + } out.extend([p[0], p[1], p[2], 255]); } } + tracing::info!(format, ?low, ?high, ?zero, texels = w * h, "target values (8-bit, RGBA)"); return Some(out); } // B8G8R8A8 and B8G8R8X8 (89 is R10G10B10_XR_BIAS_A2, below). From 98c654b78893fe3245c2a244ceace271193de574 Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 04:59:15 +0100 Subject: [PATCH 14/83] GPU: the console's 16-bit depth with stencil is float depth on the host The console's 16-bit depth with stencil (formats 118-120; Grand Theft Auto VI's material depth) was a host D24S8 texture. CS_GenerateMaterialMasks and CS_MaterialTilesInitial write it through 16-bit unordered views (the depth twin), the 180 tiled-lighting draws then test it EQUAL at z = the material index times the title's 1/65535 (0x37800080), and the twin reached the depth plane as 24-bit unorm by copy. On the RX 6700 XT a draw at those depths passed EQUAL for k = 258 only of 1..4096: the driver keeps 24-bit depth as floats (AMD hardware has no 24-bit depth), so a copy stores d24 / (2^24 - 1) and the rasteriser the unquantised z, and the two agree only by accident. Every tiled-lighting draw failed its depth test on every pixel. Now 118-120 are D32_FLOAT_S8X24 (20-22) on the host, and the twin converter writes the float the title's own shaders compute for 16-bit value u, f32(u) * 0x37800080 (back: round(f * 65535)), so the depth plane holds the very float a draw rasterises. That float equals the correctly rounded u / 65535 (what the console's R16_UNORM view reads) for every u but 512 values from 257 up (1 ULP); every float rounds back to its u. Evidence: a_depth_texture_written_through_unordered_views_reads_as_depth now draws a square (two triangles, as the title's rectangles become) per pixel at the title's depth for k = 1..4096 against the UAV-written plane and asserts all pass (24-bit: only k = 258), on the RX 6700 XT (suite 147 passed) and WARP (150 passed, with diagnostics); the twin round trip, stencil and clear-to-16-bit checks still pass. Runs light5-light7 (240 s, warm, with the luminance read-back): no crash or removal. Run light7, frame 1515 (raw dumps): the lighting records with an instance (0, 1, 5, 7, 29) are exactly the material indices present; pixels whose 128x120 group lets their draw run are 86-99 % exactly zero after the lighting submission (index 5: 1.31 M pixels, 99 %), pixels whose group culls it only 41-60 %; the lighting pipelines test depth EQUAL, write no depth, use no stencil, depth bounds or blending. So the draws now pass and overwrite the target with their own result. Expect DARKER surfaces in the cutscene until the shadow tracing runs; not a regression of this change. Before it, those pixels kept what the material mask pass had written into the lighting target (light3's "lit-looking" buildings were those leftovers, not light). The tiled-lighting shader's per-light shadow factor reads a tile map and atlas (15360x180 R32_UINT, 4096x3640 R8_UINT) that are all zero because CS_TraceShadowRays_Checkerboard is dropped untranslated, so every shadowed light is skipped and the result is 0 there. Shortcut (comment at pc_format): a depth bias on such targets counts in float steps, not 1/65535. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/draw.rs | 146 +++++++++++++++++++++++++++-- crates/victory-gpu/src/resource.rs | 13 ++- crates/victory-gpu/src/twin.rs | 28 ++---- 3 files changed, 157 insertions(+), 30 deletions(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 4cf4fbe299..592fcbde90 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -1952,6 +1952,128 @@ void main(uint3 id : SV_DispatchThreadID) { } } + /// Which pixels of a 64x64 host D32S8 `texture` (title texture `depth`) + /// pass an EQUAL depth test against a square (two triangles, as the + /// title's rectangles become) drawn over pixel `k - 1` (row by row) with + /// z = k times the title's 1/65535 (`0x37800080`), the depth + /// `VS_TiledLighting` gives draw k: entry `k - 1`. + fn equal_test_passes(depth: This, texture: &ID3D12Resource) -> Vec { + use windows::Win32::Graphics::Dxgi::Common::*; + const SOURCE: &str = r#" +#define RS "RootFlags(0)" +static const float2 CORNERS[6] = { float2(0, 0), float2(1, 0), float2(0, 1), float2(1, 0), float2(1, 1), float2(0, 1) }; +[RootSignature(RS)] +float4 vs(uint v : SV_VertexID) : SV_Position { + uint i = v / 6; + float2 p = float2(i % 64, i / 64) + CORNERS[v % 6]; + return float4(p.x / 32.0 - 1.0, 1.0 - p.y / 32.0, (float)(i + 1) * asfloat(0x37800080), 1.0); +} +uint ps() : SV_Target { return 1; } +"#; + let host = crate::host::host().unwrap(); + let blob = |entry: windows::core::PCSTR, target: windows::core::PCSTR| { + let mut code: Option = None; + // SAFETY: the source and names outlive the call. + unsafe { D3DCompile(SOURCE.as_ptr().cast(), SOURCE.len(), s!("equal"), None, None, entry, target, 0, 0, &mut code, None) }.unwrap(); + code.unwrap() + }; + let (vs, ps) = (blob(s!("vs"), s!("vs_5_1")), blob(s!("ps"), s!("ps_5_1"))); + // SAFETY: the blobs' own bytes. + let bytes = |b: &ID3DBlob| unsafe { D3D12_SHADER_BYTECODE { pShaderBytecode: b.GetBufferPointer(), BytecodeLength: b.GetBufferSize() } }; + // SAFETY: a compiled shader with its root signature inside. + let root: ID3D12RootSignature = unsafe { + host.device.CreateRootSignature(0, std::slice::from_raw_parts(vs.GetBufferPointer().cast::(), vs.GetBufferSize())) + } + .unwrap(); + let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + // SAFETY: borrowed for the call. + pRootSignature: unsafe { std::mem::transmute_copy(&root) }, + VS: bytes(&vs), + PS: bytes(&ps), + SampleMask: u32::MAX, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + NumRenderTargets: 1, + DSVFormat: DXGI_FORMAT_D32_FLOAT_S8X24_UINT, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + desc.RTVFormats[0] = DXGI_FORMAT_R32_UINT; + desc.BlendState.RenderTarget[0].RenderTargetWriteMask = 0xf; + desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + desc.RasterizerState.DepthClipEnable = true.into(); + desc.DepthStencilState.DepthEnable = true.into(); + desc.DepthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ZERO; + desc.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_EQUAL; + // SAFETY: a complete description. + let pso: ID3D12PipelineState = unsafe { host.device.CreateGraphicsPipelineState(&desc) }.unwrap(); + let target_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 64, + Height: 64, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R32_UINT, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + ..Default::default() + }; + let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + let mut target: Option = None; + // SAFETY: plain creation. + unsafe { + host.device.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &target_desc, D3D12_RESOURCE_STATE_RENDER_TARGET, None, &mut target) + } + .unwrap(); + let target = target.unwrap(); + let mut f = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + let mut total = 0; + // SAFETY: outputs for one subresource. + unsafe { host.device.GetCopyableFootprints(&target_desc, 0, 1, 0, Some(&mut f), None, None, Some(&mut total)) }; + let (raw, data) = host.shared_buffer(total).unwrap(); + let list = host.new_list().unwrap(); + crate::list::ensure_state(&list, depth, 0x10); + let dsv = D3D12_DEPTH_STENCIL_VIEW_DESC { + Format: DXGI_FORMAT_D32_FLOAT_S8X24_UINT, + ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2D, + ..Default::default() + }; + let (rtv, dsv) = (host.rtv(&target, None), host.dsv(texture, Some(&dsv))); + // SAFETY: an open list; the target in the render target state, the + // depth texture in the depth write state; copies into our buffer. + unsafe { + let l = &list.list; + l.ClearRenderTargetView(rtv, &[0.0; 4], None); + l.OMSetRenderTargets(1, Some(&rtv), false, Some(&dsv)); + l.RSSetViewports(&[D3D12_VIEWPORT { Width: 64.0, Height: 64.0, MaxDepth: 1.0, ..Default::default() }]); + l.RSSetScissorRects(&[windows::Win32::Foundation::RECT { right: 64, bottom: 64, ..Default::default() }]); + l.SetGraphicsRootSignature(&root); + l.SetPipelineState(&pso); + l.IASetPrimitiveTopology(windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + l.DrawInstanced(64 * 64 * 6, 1, 0, 0); + l.ResourceBarrier(&[crate::host::transition(&target, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + let to = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&raw), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: f }, + }; + let from = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&target), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 }, + }; + l.CopyTextureRegion(&to, 0, 0, 0, &from, None); + } + list.close(); + host.execute(&[&list]); + (0..64 * 64) + .map(|i| { + // SAFETY: inside the mapped buffer, by the footprint. + unsafe { (data.add(f.Offset as usize + (i / 64) * f.Footprint.RowPitch as usize + (i % 64) * 4) as *const u32).read() == 1 } + }) + .collect() + } + /// A title buffer of `bytes` in memory of its own. fn buffer(bytes: u64) -> This { let desc: [u32; 14] = [1, 0, 0, 0, bytes as u32, (bytes >> 32) as u32, 1, 1 | 1 << 16, 0, 1, 0, 1, 0, 0]; @@ -2230,11 +2352,11 @@ void main(uint3 id : SV_DispatchThreadID) { } /// A depth texture with stencil (the console's 16-bit depth, the - /// host's 24-bit) written through unordered views of its planes, then - /// read as depth and stencil: the 16-bit depth arrives in 24 bits as - /// the host converts the same value, the stencil as written. Rendered - /// as depth (a clear), then used through the unordered view: back in - /// 16 bits. + /// host's 32-bit float) written through unordered views of its planes, + /// then read as depth and stencil: the 16-bit depth arrives as the + /// float the title's shaders compute for it, the stencil as written, + /// and a draw at that depth passes an EQUAL test. Rendered as depth (a + /// clear), then used through the unordered view: back in 16 bits. #[test] fn a_depth_texture_written_through_unordered_views_reads_as_depth() { let Some(host) = crate::host::host() else { @@ -2321,7 +2443,8 @@ void main(uint3 id : SV_DispatchThreadID) { } list.close(); host.execute(&[&list]); - let d24 = |u: u32| u * 256 + (u * 255 + 32767) / 65535; + // The title's float for 16-bit value u (its 1/65535 is 0x37800080). + let float = |u: u32| (u as f32 * f32::from_bits(0x3780_0080)).to_bits(); for (x, y) in [(0usize, 0usize), (5, 0), (63, 2), (17, 40), (63, 63)] { let k = (1 + x + 64 * y) as u32; // SAFETY: inside the mapped buffers. @@ -2336,15 +2459,22 @@ void main(uint3 id : SV_DispatchThreadID) { raw_data.add(f[1].Offset as usize + y * f[1].Footprint.RowPitch as usize + x).read(), ) }; - assert_eq!(word & 0xff_ffff, d24(k), "24-bit depth at {x},{y}"); + assert_eq!(word, float(k), "depth at {x},{y}"); assert_eq!(u32::from(byte), ((x ^ y) & 0xff) as u32); } + // Tested EQUAL against a point at the depth the title's tiled + // lighting gives value k (k times its 1/65535), as the console's + // 16-bit depth passes it for every k. In 24-bit depth on the RX 6700 + // XT only k = 258 of 1..=4096 passed. + let passed = equal_test_passes(depth, ©.texture); + let failed: Vec = (1..=4096).filter(|&k| !passed[k as usize - 1]).collect(); + assert!(failed.is_empty(), "EQUAL fails at {failed:?}"); // Rendered as depth (a clear of both planes), then used through // the unordered view: copied to the twin, converted back. list.reset(); crate::list::ensure_state(&list, depth, 0x10); let dsv = D3D12_DEPTH_STENCIL_VIEW_DESC { - Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_D24_UNORM_S8_UINT, + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_D32_FLOAT_S8X24_UINT, ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2D, ..Default::default() }; diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index dcc0ab1924..67ad4812ab 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -227,12 +227,17 @@ fn footprint(desc: &ResourceDesc) -> Option { } /// A format as the host has it. The console's 16-bit depth with stencil -/// (and its typeless views) has no PC format: the 24-bit ones stand in. +/// (and its typeless views) has no PC format: the 32-bit float ones stand +/// in, so that depth its shaders write through unordered views +/// (`crate::twin`) arrives as the very float a draw rasterises; copied into +/// 24-bit depth it never tested EQUAL against a draw on the RX 6700 XT. +/// shortcut: a depth bias on such a target counts in float steps, not +/// 1/65535; scale it if a title's 16-bit depth biased draws show acne. pub(crate) fn pc_format(format: u32) -> u32 { match format { - 118 => 45, - 119 => 46, - 120 => 47, + 118 => 20, + 119 => 21, + 120 => 22, other => other, } } diff --git a/crates/victory-gpu/src/twin.rs b/crates/victory-gpu/src/twin.rs index b3a17306c8..89554ec787 100644 --- a/crates/victory-gpu/src/twin.rs +++ b/crates/victory-gpu/src/twin.rs @@ -8,7 +8,7 @@ //! contents move between the two by copies where the use changes: within //! a list where it records the change (`HostList::transition`), and at //! submission for each list's first use, from the side the lists before it -//! left newer. A 16-bit depth plane in the host's 24-bit one (the +//! left newer. A 16-bit depth plane in the host's 32-bit float one (the //! console's 16-bit depth with stencil) is converted on the way, so a //! value written as 16-bit depth compares equal to the same depth //! rasterised. @@ -75,7 +75,7 @@ struct Route { /// Its place in the scratch buffer as the twin's texture has it. twin: D3D12_PLACED_SUBRESOURCE_FOOTPRINT, /// As the depth texture has it, where that differs: a 16-bit depth - /// plane the host keeps in 24 bits (32 per texel), converted. + /// plane the host keeps as 32-bit floats, converted. depth: Option, } @@ -453,24 +453,16 @@ fn uav_barrier() -> D3D12_RESOURCE_BARRIER { } } -/// 16-bit depth (unorm, two per dword) to the host's 24-bit depth plane (in -/// the low 24 bits of 32) and back, in the scratch buffer: `u * (2^24 - 1) -/// / 65535` rounded, exactly, and back to the 16-bit value whose 24-bit one -/// is nearest. +/// 16-bit depth (unorm, two per dword) to the host's 32-bit float depth +/// plane and back, in the scratch buffer: `u` becomes `u` times +/// `0x37800080` (the title's 1/65535; its tiled-lighting draws rasterise +/// that very float and test it EQUAL), and a float back the nearest `u`. const SOURCE: &str = r#" #define RS "RootConstants(num32BitConstants=8, b0), UAV(u0)" cbuffer C : register(b0) { uint width; uint height; uint pitch16; uint at16; uint pitch32; uint at32; uint toDepth; uint unused; }; RWByteAddressBuffer buf : register(u0); -uint d24(uint u) { return u * 256 + (u * 255 + 32767) / 65535; } -uint u16(uint d) { - d &= 0xffffff; - uint u = min(d >> 8, 65535); - uint best = u; - int err = abs((int)d24(u) - (int)d); - if (u > 0 && abs((int)d24(u - 1) - (int)d) < err) { best = u - 1; err = abs((int)d24(u - 1) - (int)d); } - if (u < 65535 && abs((int)d24(u + 1) - (int)d) < err) { best = u + 1; } - return best; -} +uint depth(uint u) { return asuint((float)u * asfloat(0x37800080)); } +uint u16(uint d) { return (uint)(saturate(asfloat(d)) * 65535.0 + 0.5); } [RootSignature(RS)] [numthreads(64, 1, 1)] void main(uint3 id : SV_DispatchThreadID) { @@ -482,8 +474,8 @@ void main(uint3 id : SV_DispatchThreadID) { bool two = x + 1 < width; if (toDepth != 0) { uint pair = buf.Load(a); - buf.Store(b, d24(pair & 0xffff)); - if (two) buf.Store(b + 4, d24(pair >> 16)); + buf.Store(b, depth(pair & 0xffff)); + if (two) buf.Store(b + 4, depth(pair >> 16)); } else { uint lo = u16(buf.Load(b)); uint hi = two ? u16(buf.Load(b + 4)) : 0; From 2d4aa5570fb646c941d17d2ab8d92ca883187074 Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 05:06:55 +0100 Subject: [PATCH 15/83] GPU: the snapshot pool keeps at most 512 MiB Snapshot buffers kept for reuse were capped at 2 GiB of private commit. Since shaders mark the pages they write (cd94d353), the cutscene snapshots 0.1-0.8 GB a frame over 26-45 submissions (run textures5: 402 MB a frame; mk2/mk3: 10-134 ms of snapshots), the largest single one the 174 MiB GPU-heap buffer; 512 MiB keeps two of those and frees up to 1.5 GiB of the process's commit (the title's world runs at 25.6-26.9 GB on a 32 GB machine). Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/shadow.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 74eedc94f4..6c74d82d74 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -86,7 +86,7 @@ fn give_back(v: Vec) { } /// Snapshot memory kept for reuse. -const POOL_BYTES: usize = 2 << 30; +const POOL_BYTES: usize = 512 << 20; // SAFETY: D3D12 resources are free-threaded; `data` is a persistent mapping // written only on the submitting thread. From 2a93ff0080fbd617232f9d788a5c1cb7874020b8 Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 05:06:53 +0100 Subject: [PATCH 16/83] GPU: our heap bytes and the process heaps in the memory line (diagnostics) The video-memory line also gives the bytes committed in every process heap (Rust code's and the title's C runtime's) and, through a counting global allocator the binary installs in diagnostics builds, the bytes Rust code holds: the 12.5 GB of plain private commit not yet attributed (run textures5). Co-Authored-By: Claude Opus 5.5 --- apps/victory/src/main.rs | 5 +++ crates/victory-gpu/src/copystat.rs | 65 ++++++++++++++++++++++++++++++ crates/victory-gpu/src/host.rs | 4 +- crates/victory-gpu/src/lib.rs | 2 + 4 files changed, 75 insertions(+), 1 deletion(-) diff --git a/apps/victory/src/main.rs b/apps/victory/src/main.rs index 5c8749f723..07f7591685 100644 --- a/apps/victory/src/main.rs +++ b/apps/victory/src/main.rs @@ -136,6 +136,11 @@ enum Console { SeriesS, } +/// Diagnostics: the heap bytes Rust code holds, for the statistics. +#[cfg(all(windows, feature = "diagnostics"))] +#[global_allocator] +static ALLOC: victory_gpu::CountingAlloc = victory_gpu::CountingAlloc; + fn main() -> Result<()> { victory_core::logging::init("info"); // The audio recorder `run` starts for `VICTORY_AUDIO_CAPTURE`. diff --git a/crates/victory-gpu/src/copystat.rs b/crates/victory-gpu/src/copystat.rs index f9d15c04da..40cfaa6eba 100644 --- a/crates/victory-gpu/src/copystat.rs +++ b/crates/victory-gpu/src/copystat.rs @@ -330,3 +330,68 @@ pub(crate) fn log(frames: f64) { ); } } + +/// A global allocator that counts the bytes Rust code holds (the +/// statistics' "our heap"; the binary installs it in diagnostics builds). +pub struct CountingAlloc; + +/// Bytes [`CountingAlloc`] has handed out and not taken back. +pub(crate) static HEAP_BYTES: AtomicU64 = AtomicU64::new(0); + +// SAFETY: every call goes to the system allocator unchanged; only counted. +unsafe impl std::alloc::GlobalAlloc for CountingAlloc { + unsafe fn alloc(&self, layout: std::alloc::Layout) -> *mut u8 { + // SAFETY: the caller's layout, passed on. + let p = unsafe { std::alloc::System.alloc(layout) }; + if !p.is_null() { + HEAP_BYTES.fetch_add(layout.size() as u64, Relaxed); + } + p + } + + unsafe fn alloc_zeroed(&self, layout: std::alloc::Layout) -> *mut u8 { + // SAFETY: as above. + let p = unsafe { std::alloc::System.alloc_zeroed(layout) }; + if !p.is_null() { + HEAP_BYTES.fetch_add(layout.size() as u64, Relaxed); + } + p + } + + unsafe fn dealloc(&self, p: *mut u8, layout: std::alloc::Layout) { + HEAP_BYTES.fetch_sub(layout.size() as u64, Relaxed); + // SAFETY: a block this allocator handed out with this layout. + unsafe { std::alloc::System.dealloc(p, layout) } + } + + unsafe fn realloc(&self, p: *mut u8, layout: std::alloc::Layout, size: usize) -> *mut u8 { + // SAFETY: as above. + let q = unsafe { std::alloc::System.realloc(p, layout, size) }; + if !q.is_null() { + HEAP_BYTES.fetch_sub(layout.size() as u64, Relaxed); + HEAP_BYTES.fetch_add(size as u64, Relaxed); + } + q + } +} + +/// Bytes committed in every heap of the process (ours and the title's C +/// runtime share the process heap). +pub(crate) fn heaps_committed() -> u64 { + use windows_sys::Win32::System::Memory::{GetProcessHeaps, HEAP_SUMMARY, HeapSummary}; + let mut heaps = vec![std::ptr::null_mut(); 256]; + // SAFETY: a buffer of that many handles. + let n = unsafe { GetProcessHeaps(heaps.len() as u32, heaps.as_mut_ptr()) } as usize; + heaps.truncate(n.min(heaps.len())); + heaps + .iter() + .map(|&h| { + let mut s = HEAP_SUMMARY { + cb: size_of::() as u32, + ..Default::default() + }; + // SAFETY: a live heap handle and a sized structure. + if unsafe { HeapSummary(h, 0, &mut s) } != 0 { s.cbCommitted as u64 } else { 0 } + }) + .sum() +} diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 8156d8b8c3..b675e24f20 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -2522,9 +2522,11 @@ impl Meter { tracing::info!( "video memory: {local:.0} MB of a {budget:.0} MB budget on the card, \ {system:.0} MB of {system_budget:.0} MB in system memory; process commit {:.0} MB, \ - working set {:.0} MB; texture staging {:.0} MB; placed textures made {:.0} MB", + working set {:.0} MB; process heaps {:.0} MB (Rust {:.0} MB); texture staging {:.0} MB; placed textures made {:.0} MB", commit as f64 / 1e6, working_set as f64 / 1e6, + crate::copystat::heaps_committed() as f64 / 1e6, + crate::copystat::HEAP_BYTES.load(Ordering::Relaxed) as f64 / 1e6, crate::texture::STAGING_BYTES.load(Ordering::Relaxed) as f64 / 1e6, crate::resource::PLACED_BYTES.load(Ordering::Relaxed) as f64 / 1e6, ); diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index a392bd369a..fc1c958bd0 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -64,6 +64,8 @@ mod twin; #[cfg(windows)] mod watch; +#[cfg(all(windows, feature = "diagnostics"))] +pub use copystat::CountingAlloc; #[cfg(windows)] pub use host::on_failure; #[cfg(windows)] From 280b1505891bad72dffd5dcbd0c5dff59dd333d7 Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 05:18:49 +0100 Subject: [PATCH 17/83] GPU: change tracking guards only the runtime's memory, region by region `watch::track` decided from a range's first page whether the whole range was the runtime's GPU memory. Memory outside title buffers gets a host copy of its 4 MiB-aligned window (`shadow::loose`); a window whose first page was free memory was tracked whole, and taking it guarded (made read-only) every committed page in it, other allocations' too. In the crate's tests a constant view of a heap block did that to the process heap: threads faulted inside RtlFreeHeap/RtlAllocateHeap while holding the heap lock and waited in the guard handler for the guard lock, whose holder (a take in another test's submission) waited for the heap lock. The suite hung about one run in two on a branch that added such a test (stacks of two hung runs; the reading of who held which lock is inferred from them). The decision is now made for every region the range covers: write-watched pool memory, or with views anything but plain committed memory and images, as before for the first page. A 64 KiB page touching any other memory is not tracked: never guarded, and copied whole at each use, as a copy of memory with no tracker always was (such a copy is never clean). One write-watch query still answers the common case (the range in one pool) without `VirtualQuery`, which costs milliseconds in the runtime's big pools; the region walk runs once, when a copy is made. In boot-to-world runs no memory was copied whole (perf2, perf3, mk3: 0.0 MB in every window), so this is about robustness. Tests: a window from free memory over a plain allocation into a pool guards the pool only; a title buffer over a pool and a plain allocation copies the plain part at each use, its bytes and their later change, and leaves it writable. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/shadow.rs | 78 +++++++++++++++- crates/victory-gpu/src/watch.rs | 150 ++++++++++++++++++++++++++----- 2 files changed, 203 insertions(+), 25 deletions(-) diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 6c74d82d74..ab6a258e43 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -576,7 +576,19 @@ impl Shadow { #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::WatchUs, started.elapsed().as_micros() as u64); // Cut to the range: next to it shaders may be writing the copy. - let copied: usize = runs.into_iter().map(|(a, b)| self.copy(a, b)).sum(); + let mut copied: usize = runs.into_iter().map(|(a, b)| self.copy(a, b)).sum(); + // Parts on memory that is not the runtime's: whole, as below. + for (a, b) in t.untracked(from, to) { + #[cfg(feature = "diagnostics")] + let started = std::time::Instant::now(); + copied += self.copy(a, b); + #[cfg(feature = "diagnostics")] + { + use crate::copystat::{C, add}; + add(C::WholeBytes, (b - a) as u64); + add(C::WholeUs, started.elapsed().as_micros() as u64); + } + } #[cfg(feature = "diagnostics")] { use crate::copystat::{C, add}; @@ -1066,6 +1078,70 @@ mod tests { unregister(p, p as u64); } + /// A title buffer over a pool and, after it, a plain allocation (memory + /// that is not the runtime's): the pool is tracked and guarded; the + /// plain allocation's bytes are copied at each use and never guarded, + /// so a value the title keeps there reaches the copy, and again after + /// the title changes it. + #[test] + fn bytes_off_the_runtimes_memory_are_copied_at_each_use() { + use crate::watch::tests::{MEM_WRITE_WATCH, free}; + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, MEMORY_BASIC_INFORMATION, PAGE_READONLY, PAGE_READWRITE, + VirtualAlloc, VirtualFree, VirtualQuery, + }; + // A pool page and a plain one right after it, in two pages found free + // (other tests allocate meanwhile: tried again if taken). + let (pool, plain) = (0..8) + .find_map(|_| { + // SAFETY: a fresh reservation, released at once; then + // allocations where it was, freed below. + unsafe { + let p = VirtualAlloc(std::ptr::null(), 2 * PAGE, MEM_RESERVE, PAGE_READWRITE) as usize; + VirtualFree(p as *mut _, 0, MEM_RELEASE); + let at = |q: usize, kind: u32| { + VirtualAlloc(q as *const _, PAGE, MEM_RESERVE | MEM_COMMIT | kind, PAGE_READWRITE) as usize + }; + let (pool, plain) = (at(p, MEM_WRITE_WATCH), at(p + PAGE, 0)); + if p != 0 && pool == p && plain == p + PAGE { + return Some((pool, plain)); + } + [pool, plain].into_iter().filter(|&q| q != 0).for_each(free); + None + } + }) + .expect("two free pages"); + let len = 2 * PAGE; + register(pool, pool as u64, len as u64); + let Some(copy) = find(pool as u64, len as u64) else { + unregister(pool, pool as u64); + [pool, plain].into_iter().for_each(free); + return; // no host GPU here + }; + let word = (plain + 64) as *mut u32; + let protection = |p: usize| { + // SAFETY: plain data filled in by the query. + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + unsafe { VirtualQuery(p as *const _, &mut info, size_of_val(&info)) }; + info.Protect + }; + // SAFETY: a word of our plain allocation. + unsafe { word.write_volatile(0x1234) }; + copy.update(pool, len); + assert_eq!(copy.read_host(word as u64, 1), [0x1234]); + assert!(!copy.clean(), "never clean: part of it is not tracked"); + // SAFETY: as above. + unsafe { word.write_volatile(0x5678) }; + copy.update(pool, len); + assert_eq!(copy.read_host(word as u64, 1), [0x5678], "the title's change reaches the copy"); + assert_eq!(protection(pool), PAGE_READONLY, "the pool is guarded"); + assert_eq!(protection(plain), PAGE_READWRITE, "the plain allocation is not"); + unregister(pool, pool as u64); + // The pages stay allocated (as the other tests' pools): a copy some + // page table still holds must not name memory reused meanwhile. + } + /// Ranges shaders write far apart are kept apart (not the copy between /// them); what the GPU wrote goes back once, whichever overlapping /// ranges declared it, and nothing else does. diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 24052d9246..0e029d8fab 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -85,6 +85,9 @@ pub(crate) struct Tracked { start: usize, end: usize, changed: Arc, + /// Parts of the range on pages that are not the runtime's memory (in + /// order): not tracked, copied whole at each use ([`Tracked::untracked`]). + untracked: Vec<(usize, usize)>, } struct Guards { @@ -209,46 +212,87 @@ fn guard_aliases(g: &mut Guards, pairs: &[(usize, usize)]) { /// written through other views showing the same pages: the title fills /// streamed textures and video planes through a pool view and maps the /// pages into its tiled heap, where a guard sees none of it). +/// +/// Only the pages of the range that are such memory are tracked; the rest is +/// never guarded and is copied whole at each use, as memory with no tracker. pub(crate) fn track(start: usize, len: usize, views: bool) -> Option { - if len == 0 || !runtime_memory(start, views) { + if len == 0 { return None; } - install(); let end = start + len; - let pages = start / PAGE..end.div_ceil(PAGE); - let changed = Arc::new(Changed(Mutex::new(pages.clone().collect()), Mutex::default(), AtomicBool::new(true))); + let pages = runtime_pages(start, end, views); + if pages.is_empty() { + return None; + } + install(); + let changed = Arc::new(Changed(Mutex::new(pages.iter().copied().collect()), Mutex::default(), AtomicBool::new(true))); let mut g = guards(); - for page in pages { + for &page in &pages { g.holders.entry(page).or_default().push(changed.clone()); } + // The rest of the range, as byte runs. + let mut untracked: Vec<(usize, usize)> = Vec::new(); + let mut at = start; + for &page in pages.iter().chain([&usize::MAX]) { + let (a, b) = ((page.saturating_mul(PAGE)).max(start).min(end), (page.saturating_add(1).saturating_mul(PAGE)).min(end)); + if at < a { + untracked.push((at, a)); + } + at = at.max(b); + } Some(Tracked { start, end, changed, + untracked, }) } -/// Whether memory at `at` is the runtime's GPU memory: a write-watched -/// pool, or (with `views`) a view or a placeholder (anything but plain -/// committed memory). -fn runtime_memory(at: usize, views: bool) -> bool { +/// The pages of `[start, end)` that are the runtime's GPU memory: a +/// write-watched pool, or (with `views`) anything but plain committed memory +/// and images (views, placeholders, nothing mapped yet). Decided for every +/// region the range covers, and a page touching any other memory is left +/// out: a range can run past its allocation (a 4 MiB window of memory +/// outside buffers, `crate::shadow`), and when the first page alone decided, +/// a window starting in free memory had the process heap's pages after it +/// guarded; the heap's own code then faulted while holding its lock, and the +/// guard handler waited for the guard lock, whose holder waited for the heap +/// lock (the crate's tests hung). +/// +/// shortcut: memory free or reserved when the range is tracked counts as the +/// runtime's; another allocator committing it before the first take would +/// have it guarded. +fn runtime_pages(start: usize, end: usize, views: bool) -> Vec { use windows_sys::Win32::System::Memory::{ - GetWriteWatch, MEM_COMMIT, MEM_PRIVATE, MEMORY_BASIC_INFORMATION, VirtualQuery, + GetWriteWatch, MEM_COMMIT, MEM_IMAGE, MEM_PRIVATE, MEMORY_BASIC_INFORMATION, VirtualQuery, }; - let page = at & !(4096 - 1); - let (mut found, mut count, mut granularity) = (0usize, 1usize, 0u32); - // SAFETY: room for one answer; no reset, so nothing changes. - let watched = unsafe { - GetWriteWatch(0, page as *const _, 4096, (&raw mut found).cast(), &mut count, &mut granularity) - } == 0; - if watched || !views { - return watched; + let watched = |at: usize, len: usize| { + let (mut found, mut count, mut granularity) = (0usize, 1usize, 0u32); + // SAFETY: room for one answer; no reset, so nothing changes. + unsafe { GetWriteWatch(0, at as *const _, len, (&raw mut found).cast(), &mut count, &mut granularity) == 0 } + }; + let (first, last) = (start / PAGE, end.div_ceil(PAGE)); + // One pool holds it all (the common case; asking `VirtualQuery` costs + // milliseconds in the runtime's big pools). + if watched(start & !(4096 - 1), end - (start & !(4096 - 1))) { + return (first..last).collect(); + } + let (mut runtime, mut other) = (std::collections::BTreeSet::new(), std::collections::BTreeSet::new()); + let mut at = start & !(4096 - 1); + while at < end { + // SAFETY: plain data filled in by the query. + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + if unsafe { VirtualQuery(at as *const _, &mut info, size_of_val(&info)) } == 0 { + break; + } + let next = (info.BaseAddress as usize + info.RegionSize).max(at + 1).min(end); + let ours = watched(at, next - at) + || views && info.Type != MEM_IMAGE && !(info.State == MEM_COMMIT && info.Type == MEM_PRIVATE); + (if ours { &mut runtime } else { &mut other }).extend(at / PAGE..next.div_ceil(PAGE)); + at = next; } - // SAFETY: plain data filled in by the query. - let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; - // SAFETY: a valid out pointer of the right size. - let n = unsafe { VirtualQuery(page as *const _, &mut info, size_of_val(&info)) }; - n != 0 && !(info.State == MEM_COMMIT && info.Type == MEM_PRIVATE) + runtime.difference(&other).copied().collect() } impl Drop for Tracked { @@ -371,7 +415,17 @@ impl Tracked { /// finds nothing, and asking costs no lock. A write racing this answer /// is found by the next asking, as one racing a take. pub(crate) fn clean(&self) -> bool { - !self.changed.2.load(Ordering::Acquire) + self.untracked.is_empty() && !self.changed.2.load(Ordering::Acquire) + } + + /// The parts of `[from, to)` that are not tracked (see + /// [`Tracked::untracked`] field): to be copied whole at each use. + pub(crate) fn untracked(&self, from: usize, to: usize) -> Vec<(usize, usize)> { + self.untracked + .iter() + .map(|&(a, b)| (a.max(from), b.min(to))) + .filter(|&(a, b)| a < b) + .collect() } /// Shaders may write the copy's bytes `[from, to)` until [`Tracked::disarm`]: @@ -729,6 +783,54 @@ pub(crate) mod tests { free(p); } + /// A range running from free memory over another allocation into a pool + /// (a 4 MiB window of memory outside buffers) tracks the pool's pages + /// and leaves the other allocation alone: taking guards the pool only. + #[test] + fn a_range_over_foreign_memory_guards_only_the_runtimes() { + use windows_sys::Win32::System::Memory::{MEMORY_BASIC_INFORMATION, PAGE_READONLY, VirtualQuery}; + const WINDOW: usize = 4 << 20; + // In a free 4 MiB-aligned window: plain committed memory (as the + // process heap's) 1 MiB in, a pool 2 MiB in. Other tests allocate + // meanwhile, so a window taken under our feet is tried again. + let (base, foreign, pool) = (0..8) + .find_map(|_| { + // SAFETY: a fresh reservation, released at once; then + // allocations in the window it left free, freed below. + unsafe { + let p = VirtualAlloc(std::ptr::null(), 2 * WINDOW, MEM_RESERVE, PAGE_READWRITE) as usize; + VirtualFree(p as *mut _, 0, MEM_RELEASE); + let base = p.next_multiple_of(WINDOW); + let at = |offset: usize, kind: u32| { + VirtualAlloc((base + offset) as *const _, PAGE, MEM_RESERVE | MEM_COMMIT | kind, PAGE_READWRITE) as usize + }; + let (foreign, pool) = (at(1 << 20, 0), at(2 << 20, MEM_WRITE_WATCH)); + if p != 0 && foreign == base + (1 << 20) && pool == base + (2 << 20) { + return Some((base, foreign, pool)); + } + [foreign, pool].into_iter().filter(|&q| q != 0).for_each(free); + None + } + }) + .expect("a free window"); + let t = track(base, WINDOW, true).expect("the pool is tracked"); + let taken = t.take(base, base + WINDOW); + assert!(taken.iter().any(|&(a, b)| a <= pool && pool + PAGE <= b), "{taken:x?}"); + assert!(!taken.iter().any(|&(a, b)| a < foreign + PAGE && foreign < b), "{taken:x?}"); + let protection = |p: usize| { + // SAFETY: plain data filled in by the query. + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + unsafe { VirtualQuery(p as *const _, &mut info, size_of_val(&info)) }; + info.Protect + }; + assert_eq!(protection(pool), PAGE_READONLY, "the pool is guarded"); + assert_eq!(protection(foreign), PAGE_READWRITE, "the other allocation is not"); + drop(t); + free(foreign); + free(pool); + } + /// A page only partly in the range asked is copied in part and stays /// changed; edge pages count whole when the tracked part is covered. #[test] From f8095210ee84326ecbba3c5d9384ead0e8ff3b4b Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 05:03:35 +0100 Subject: [PATCH 18/83] GPU: a heap sync looks at a page's slots under one lock and makes only the changed ones Each submission's heap sync (descriptors the title copies into its heaps as bytes) mirrored every slot of every heap page written since the last sync: ~700,000 slots a frame in the intro cutscene (run perf3), two lock takings and a view clone each, 76 ms a frame after the placed-texture fix (113 ms before it, run perf2). `HostHeap::sync_slots` reads a page's records, asks the view registry once whether each names a current view, compares them with what the slots hold under one lock, and calls `mirror` only for slots whose record differs from what the slot holds: the decisions `mirror` makes for the others are to do nothing, so the result is the same. Test: a record copied as bytes and a record cleared are made at the next sync, the others passed by. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor.rs | 16 ++++-- crates/victory-gpu/src/descriptor/host.rs | 61 ++++++++++++++++++++++- 2 files changed, 73 insertions(+), 4 deletions(-) diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 8ba5cb7588..63e3dbe20c 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -186,9 +186,7 @@ pub(crate) fn sync_heaps() { crate::copystat::C::SyncSlots, last.min(u64::from(heap.desc.count)).saturating_sub(first), ); - for index in first..last.min(u64::from(heap.desc.count)) { - host.mirror(index as u32, start + index * step, false); - } + host.sync_slots(first as u32, last.min(u64::from(heap.desc.count)) as u32, start, step); } } } @@ -455,6 +453,18 @@ fn view_at(i: u32, generation: u32) -> Option { (*current == generation).then(|| view.clone()) } +/// For each record (tag, index, generation): whether it names a view that +/// is current, as [`view_at`] would find it (one lock for them all). +fn views_current(records: &[[u32; 3]]) -> Vec { + let views = VIEWS.lock().unwrap_or_else(|e| e.into_inner()); + records + .iter() + .map(|&[tag, i, generation]| { + tag == VIEW_TAG && views.list.get(i as usize).is_some_and(|(_, current)| *current == generation) + }) + .collect() +} + /// The view recorded at `handle`, if one is (and its resource is alive). pub(crate) fn view(handle: u64) -> Option { if handle == 0 { diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index dd41940623..0a816f4bab 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -10,7 +10,7 @@ use std::sync::Mutex; use windows::Win32::Graphics::Direct3D12::*; use windows::Win32::Graphics::Dxgi::Common::*; -use super::{VIEW_TAG, View, view_at}; +use super::{VIEW_TAG, View, view_at, views_current}; use crate::host::host; pub(crate) struct HostHeap { @@ -627,6 +627,34 @@ impl HostHeap { } } + /// A heap sync of slots `first..last`, whose records are at `start` + + /// index × `step`: [`HostHeap::mirror`] of each slot whose record + /// differs from what the slot holds, the rest passed by as `mirror` + /// would, with one lock of each kind for them all instead of two per slot + /// (a world frame looks at ~700,000 slots, run perf3: ~75 ms). + pub(crate) fn sync_slots(&self, first: u32, last: u32, start: u64, step: u64) { + let at = |i: u32| start + u64::from(i) * step; + // SAFETY: records in title heap memory the caller found mapped. + let records: Vec<[u32; 3]> = + (first..last).map(|i| unsafe { (at(i) as *const [u32; 3]).read_unaligned() }).collect(); + let current = views_current(&records); + let stale: Vec = { + let made = self.made.lock().unwrap_or_else(|e| e.into_inner()); + (first..last) + .zip(records.iter().zip(current)) + .filter(|&(i, (&[_, view, generation], current))| match made.get(i as usize) { + Some(&m) if current => m != u64::from(generation) << 32 | u64::from(view), + Some(&m) => m != 0, + None => true, + }) + .map(|(i, _)| i) + .collect() + }; + for i in stale { + self.mirror(i, at(i), false); + } + } + /// Makes host slot `index` from the record the title has at `handle` /// if it changed since, and returns the view recorded there. Buffer /// views are made only for draws (`for_draw`), which also copy their @@ -1476,6 +1504,37 @@ mod tests { assert!(host.kept(0), "made for the draw"); } + /// A heap sync makes the slots whose records the title changed as bytes + /// (a copy of another slot's record, a record cleared) and passes the + /// others by. + #[test] + fn heap_syncs_make_the_slots_whose_records_changed() { + if host().is_none() { + return; // no host GPU here + } + let null = std::ptr::null(); + let heap_desc: [u32; 8] = [0, 4, 1, 0, 0, 0, 0, 0]; + let mut heap = null; + let iid = crate::object::guid(0x8efb471d, 0x616c, 0x4f49, [0x90, 0xf7, 0x12, 0x7b, 0xb7, 0x63, 0xfa, 0x51]); + assert_eq!(crate::descriptor::create_heap(null, heap_desc.as_ptr().cast(), &iid, &mut heap), 0); + let title_heap = crate::descriptor::heap(heap); + let start = title_heap.start; + // A view of no memory: a view of the test's own heap memory would get + // a host copy whose 4 MiB window the guards may cover (the process + // heap guarded read-only hung the suite). + crate::descriptor::create_cbv(null, &[0, 0, 256, 0], start); + let host = title_heap.host().expect("a host view heap"); + // SAFETY: slots 0 and 1 of the heap's memory, 32 bytes each. + unsafe { std::ptr::copy_nonoverlapping(start as *const u8, (start + 32) as *mut u8, 32) }; + assert!(!host.made(1), "copied as bytes: not seen yet"); + host.sync_slots(0, 4, start, 32); + assert!(host.made(0) && host.made(1) && !host.made(2)); + // SAFETY: as above. + unsafe { std::ptr::write_bytes((start + 32) as *mut u8, 0, 32) }; + host.sync_slots(0, 4, start, 32); + assert!(host.made(0) && !host.made(1), "a cleared record leaves its slot"); + } + /// The world's 16-byte view of 0 elements removed the device. #[test] fn empty_and_overlong_buffer_views_are_refused() { From cc0e153b427730ce2a76c3e32dd6d327f2cad98e Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 05:03:36 +0100 Subject: [PATCH 19/83] GPU: change trackers keep their "written since taken" flag in one dense bitmap The flag from 19533398 let a submission skip host copies the title had not written, but reading it still touched each copy (copy, tracker, flag: a cache miss or more each) and the heap step cloned its ~9,000 merged ranges first: the heap and page-table steps still took 25-41 and 16-26 ms a frame (run perf3) to find the few written copies among ~14,000. Each tracker now owns a bit in a static bitmap (set and cleared under its lock as before, read without one; given back when the tracker goes). The heap's merged ranges and the page table's copy list keep each copy's bit beside it, and both steps read the bits, walk their lists in place and pass only written copies to the batch. Test: a new tracker starts dirty, a taken one reads clean, a tracker with no bit is never clean. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/bindless.rs | 46 ++++++++------ crates/victory-gpu/src/memory.rs | 17 +++-- crates/victory-gpu/src/shadow.rs | 6 ++ crates/victory-gpu/src/watch.rs | 99 ++++++++++++++++++++++++++---- 4 files changed, 133 insertions(+), 35 deletions(-) diff --git a/crates/victory-gpu/src/bindless.rs b/crates/victory-gpu/src/bindless.rs index f50fcda243..a85c4a7977 100644 --- a/crates/victory-gpu/src/bindless.rs +++ b/crates/victory-gpu/src/bindless.rs @@ -44,8 +44,9 @@ pub(crate) struct Viewed { type Range = (usize, u64, u64, bool); -/// A merged range: copy, start, bytes, unordered access. -type Hull = (Arc, u64, u64, bool); +/// A merged range: copy, start, bytes, unordered access, the copy's bit in +/// the change tracker (`crate::watch::clean_bit`). +type Hull = (Arc, u64, u64, bool, Option); #[derive(Default)] struct Inner { @@ -131,21 +132,24 @@ impl Viewed { /// The buffer ranges views reach, merged per host copy and kind /// (shader resource, unordered access): copy, start, bytes. + #[cfg(any(test, feature = "diagnostics"))] fn ranges(&self) -> Vec { - let mut inner = self.inner.lock().unwrap_or_else(|e| e.into_inner()); - if let Some(hulls) = &inner.hulls { - return hulls.clone(); - } - let hulls: Vec = inner - .ends - .iter() - .filter_map(|(&(_, uav), (shadow, starts, ends))| { - let (&from, &to) = (starts.keys().next()?, ends.keys().next_back()?); - Some((shadow.clone(), from, to - from, uav)) - }) - .collect(); - inner.hulls = Some(hulls.clone()); - hulls + self.inner.lock().unwrap_or_else(|e| e.into_inner()).hulls().clone() + } +} + +impl Inner { + /// [`Viewed::ranges`], made once while no range comes or goes. + fn hulls(&mut self) -> &Vec { + let Inner { hulls, ends, .. } = self; + hulls.get_or_insert_with(|| { + ends.iter() + .filter_map(|(&(_, uav), (shadow, starts, ends))| { + let (&from, &to) = (starts.keys().next()?, ends.keys().next_back()?); + Some((shadow.clone(), from, to - from, uav, shadow.dirty_bit())) + }) + .collect() + }) } } @@ -256,9 +260,15 @@ impl Uploads { /// there. Copying back the whole unordered ranges after every submission /// (about 1 GB of them in the world) cost seconds per frame; the upgrade /// is shaders marking the pages they write (as `crate::memory` does). +/// +/// Copies the title has not written since they took it are passed by: a +/// world submission's heaps reach ~9,000 copies, a few of them written. pub(crate) fn refresh(viewed: &Viewed, mut add: impl FnMut(&Arc, usize, usize)) { - for (shadow, address, len, _) in viewed.ranges() { - add(&shadow, address as usize, len as usize); + let mut inner = viewed.inner.lock().unwrap_or_else(|e| e.into_inner()); + for (shadow, address, len, _, bit) in inner.hulls() { + if !crate::watch::clean_bit(*bit) { + add(shadow, *address as usize, *len as usize); + } } } diff --git a/crates/victory-gpu/src/memory.rs b/crates/victory-gpu/src/memory.rs index 8700ca4e93..5f65d58076 100644 --- a/crates/victory-gpu/src/memory.rs +++ b/crates/victory-gpu/src/memory.rs @@ -84,6 +84,8 @@ impl Map { #[derive(Default)] struct Layout { copies: Vec>, + /// Each copy's bit in the change tracker (`crate::watch::clean_bit`). + bits: Vec>, blocks: Vec, owner: Vec>, } @@ -313,6 +315,7 @@ impl Shared { unsafe { std::ptr::copy_nonoverlapping(dwords.as_ptr(), self.data as *mut u32, dwords.len()) }; tracing::debug!(copies = ranges.len(), blocks = blocks.len() - 1, "title memory page table"); self.layout = Arc::new(Layout { + bits: named.iter().map(|c| c.dirty_bit()).collect(), copies: named, blocks, owner, @@ -348,9 +351,15 @@ pub(crate) fn prepare(key: usize, mut add: impl FnMut(&Arc, usize, usize Some(s.layout.clone()) }) .flatten(); - for c in layout.iter().flat_map(|l| &l.copies) { - let (start, len) = c.range(); - add(c, start as usize, len as usize); + // Copies the title has not written since they took it are passed by + // without touching them (the table names every copy, ~4,700 in the world). + for l in layout.iter() { + for (c, bit) in l.copies.iter().zip(&l.bits) { + if !crate::watch::clean_bit(*bit) { + let (start, len) = c.range(); + add(c, start as usize, len as usize); + } + } } } @@ -400,7 +409,7 @@ pub(crate) fn bind(list: &HostList, key: usize) -> Option { }) }); list.defer_after(move || { - let Layout { copies, blocks, owner } = &*layout(key); + let Layout { copies, blocks, owner, .. } = &*layout(key); let precise = byte_for_byte.lock().unwrap_or_else(|e| e.into_inner()); // SAFETY: the bitmap is mapped and the list's run is over. let marks = unsafe { std::slice::from_raw_parts_mut(data as *mut u32, words) }; diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index ab6a258e43..ed7808f633 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -485,6 +485,12 @@ impl Shadow { self.tracked.as_ref().is_some_and(crate::watch::Tracked::clean) } + /// Its tracker's bit: `crate::watch::clean_bit` of it is + /// [`Shadow::clean`] (none for memory that is not tracked: never clean). + pub(crate) fn dirty_bit(&self) -> Option { + self.tracked.as_ref().and_then(crate::watch::Tracked::bit) + } + /// At submission: copies what changed of `[address, address + len)` /// since it was last copied (all of it if the memory is not /// write-watched). Returns the bytes copied. diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 0e029d8fab..c2d50ee78b 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -35,7 +35,7 @@ //! and allocated again while a tracker holds it is not seen. use std::collections::{BTreeMap, BTreeSet}; -use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex}; /// The unit tracked and copied: 64 KiB, the console's page. Finer units @@ -44,9 +44,56 @@ use std::sync::{Arc, Mutex}; pub(crate) const PAGE: usize = 64 << 10; /// The pages a tracker has not taken since they changed, what it saves of -/// pages it armed, and whether the first holds any (set and cleared under -/// its lock, read without: [`Tracked::clean`]). -struct Changed(Mutex>, Mutex, AtomicBool); +/// pages it armed, and its bit in [`DIRTY`] (none: always taken as dirty). +struct Changed(Mutex>, Mutex, Option); + +/// A bit per tracker, set while it holds changed pages: set and cleared +/// under the tracker's lock, read without one ([`Tracked::clean`]). Dense, +/// so that a submission asking about every copy its heaps reach (~14,000) +/// reads a few KB instead of a cache line per copy. +static DIRTY: [AtomicU64; DIRTY_WORDS] = [const { AtomicU64::new(0) }; DIRTY_WORDS]; +const DIRTY_WORDS: usize = 1 << 14; + +/// Bits of [`DIRTY`] given back, and the first never handed out. +static FREE_BITS: Mutex<(Vec, u32)> = Mutex::new((Vec::new(), 0)); + +fn dirty_bit() -> Option { + let mut free = FREE_BITS.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(bit) = free.0.pop() { + return Some(bit); + } + let bit = free.1; + (bit < (DIRTY_WORDS * 64) as u32).then(|| { + free.1 += 1; + bit + }) +} + +fn set_dirty(bit: Option, dirty: bool) { + if let Some(bit) = bit { + let (word, mask) = (&DIRTY[bit as usize / 64], 1u64 << (bit % 64)); + if dirty { + word.fetch_or(mask, Ordering::Release); + } else { + word.fetch_and(!mask, Ordering::Release); + } + } +} + +/// Whether the tracker with bit `bit` holds no changed page (see +/// [`Tracked::clean`]). +pub(crate) fn clean_bit(bit: Option) -> bool { + bit.is_some_and(|bit| DIRTY[bit as usize / 64].load(Ordering::Acquire) & 1 << (bit % 64) == 0) +} + +impl Drop for Changed { + fn drop(&mut self) { + if let Some(bit) = self.2 { + set_dirty(Some(bit), false); + FREE_BITS.lock().unwrap_or_else(|e| e.into_inner()).0.push(bit); + } + } +} /// Pages (page numbers) whose bytes a tracker keeps when they are first /// written after it took them, and those bytes: while shaders may be @@ -225,11 +272,6 @@ pub(crate) fn track(start: usize, len: usize, views: bool) -> Option { return None; } install(); - let changed = Arc::new(Changed(Mutex::new(pages.iter().copied().collect()), Mutex::default(), AtomicBool::new(true))); - let mut g = guards(); - for &page in &pages { - g.holders.entry(page).or_default().push(changed.clone()); - } // The rest of the range, as byte runs. let mut untracked: Vec<(usize, usize)> = Vec::new(); let mut at = start; @@ -240,6 +282,15 @@ pub(crate) fn track(start: usize, len: usize, views: bool) -> Option { } at = at.max(b); } + // A tracker with untracked parts is never clean: no bit. + let bit = if untracked.is_empty() { dirty_bit() } else { None }; + set_dirty(bit, true); + let changed = Arc::new(Changed(Mutex::new(pages.iter().copied().collect()), Mutex::default(), bit)); + let mut g = guards(); + for &page in &pages { + g.holders.entry(page).or_default().push(changed.clone()); + } + drop(g); Some(Tracked { start, end, @@ -374,7 +425,7 @@ impl Tracked { changed.remove(&page); self.changed.taken(page); } - self.changed.2.store(!changed.is_empty(), Ordering::Release); + set_dirty(self.changed.2, !changed.is_empty()); drop(changed); drop(g); let mut runs: Vec<(usize, usize)> = Vec::new(); @@ -408,14 +459,20 @@ impl Tracked { changed.remove(&page); self.changed.taken(page); } - self.changed.2.store(!changed.is_empty(), Ordering::Release); + set_dirty(self.changed.2, !changed.is_empty()); } /// Whether no page changed since it was taken: then [`Tracked::take`] /// finds nothing, and asking costs no lock. A write racing this answer /// is found by the next asking, as one racing a take. pub(crate) fn clean(&self) -> bool { - self.untracked.is_empty() && !self.changed.2.load(Ordering::Acquire) + clean_bit(self.changed.2) + } + + /// The tracker's bit for [`clean_bit`], for callers that ask about + /// many trackers at once without touching each (none: never clean). + pub(crate) fn bit(&self) -> Option { + self.changed.2 } /// The parts of `[from, to)` that are not tracked (see @@ -549,7 +606,7 @@ fn changed_here(g: &mut Guards, first: usize, last: usize, save: bool) -> bool { for c in holders { let first_write = { let mut set = c.0.lock().unwrap_or_else(|e| e.into_inner()); - c.2.store(true, Ordering::Release); + set_dirty(c.2, true); set.insert(page) }; if first_write && save { @@ -831,6 +888,22 @@ pub(crate) mod tests { free(pool); } + /// A tracker's dirty bit goes back when it goes, and the next tracker + /// starts dirty on it (everything changed at first). + #[test] + fn a_new_tracker_starts_dirty_on_a_bit_given_back() { + let p = pool(1); + let a = track(p, PAGE, true).expect("tracked"); + assert_eq!(a.take(p, p + PAGE).len(), 1); + assert!(a.clean() && clean_bit(a.bit())); + drop(a); + let b = track(p, PAGE, true).expect("tracked"); + assert!(!b.clean() && !clean_bit(b.bit())); + assert!(!clean_bit(None), "no bit: never clean"); + drop(b); + free(p); + } + /// A page only partly in the range asked is copied in part and stays /// changed; edge pages count whole when the tracked part is covered. #[test] From ed887f24f0bfc6e6d77c9c4b8b674a13a58e6b52 Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 05:03:36 +0100 Subject: [PATCH 20/83] GPU: diagnostics: copies redone piece by piece are timed; GPU timing keys keep the pipeline * copystat: time spent in copies that met an unmapped page and were redone by 64 KiB and 4 KiB pieces (10-22 MB of unmapped memory a frame in run perf3, thousands of failing kernel reads, not counted before). * `VICTORY_GPU_TIMING`'s per-pipeline table dropped every word starting with a digit, so pipeline hashes starting with one vanished from its keys; the key is now the command's kind and the pipeline's name. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/copystat.rs | 7 +++++-- crates/victory-gpu/src/host.rs | 14 +++++++++----- 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/crates/victory-gpu/src/copystat.rs b/crates/victory-gpu/src/copystat.rs index 40cfaa6eba..34348407e7 100644 --- a/crates/victory-gpu/src/copystat.rs +++ b/crates/victory-gpu/src/copystat.rs @@ -99,8 +99,10 @@ pub(crate) enum C { SyncHeapsUs, /// Of those: heap slots looked at (every slot of each page written). SyncSlots, + /// Time in copies redone piece by piece after meeting an unmapped page. + FallbackUs, } -const COUNTERS: usize = 59; +const COUNTERS: usize = 60; static COUNT: [AtomicU64; COUNTERS] = [const { AtomicU64::new(0) }; COUNTERS]; pub(crate) fn add(c: C, n: u64) { @@ -222,7 +224,7 @@ pub(crate) fn log(frames: f64) { "copies per frame: {:.1} submissions; {:.0} title copies {:.1} MB; {:.0} refreshes {:.1} MB, \ {:.0} skipped {:.1} MB; {:.0} runs {:.1} ms; {:.0} queries {:.2} ms, moves {:.2} ms, \ {:.2} MB unmapped; {:.0} page faults; {:.0} watches {:.2} ms, {:.1} MB checked, {:.1} MB \ - unchanged; {:.1} fallbacks; {:.0} guard faults; textures {:.1} MB watched and \ + unchanged; {:.1} fallbacks ({:.1} ms); {:.0} guard faults; textures {:.1} MB watched and \ changed, {:.1} MB hashed, {:.1} MB of them changed; watch time: kernel {:.1} ms, view queries {:.1} ms, protecting {:.1} ms; copied whole (not tracked) {:.1} MB in {:.1} ms; snapshots {:.1} MB in {:.1} ms; page faults {:.0} preparing, {:.0} copying back; {:.0} tracked pages marked through another mapping; \ guards: {:.2} ms in the handler, {:.0} protect calls for {:.0} pages, {:.0} pages opened; \ {:.0} tracked pages written ({:.0} of them the frame before too); change checks: {:.1} ms \ @@ -250,6 +252,7 @@ pub(crate) fn log(frames: f64) { mb(c[C::Checked as usize]), mb(c[C::Unchanged as usize]), c[C::Fallbacks as usize], + ms(c[C::FallbackUs as usize]), c[C::GuardFaults as usize], mb(c[C::TexWatched as usize]), mb(c[C::TexHashed as usize]), diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index b675e24f20..15584c2fee 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -311,12 +311,14 @@ fn gpu_times(wall: Duration, commands: &[(f64, String)]) { let (by, wall_ms, sum) = times.get_or_insert_with(Default::default); *wall_ms += wall.as_secs_f64() * 1e3; for (ms, note) in commands { + // "draw 3x1 [mesh 1f.., pixel 2e..] | ...": the kind and the pipeline. let head = note.split(" | ").next().unwrap_or_default(); - let key: Vec<&str> = head - .split(' ') - .filter(|w| !w.starts_with(|c: char| c.is_ascii_digit()) && !w.starts_with("0x")) - .collect(); - let e = by.entry(key.join(" ")).or_default(); + let kind = head.split(' ').next().unwrap_or_default(); + let key = match head.find('[') { + Some(at) => format!("{kind} {}", &head[at..]), + None => kind.to_owned(), + }; + let e = by.entry(key).or_default(); (e.0, e.1) = (e.0 + ms, e.1 + 1); *sum += ms; } @@ -2126,6 +2128,8 @@ pub(crate) fn copy_mapped(dst: *mut u8, src: *const u8, len: usize, title_dst: b } #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::Fallbacks, 1); + #[cfg(feature = "diagnostics")] + let _timed = crate::watch::Timed(std::time::Instant::now(), crate::copystat::C::FallbackUs); // Something is unmapped: page by page (64 KiB, then 4 KiB in a piece // that fails), zeros for what cannot be read. for_pieces(src as usize, len, 64 << 10, |at, n| { From 6cc6aa3525d37b71a4d7189a7aaa1ff9f20a72bc Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 05:58:58 +0100 Subject: [PATCH 21/83] GPU: copies of single views share large buffers A view the title places off its buffer copy's elements gets a host copy of its own bytes (`shadow::exact`), and each was a committed buffer of its own: a kernel call to make it (and one to free it) on the title's recording threads and on the submitting thread during heap syncs, 240-820 a frame in the cutscene, and 64 KiB of memory each for ~2 KB of data (~5,000 live). A stack sample of a `drops` run caught the submitting thread in that kernel call inside the heap sync, which holds the heaps' lock, while three title threads waited for that lock to write views. Such copies now take runs of shared 16 MiB buffers (first fit; a run starts at a multiple of the view's element and of 256 bytes, so the view's first element stays exact; a copy larger than a buffer gets one of its size); a run goes back, joined to its free neighbours, when its copy goes. A host copy knows where it starts in its buffer (`offset` adds it; its mapping and host address point at the run), so the views made over it are unchanged. Copies are now keyed by element size too. Test: runs are aligned to their elements, disjoint, and joined again. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/draw.rs | 2 +- crates/victory-gpu/src/shadow.rs | 165 ++++++++++++++++++++++++++++--- 2 files changed, 153 insertions(+), 14 deletions(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 592fcbde90..a3eb0ea416 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -2616,7 +2616,7 @@ void main(uint3 id : SV_DispatchThreadID) { unsafe { made.GetDesc() }.Width }; assert_eq!(width(start + 456), 1 << 16, "on an element: the buffer's copy"); - assert_eq!(width(start + 100), (4 * 456u64).next_multiple_of(256), "off: its own bytes"); + assert_ne!(width(start + 100), 1 << 16, "off: a copy of its own bytes (in a shared buffer)"); let (copy, address, len) = crate::descriptor::host::view_copy(&view(start + 100)).unwrap(); assert_eq!((copy.range(), address, len), ((start + 100, 4 * 456), start + 100, 4 * 456)); drop(copy); diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index ed7808f633..577ac8ffea 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -46,6 +46,11 @@ pub(crate) struct Shadow { /// 64 KiB title page it touches (tracked memory only): writes through /// views of it are marked there ([`Shadow::mark_entry`]). marks: Option, + /// Where it starts in `buffer` (0 but for copies sharing a buffer), and + /// the run of the shared buffer it holds ([`Arena`]), given back when it + /// goes. + base: u64, + slice: Option, } /// Snapshot segments (offset, bytes) and the pieces compared. @@ -138,7 +143,7 @@ impl Shadow { /// Offset of a title address from the buffer's start. pub(crate) fn offset(&self, address: u64) -> u64 { - address - self.start + address - self.start + self.base } /// Where the title memory it copies starts, and its length. @@ -200,6 +205,12 @@ impl Shadow { } fn new(buffer: ID3D12Resource, data: *mut u8, gpu: u64, start: u64, len: u64) -> Arc { + Shadow::new_at(buffer, data, gpu, start, len, None) + } + + /// [`Shadow::new`] of a copy in a run of a shared buffer (`data` and + /// `gpu` are the run's). + fn new_at(buffer: ID3D12Resource, data: *mut u8, gpu: u64, start: u64, len: u64, slice: Option) -> Arc { let tracked = crate::watch::track(start as usize, len as usize, true); let marks = tracked.as_ref().and_then(|_| marks().take(pages(start, len))); let shadow = Arc::new(Shadow { @@ -212,6 +223,8 @@ impl Shadow { pending: Mutex::default(), before: Mutex::default(), marks, + base: slice.map_or(0, |s| s.offset), + slice, }); if let Some(base) = marks { self::marks().owners.insert(base, Arc::downgrade(&shadow)); @@ -629,6 +642,9 @@ impl Shadow { impl Drop for Shadow { fn drop(&mut self) { + if let Some(slice) = self.slice { + arena().give_back(slice); + } if let Some(base) = self.marks { let mut m = marks(); m.owners.remove(&base); @@ -940,7 +956,7 @@ pub(crate) fn for_view(address: u64, len: u64, element: u64) -> Option<(Arc 0) .count(); + let (chunks, held) = { + let a = arena(); + // SAFETY: live buffers. + let size = |c: &(ID3D12Resource, usize, u64, BTreeMap)| unsafe { c.0.GetDesc() }.Width; + let held: u64 = a.chunks.iter().map(|c| size(c) - c.3.values().sum::()).sum(); + (a.chunks.len(), held) + }; if asks > 0 { tracing::info!( - "buffer views off their copy's elements: {:.0} asked for/frame, {:.0} copies made/frame ({:.1} KB), largest {largest} bytes, {live} live", + "buffer views off their copy's elements: {:.0} asked for/frame, {:.0} copies made/frame ({:.1} KB), largest {largest} bytes, {live} live in {chunks} shared buffers ({:.1} MB held)", asks as f64 / frames, made as f64 / frames, - bytes as f64 / frames / 1e3 + bytes as f64 / frames / 1e3, + held as f64 / 1e6 ); } } @@ -977,12 +1001,12 @@ pub(crate) fn log_views(frames: f64) { /// new copy of the same bytes took the refreshes). With the size the map /// is next pruned of dead entries at. #[allow(clippy::type_complexity)] -static EXACT: Mutex<(usize, BTreeMap<(u64, u64), std::sync::Weak>)> = Mutex::new((0, BTreeMap::new())); +static EXACT: Mutex<(usize, BTreeMap<(u64, u64, u64), std::sync::Weak>)> = Mutex::new((0, BTreeMap::new())); -fn exact(address: u64, len: u64) -> Option> { +fn exact(address: u64, len: u64, element: u64) -> Option> { let mut guard = EXACT.lock().unwrap_or_else(|e| e.into_inner()); let (prune_at, map) = &mut *guard; - if let Some(shadow) = map.get(&(address, len)).and_then(std::sync::Weak::upgrade) { + if let Some(shadow) = map.get(&(address, len, element)).and_then(std::sync::Weak::upgrade) { return Some(shadow); } // Ring positions change every frame: entries die by the hundred. @@ -990,12 +1014,10 @@ fn exact(address: u64, len: u64) -> Option> { map.retain(|_, w| w.strong_count() > 0); *prune_at = (2 * map.len()).max(1024); } - let (buffer, data) = host()?.shared_buffer(len.next_multiple_of(256))?; - crate::host::name(&buffer, || format!("title view {address:#x}+{len:#x}")); - // SAFETY: a live buffer. - let gpu = unsafe { buffer.GetGPUVirtualAddress() }; - let shadow = Shadow::new(buffer, data, gpu, address, len); - map.insert((address, len), Arc::downgrade(&shadow)); + // A run of a shared buffer, its start a whole number of elements in. + let (buffer, data, gpu, slice) = arena().take(len, element)?; + let shadow = Shadow::new_at(buffer, data, gpu, address, len, Some(slice)); + map.insert((address, len, element), Arc::downgrade(&shadow)); #[cfg(feature = "diagnostics")] { use std::sync::atomic::Ordering::Relaxed; @@ -1006,6 +1028,98 @@ fn exact(address: u64, len: u64) -> Option> { Some(shadow) } +/// A run of an [`Arena`] buffer: the buffer, where the run starts, its +/// bytes. +#[derive(Clone, Copy)] +struct Slice { + chunk: usize, + offset: u64, + len: u64, +} + +/// Shared buffers for the copies of single views ([`exact`]): they are +/// small (~2 KB on average) and come and go by the hundred a frame, and a +/// buffer of their own each cost a kernel call to make and one to free on +/// the title's threads and the submitting one (300-820 a frame), and 64 KiB +/// of memory each (~5,000 live). +#[derive(Default)] +struct Arena { + /// Each buffer, its mapping and host address, and its free runs + /// (offset → bytes). + chunks: Vec<(ID3D12Resource, usize, u64, BTreeMap)>, +} + +/// Bytes of each arena buffer (a larger copy gets one of its size). +const CHUNK: u64 = 16 << 20; + +static ARENA: Mutex = Mutex::new(Arena { chunks: Vec::new() }); + +fn arena() -> std::sync::MutexGuard<'static, Arena> { + ARENA.lock().unwrap_or_else(|e| e.into_inner()) +} + +impl Arena { + /// A run of `len` bytes starting at a multiple of `element` (and of 256) + /// in a shared buffer: the buffer, the run's mapping and host address. + fn take(&mut self, len: u64, element: u64) -> Option<(ID3D12Resource, *mut u8, u64, Slice)> { + let gcd = |mut a: u64, mut b: u64| { + while b != 0 { + (a, b) = (b, a % b); + } + a + }; + let align = 256 / gcd(256, element.max(1)) * element.max(1); + let len = len.max(1).next_multiple_of(4); + let fits = |free: &BTreeMap| { + free.iter().find_map(|(&at, &n)| { + let start = at.next_multiple_of(align); + (start + len <= at + n).then_some((at, n, start)) + }) + }; + let found = self.chunks.iter().enumerate().find_map(|(c, chunk)| fits(&chunk.3).map(|f| (c, f))); + let (chunk, (at, n, start)) = match found { + Some(found) => found, + None => { + let size = CHUNK.max((len + align).next_multiple_of(1 << 16)); + let (buffer, data) = host()?.shared_buffer(size)?; + crate::host::name(&buffer, || format!("title views {size:#x}")); + // SAFETY: a live buffer. + let gpu = unsafe { buffer.GetGPUVirtualAddress() }; + let free = BTreeMap::from([(0, size)]); + self.chunks.push((buffer, data as usize, gpu, free)); + let c = self.chunks.len() - 1; + (c, fits(&self.chunks[c].3)?) + } + }; + let (buffer, data, gpu, free) = &mut self.chunks[chunk]; + free.remove(&at); + if start > at { + free.insert(at, start - at); + } + if at + n > start + len { + free.insert(start + len, at + n - start - len); + } + let slice = Slice { chunk, offset: start, len }; + Some((buffer.clone(), (*data + start as usize) as *mut u8, *gpu + start, slice)) + } + + /// A run goes back, joined to its free neighbours. + fn give_back(&mut self, slice: Slice) { + let Some((_, _, _, free)) = self.chunks.get_mut(slice.chunk) else { return }; + let (mut at, mut n) = (slice.offset, slice.len); + if let Some((&before, &m)) = free.range(..at).next_back() + && before + m == at + { + free.remove(&before); + (at, n) = (before, n + m); + } + if let Some(m) = free.remove(&(at + n)) { + n += m; + } + free.insert(at, n); + } +} + /// Every host copy of title memory made so far (buffers and windows). pub(crate) fn all() -> Vec> { let mut all: Vec> = buffers().values().filter_map(|e| e.shadow.clone()).collect(); @@ -1148,6 +1262,31 @@ mod tests { // page table still holds must not name memory reused meanwhile. } + /// Runs of the shared buffers start a whole number of elements (and of + /// 256 bytes) in, do not overlap, and join again when given back. + #[test] + fn arena_runs_are_aligned_to_their_elements_and_join_again() { + if host().is_none() { + return; // no host GPU here + } + let mut arena = Arena::default(); + let (_, _, _, a) = arena.take(100, 456).unwrap(); + let (_, _, _, b) = arena.take(5000, 16).unwrap(); + let (_, _, _, c) = arena.take(4, 4).unwrap(); + assert!(a.offset % 456 == 0 && a.offset % 256 == 0 && b.offset % 256 == 0); + let mut runs = [a, b, c].map(|s| (s.offset, s.offset + s.len)); + runs.sort_unstable(); + assert!(runs.windows(2).all(|w| w[0].1 <= w[1].0), "{runs:?}"); + for s in [b, a, c] { + arena.give_back(s); + } + assert_eq!(arena.chunks.len(), 1); + assert_eq!(arena.chunks[0].3.len(), 1, "one free run again"); + // Larger than a buffer: one of its own. + let (_, _, _, d) = arena.take(CHUNK + 1, 4).unwrap(); + assert_eq!((arena.chunks.len(), d.chunk), (2, 1)); + } + /// Ranges shaders write far apart are kept apart (not the copy between /// them); what the GPU wrote goes back once, whichever overlapping /// ranges declared it, and nothing else does. From c4e022d6c235eba6e4cef7dd82e981d7539a80c1 Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 05:58:58 +0100 Subject: [PATCH 22/83] GPU: diagnostics: title threads' wait for the heaps' lock; host copies in video memory * copystat: time title threads spend waiting for the shader-visible heaps' lock when they write a view (held by each submission's heap sync). * `VICTORY_COPIES_IN_VIDEO_MEMORY=1`: shared buffers, host copies of title memory among them, in a GPU upload heap (video memory the CPU maps) where the host has one, to measure how much of the GPU's time is shaders reading copies across the bus. CPU reads of the copies get slow (snapshots, copy-backs): for that measurement only. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/copystat.rs | 8 +++++-- crates/victory-gpu/src/descriptor.rs | 4 ++++ crates/victory-gpu/src/host.rs | 34 ++++++++++++++++++++++++++++ 3 files changed, 44 insertions(+), 2 deletions(-) diff --git a/crates/victory-gpu/src/copystat.rs b/crates/victory-gpu/src/copystat.rs index 34348407e7..060428c811 100644 --- a/crates/victory-gpu/src/copystat.rs +++ b/crates/victory-gpu/src/copystat.rs @@ -101,8 +101,11 @@ pub(crate) enum C { SyncSlots, /// Time in copies redone piece by piece after meeting an unmapped page. FallbackUs, + /// Title threads writing a view into a shader-visible heap: time + /// waiting for the heaps' lock (held by heap syncs and other writers). + MirrorWaitUs, } -const COUNTERS: usize = 60; +const COUNTERS: usize = 61; static COUNT: [AtomicU64; COUNTERS] = [const { AtomicU64::new(0) }; COUNTERS]; pub(crate) fn add(c: C, n: u64) { @@ -231,7 +234,7 @@ pub(crate) fn log(frames: f64) { asking for other mappings, {:.1} ms waiting for the guard lock; preparing: {:.1} ms in \ refresh batches, steps (each with the batch it flushes): refresh {:.1} ms, copy {:.1} ms, \ work {:.1} ms, GPU writes {:.1} ms, textures {:.1} ms, heaps {:.1} ms, title memory {:.1} ms; \ - heap texture uploads {:.1} ms, state preludes {:.1} ms, heap slots the title copied {:.1} ms ({:.0} slots); copying back compared {:.1} MB in {:.1} ms; marked pages: {:.0} compared, {:.1} MB written back in {:.1} ms, {:.0} kept the title's, {:.0} saved; working set {:.0} MB, \ + heap texture uploads {:.1} ms, state preludes {:.1} ms, heap slots the title copied {:.1} ms ({:.0} slots), title threads waiting to write views {:.1} ms; copying back compared {:.1} MB in {:.1} ms; marked pages: {:.0} compared, {:.1} MB written back in {:.1} ms, {:.0} kept the title's, {:.0} saved; working set {:.0} MB, \ {:.0} hard faults", c[C::Submissions as usize], c[C::Copies as usize], @@ -287,6 +290,7 @@ pub(crate) fn log(frames: f64) { ms(c[C::PreludeUs as usize]), ms(c[C::SyncHeapsUs as usize]), c[C::SyncSlots as usize], + ms(c[C::MirrorWaitUs as usize]), mb(c[C::CompareBytes as usize]), ms(c[C::CompareUs as usize]), c[C::MarkedPages as usize], diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 63e3dbe20c..84ce54358f 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -126,7 +126,11 @@ static SHADER_HEAPS: std::sync::Mutex> = std::sync::Mutex /// so `Heap::drop` cannot free the heap concurrently. #[cfg(windows)] fn mirror(handle: u64) { + #[cfg(feature = "diagnostics")] + let waited = crate::watch::Timed(std::time::Instant::now(), crate::copystat::C::MirrorWaitUs); let heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner()); + #[cfg(feature = "diagnostics")] + drop(waited); let Some(&(_, _, at)) = heaps .iter() .find(|&&(start, end, _)| (start..end).contains(&handle)) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 15584c2fee..f6acf1bb3c 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -2790,6 +2790,34 @@ pub(crate) fn legal_for(flags: u32, state: u32) -> u32 { } impl Host { + /// Diagnostics, `VICTORY_COPIES_IN_VIDEO_MEMORY`: [`Host::shared_buffer`]s + /// (host copies of title memory among them) in video memory the CPU maps + /// (a GPU upload heap, where the host has one), to measure how much of + /// the GPU's time is shaders reading the copies over the bus. CPU reads + /// of them (snapshots, copy-backs) become slow: for that measurement only. + #[cfg(feature = "diagnostics")] + fn copies_in_video_memory(&self) -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| { + if !crate::switch::on("VICTORY_COPIES_IN_VIDEO_MEMORY") { + return false; + } + let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS16::default(); + // SAFETY: the query writes its own structure of the given size. + let ok = unsafe { + self.device.CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS16, + (&raw mut options).cast(), + size_of_val(&options) as u32, + ) + } + .is_ok() + && options.GPUUploadHeapSupported.as_bool(); + tracing::warn!(on = ok, "host copies of title memory in video memory (diagnostics)"); + ok + }) + } + /// A buffer in system memory that the CPU maps (write-back, so reading /// it is fast too) and shaders read and write: for host copies of title /// memory that shaders write, which upload memory cannot be. Starts in @@ -2801,6 +2829,12 @@ impl Host { MemoryPoolPreference: D3D12_MEMORY_POOL_L0, ..Default::default() }; + #[cfg(feature = "diagnostics")] + let heap = if self.copies_in_video_memory() { + D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_GPU_UPLOAD, ..Default::default() } + } else { + heap + }; let desc = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: size.max(1), From 29221419b5bccc1536b3c09d06387e2307cdfbf7 Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 05:59:42 +0100 Subject: [PATCH 23/83] GPU: a heap's merged view ranges are kept current, not rebuilt whole after each change Each list running heap-indexing shaders asks for the ranges every view of the heap reaches, merged per host copy; they were rebuilt from all ~9,000 copies whenever one range came or went, which the title's view writes do between most lists: the heap step still took 13-27 ms a frame in run perf4 although it now passes clean copies by. The merged range of a copy is now updated where its ranges are counted, only for that copy, and the step walks the current set. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/bindless.rs | 44 ++++++++++++++---------------- 1 file changed, 20 insertions(+), 24 deletions(-) diff --git a/crates/victory-gpu/src/bindless.rs b/crates/victory-gpu/src/bindless.rs index a85c4a7977..e2fb5a4cfd 100644 --- a/crates/victory-gpu/src/bindless.rs +++ b/crates/victory-gpu/src/bindless.rs @@ -53,9 +53,11 @@ struct Inner { slots: HashMap, ranges: BTreeMap)>, textures: BTreeMap, - /// `ranges` merged per copy and kind ([`Viewed::ranges`]), while no - /// range is added or dropped: every list running heap shaders asks. - hulls: Option>, + /// `ranges` merged per copy and kind ([`Viewed::ranges`]), kept current + /// as ranges come and go (each list running heap shaders asks for all + /// of them; rebuilt whole after every change, they cost 13-27 ms a frame, + /// run perf4). + hulls: HashMap<(usize, bool), Hull>, /// Per copy and kind (unordered access): the copy, and how many ranges /// start and end at each offset, so that the hulls are made from the /// copies, not from every range (the title rewrites slots between most @@ -91,15 +93,24 @@ impl Inner { } // A range came or went: its copy's hull may change. if (was == 0) != (now == 0) { - self.hulls = None; let ends = self .ends .entry((key.0, key.3)) .or_insert_with(|| (shadow.clone(), BTreeMap::new(), BTreeMap::new())); tally(&mut ends.1, key.1, now > 0); tally(&mut ends.2, key.2, now > 0); - if ends.1.is_empty() { - self.ends.remove(&(key.0, key.3)); + let hull = match (ends.1.keys().next(), ends.2.keys().next_back()) { + (Some(&from), Some(&to)) => Some((shadow.clone(), from, to - from, key.3, shadow.dirty_bit())), + _ => None, + }; + match hull { + Some(hull) => { + self.hulls.insert((key.0, key.3), hull); + } + None => { + self.ends.remove(&(key.0, key.3)); + self.hulls.remove(&(key.0, key.3)); + } } } } @@ -134,22 +145,7 @@ impl Viewed { /// (shader resource, unordered access): copy, start, bytes. #[cfg(any(test, feature = "diagnostics"))] fn ranges(&self) -> Vec { - self.inner.lock().unwrap_or_else(|e| e.into_inner()).hulls().clone() - } -} - -impl Inner { - /// [`Viewed::ranges`], made once while no range comes or goes. - fn hulls(&mut self) -> &Vec { - let Inner { hulls, ends, .. } = self; - hulls.get_or_insert_with(|| { - ends.iter() - .filter_map(|(&(_, uav), (shadow, starts, ends))| { - let (&from, &to) = (starts.keys().next()?, ends.keys().next_back()?); - Some((shadow.clone(), from, to - from, uav, shadow.dirty_bit())) - }) - .collect() - }) + self.inner.lock().unwrap_or_else(|e| e.into_inner()).hulls.values().cloned().collect() } } @@ -264,8 +260,8 @@ impl Uploads { /// Copies the title has not written since they took it are passed by: a /// world submission's heaps reach ~9,000 copies, a few of them written. pub(crate) fn refresh(viewed: &Viewed, mut add: impl FnMut(&Arc, usize, usize)) { - let mut inner = viewed.inner.lock().unwrap_or_else(|e| e.into_inner()); - for (shadow, address, len, _, bit) in inner.hulls() { + let inner = viewed.inner.lock().unwrap_or_else(|e| e.into_inner()); + for (shadow, address, len, _, bit) in inner.hulls.values() { if !crate::watch::clean_bit(*bit) { add(shadow, *address as usize, *len as usize); } From ac7ffc0ae14ebc91dedbe4f3d17a114f4febaa30 Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 06:22:45 +0100 Subject: [PATCH 24/83] GPU: large heap allocations name their caller; list upload memory in the memory line (diagnostics) The counting allocator logs the stack of the first allocation of each power-of-two size class from 32 MiB (who holds our 1.8 GB of large blocks, run textures6), and the video-memory line counts the live list upload blocks (list 0x4a0) and their bytes. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/copystat.rs | 36 ++++++++++++++++++++++++++++++ crates/victory-gpu/src/host.rs | 4 +++- crates/victory-gpu/src/list.rs | 9 ++++++++ 3 files changed, 48 insertions(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/copystat.rs b/crates/victory-gpu/src/copystat.rs index 060428c811..2b183647cd 100644 --- a/crates/victory-gpu/src/copystat.rs +++ b/crates/victory-gpu/src/copystat.rs @@ -345,6 +345,33 @@ pub struct CountingAlloc; /// Bytes [`CountingAlloc`] has handed out and not taken back. pub(crate) static HEAP_BYTES: AtomicU64 = AtomicU64::new(0); +/// Allocations of at least this many bytes name their caller, once per +/// power-of-two size class (who holds the big blocks of our heap). +const LARGE: usize = 32 << 20; + +/// Logs the stack of a large allocation of `size` bytes, the first of its +/// size class. +fn note_large(size: usize) { + static SEEN: std::sync::Mutex = std::sync::Mutex::new(0); + std::thread_local!(static INSIDE: std::cell::Cell = const { std::cell::Cell::new(false) }); + let class = 1u64 << size.ilog2().min(63); + if INSIDE.with(|i| i.replace(true)) { + return; + } + let first = { + let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner()); + let first = *seen & class == 0; + *seen |= class; + first + }; + if first { + let trace = std::backtrace::Backtrace::force_capture().to_string(); + let frames: Vec<&str> = trace.lines().filter(|l| l.contains("victory")).take(24).collect(); + tracing::info!(mb = size >> 20, "a large heap allocation (first of its size class): {}", frames.join(" | ")); + } + INSIDE.with(|i| i.set(false)); +} + // SAFETY: every call goes to the system allocator unchanged; only counted. unsafe impl std::alloc::GlobalAlloc for CountingAlloc { unsafe fn alloc(&self, layout: std::alloc::Layout) -> *mut u8 { @@ -352,6 +379,9 @@ unsafe impl std::alloc::GlobalAlloc for CountingAlloc { let p = unsafe { std::alloc::System.alloc(layout) }; if !p.is_null() { HEAP_BYTES.fetch_add(layout.size() as u64, Relaxed); + if layout.size() >= LARGE { + note_large(layout.size()); + } } p } @@ -361,6 +391,9 @@ unsafe impl std::alloc::GlobalAlloc for CountingAlloc { let p = unsafe { std::alloc::System.alloc_zeroed(layout) }; if !p.is_null() { HEAP_BYTES.fetch_add(layout.size() as u64, Relaxed); + if layout.size() >= LARGE { + note_large(layout.size()); + } } p } @@ -377,6 +410,9 @@ unsafe impl std::alloc::GlobalAlloc for CountingAlloc { if !q.is_null() { HEAP_BYTES.fetch_sub(layout.size() as u64, Relaxed); HEAP_BYTES.fetch_add(size as u64, Relaxed); + if size >= LARGE { + note_large(size); + } } q } diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index f6acf1bb3c..b49b391645 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -2526,13 +2526,15 @@ impl Meter { tracing::info!( "video memory: {local:.0} MB of a {budget:.0} MB budget on the card, \ {system:.0} MB of {system_budget:.0} MB in system memory; process commit {:.0} MB, \ - working set {:.0} MB; process heaps {:.0} MB (Rust {:.0} MB); texture staging {:.0} MB; placed textures made {:.0} MB", + working set {:.0} MB; process heaps {:.0} MB (Rust {:.0} MB); texture staging {:.0} MB; placed textures made {:.0} MB; list upload memory {} blocks {:.0} MB", commit as f64 / 1e6, working_set as f64 / 1e6, crate::copystat::heaps_committed() as f64 / 1e6, crate::copystat::HEAP_BYTES.load(Ordering::Relaxed) as f64 / 1e6, crate::texture::STAGING_BYTES.load(Ordering::Relaxed) as f64 / 1e6, crate::resource::PLACED_BYTES.load(Ordering::Relaxed) as f64 / 1e6, + crate::list::UPLOADS[0].load(Ordering::Relaxed), + crate::list::UPLOADS[1].load(Ordering::Relaxed) as f64 / 1e6, ); } let [gpu, title] = crate::resource::texture_census().map(|r| r.map(|b| b as f64 / 1e6)); diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 8df296f96c..80bc2baabc 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -1084,6 +1084,8 @@ impl Upload { return None; } crate::shadow::register(at, at as u64, len as u64); + UPLOADS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + UPLOADS[1].fetch_add(len as u64, std::sync::atomic::Ordering::Relaxed); Some(Upload { at, len }) } @@ -1107,6 +1109,8 @@ impl Drop for Upload { fn drop(&mut self) { use windows_sys::Win32::System::Memory::{MEM_RELEASE, VirtualFree}; crate::shadow::unregister(self.at, self.at as u64); + UPLOADS[0].fetch_sub(1, std::sync::atomic::Ordering::Relaxed); + UPLOADS[1].fetch_sub(self.len as u64, std::sync::atomic::Ordering::Relaxed); // Not guarded any more: memory allocated here next is new. crate::watch::title_memory_remapped(self.at, self.len); // SAFETY: our allocation; lists that still use its copy hold that. @@ -1118,6 +1122,11 @@ impl Drop for Upload { #[cfg(windows)] unsafe impl Send for Upload {} +/// Live list upload blocks and their bytes (the statistics). +#[cfg(windows)] +pub(crate) static UPLOADS: [std::sync::atomic::AtomicU64; 2] = + [std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0)]; + /// Draw state the host has no use for (root signatures: ours come with /// the pipeline; depth bounds, depth order and shading rate hints): any /// arguments, nothing returned. From 23a4b62bbb7d05aad96e43d8c2dde638ff8e43ef Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 06:34:36 +0100 Subject: [PATCH 25/83] GPU: a texture is uploaded once per submission, and only when its bytes changed Every list that read a title-written texture through a table recorded the copy of its staging buffer into the host texture, changed or not: run perf7 counted 3,195 texture copy commands in one frame for 149 textures (a 64x64x32 R16 array 24 times, a 512x512 BC7 18 times), 17 ms of GPU time, the largest single GPU item. A list now only defers the texture (staging and host texture). At submission the textures of all its lists are brought up to date once, and those whose memory changed are copied by the submission's own upload list (the one heap-indexed textures already had), which runs first. For memory the change journal follows, a flagged page uploads the texture only if the texture's own bytes changed (a 64 KiB page holds other data too). As for heap-indexed textures, a title copy into texture memory recorded in the same submission shows from the next one on. Test: two lists of one submission upload a texture once, the next submission not at all, and again once the title writes it. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/bindless.rs | 22 ++++- crates/victory-gpu/src/draw.rs | 45 +++++++++++ crates/victory-gpu/src/host.rs | 124 ++++++++--------------------- crates/victory-gpu/src/texture.rs | 61 +++++++++++--- 4 files changed, 142 insertions(+), 110 deletions(-) diff --git a/crates/victory-gpu/src/bindless.rs b/crates/victory-gpu/src/bindless.rs index e2fb5a4cfd..974df96aa4 100644 --- a/crates/victory-gpu/src/bindless.rs +++ b/crates/victory-gpu/src/bindless.rs @@ -187,13 +187,18 @@ fn left_kind(view: &View) -> (usize, u64, u64) { } /// At submission, before anything else of it: the textures the heaps of its -/// heap-indexing lists view are brought up to date, those whose title -/// memory changed copied into their host textures by a list of ours, which -/// the submission runs first (and leaves them readable by shaders). +/// heap-indexing lists view, and `textures` (staging and host texture of +/// those its lists read through tables, `crate::texture::upload`), are +/// brought up to date, those whose title memory changed copied into their +/// host textures by a list of ours, which the submission runs first (and +/// leaves them readable by shaders): each at most once. /// /// shortcut: a title copy into texture memory recorded in the same /// submission shows from the next one on. -pub(crate) fn uploads(heaps: &[Arc]) -> Option { +pub(crate) fn uploads( + heaps: &[Arc], + textures: &[(Arc, Arc)], +) -> Option { static LIST: Mutex = Mutex::new(Holder(None)); const SHADER_RESOURCE: u32 = 0x40 | 0x80; let mut guard = LIST.lock().unwrap_or_else(|e| e.into_inner()); @@ -205,6 +210,15 @@ pub(crate) fn uploads(heaps: &[Arc]) -> Option { } let list = guard.0.as_ref()?; let mut recorded = false; + let mut staged = std::collections::HashSet::new(); + for (staging, copy) in textures { + if staged.insert(Arc::as_ptr(staging)) && staging.refresh() { + crate::texture::record_upload(list, copy, staging); + recorded = true; + #[cfg(feature = "diagnostics")] + UPLOADED.fetch_add(1, Relaxed); + } + } let mut done = std::collections::HashSet::new(); for viewed in heaps { // Held while uploading: the title releasing a texture (and its diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index a3eb0ea416..a334928e9b 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -2351,6 +2351,51 @@ void main(uint3 id : SV_DispatchThreadID) { } } + /// A texture the title wrote, read through tables by two lists of one + /// submission, is uploaded once; the next submission uploads it again + /// only after the title writes it (run perf7 uploaded the same textures + /// up to 24 times a frame). + #[test] + fn a_texture_is_uploaded_once_per_submission_and_only_when_written() { + let Some(host) = crate::host::host() else { + return; // no host GPU here + }; + let slots = Slots::new(2); + let read = compile_cs(READ); + let (out, data) = host.shared_buffer(64 * 64 * 16).unwrap(); + // Runtime memory the change journal follows; RGBA8 64x64, linear. + let address = crate::watch::tests::pool(1) as u64; + let object = texture_at_address(address, &texture_words(64, 64, 28, 0x100, 0)); + let mut desc = [0u32; 10]; + desc[..6].copy_from_slice(&[28, 4, 0x1688, 0, 0, 1]); + let view = View::Shader(object as usize, Some(desc)); + slots.make(0, &view); + let submit = |byte: Option| { + if let Some(byte) = byte { + // SAFETY: the texture's memory, 256-byte rows of 64 texels. + unsafe { std::ptr::write_bytes(address as *mut u8, byte, 64 * 64 * 4) }; + } + let lists = [host.new_list().unwrap(), host.new_list().unwrap()]; + for list in &lists { + readable(list, &used(ResourceType::Srv), &view, false); + run(list, &slots, &read, 0, Some(&out), (8, 8)); + list.close(); + } + let before = crate::texture::UPLOADS.load(Ordering::Relaxed); + host.execute(&[&lists[0], &lists[1]]); + // SAFETY: inside the mapped output. + let texel = unsafe { (data as *const [f32; 4]).read() }; + (crate::texture::UPLOADS.load(Ordering::Relaxed) - before, texel[0]) + }; + let (n, x) = submit(Some(0x40)); + assert_eq!(n, 1, "one upload for two lists"); + assert!((x - 64.0 / 255.0).abs() < 1e-6); + assert_eq!(submit(None).0, 0, "not written: not uploaded"); + let (n, x) = submit(Some(0x80)); + assert_eq!(n, 1, "written: uploaded again"); + assert!((x - 128.0 / 255.0).abs() < 1e-6); + } + /// A depth texture with stencil (the console's 16-bit depth, the /// host's 32-bit float) written through unordered views of its planes, /// then read as depth and stencil: the 16-bit depth arrives as the diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index b49b391645..aaedce3b21 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -729,7 +729,7 @@ enum Step { GpuWrite(std::sync::Arc, usize, usize, bool), /// Brings a texture's staging buffer up to date: once per submission, /// whichever lists sample it, until a `Copy` or `Run` intervenes. - Texture(std::sync::Arc), + Texture(std::sync::Arc, std::sync::Arc), /// Brings every buffer range a view heap's views reach up to date /// (`crate::bindless`). Heap(std::sync::Arc), @@ -918,10 +918,24 @@ impl Host { .collect::>() }) .collect(); + // And textures read through tables, uploaded by the same list. + let textures: Vec<_> = runs + .iter() + .flat_map(|l| { + l.deferred() + .copies + .iter() + .filter_map(|s| match s { + Step::Texture(staging, copy) => Some((staging.clone(), copy.clone())), + _ => None, + }) + .collect::>() + }) + .collect(); #[cfg(feature = "diagnostics")] let uploading = crate::watch::Timed(std::time::Instant::now(), crate::copystat::C::UploadsUs); - let uploads = (!heaps.is_empty()) - .then(|| crate::bindless::uploads(&heaps)) + let uploads = (!heaps.is_empty() || !textures.is_empty()) + .then(|| crate::bindless::uploads(&heaps, &textures)) .flatten(); #[cfg(feature = "diagnostics")] drop(uploading); @@ -1893,10 +1907,15 @@ impl HostList { self.deferred().copies.push(Step::Host(Box::new(work))); } - /// Brings a texture's staging buffer up to date when the list is - /// submitted, keeping it alive until the list is reset. - pub(crate) fn defer_texture(&self, staging: std::sync::Arc) { - self.deferred().copies.push(Step::Texture(staging)); + /// Brings a texture's staging buffer and host texture `copy` up to date + /// when the list is submitted (`crate::bindless::uploads`), keeping + /// both alive until the list is reset. + pub(crate) fn defer_texture( + &self, + staging: std::sync::Arc, + copy: std::sync::Arc, + ) { + self.deferred().copies.push(Step::Texture(staging, copy)); } /// Runs the list's submission-time steps; refreshes go into `batch` @@ -1915,7 +1934,7 @@ impl HostList { Step::Copy(..) | Step::Fill(..) => C::StepCopyUs, Step::Run(_) | Step::Host(_) => C::StepWorkUs, Step::GpuWrite(..) => C::StepGpuWriteUs, - Step::Texture(_) => C::StepTextureUs, + Step::Texture(..) => C::StepTextureUs, Step::Heap(_) => C::StepHeapUs, Step::Memory(_) => C::StepMemoryUs, }, @@ -1970,12 +1989,8 @@ impl HostList { shadow.writing(*address, *len, *marked); continue; } - Step::Texture(staging) => { - if batch.texture_due(staging) { - staging.refresh(); - } - continue; - } + // Brought up to date before the submission's lists were made. + Step::Texture(..) => continue, Step::Heap(viewed) => { crate::bindless::refresh(viewed, |s, a, l| batch.add(s, a, l)); continue; @@ -2013,8 +2028,6 @@ struct Batch { /// The range of each copy brought up to date since the last title /// write, by copy (held, so that its address names no other). current: std::collections::HashMap, usize, usize)>, - /// Staging buffers (by address) refreshed since the last title write. - textures: std::collections::HashSet, } impl Batch { @@ -2040,17 +2053,10 @@ impl Batch { } } - /// Whether `staging` is still to be refreshed in this submission (and - /// notes it refreshed). - fn texture_due(&mut self, staging: &std::sync::Arc) -> bool { - self.textures.insert(std::sync::Arc::as_ptr(staging) as *const () as usize) - } - /// Before a step that writes title memory: pending refreshes are done /// first, and textures are checked again after it. fn title_written(&mut self) { self.flush(); - self.textures.clear(); self.current.clear(); } @@ -3129,38 +3135,8 @@ fn pump() { } #[cfg(test)] -mod batch { // Batch::texture_due lives here; `mod tests` is already taken at the top of this file +mod batch { // `mod tests` is already taken at the top of this file use super::Batch; - use std::sync::Arc; - - #[test] - fn a_texture_is_checked_once_per_submission() { - let mut batch = Batch::default(); - let (a, b) = (Arc::new([0u8; 16]), Arc::new([0u8; 16])); - // The first list sampling each texture checks it ... - assert!(batch.texture_due(&a)); - assert!(batch.texture_due(&b)); - // ... later lists of the same submission do not. - assert!(!batch.texture_due(&a)); - assert!(!batch.texture_due(&a.clone())); - assert!(!batch.texture_due(&b)); - } - - #[test] - fn title_writes_make_textures_due_again() { - let mut batch = Batch::default(); - let a = Arc::new(1u32); - assert!(batch.texture_due(&a)); - assert!(!batch.texture_due(&a)); - // A copy into title memory or work that may write it may have - // changed the texture's memory. - batch.title_written(); - assert!(batch.texture_due(&a)); - assert!(!batch.texture_due(&a)); - // A fresh submission starts over. - let mut next = Batch::default(); - assert!(next.texture_due(&a)); - } /// A host copy of tracked title memory: a submission whose lists all ask /// for it whole copies the one page the title wrote, once, and again @@ -3197,43 +3173,5 @@ mod batch { // Batch::texture_due lives here; `mod tests` is already taken at drop(copy); crate::watch::tests::free(p); } - - /// The hashing a submission does for textures in physical-page memory, - /// with every list checking the textures it samples (before) and with - /// each checked once (after). Run with - /// `cargo test --release -p victory-gpu -- --ignored --nocapture texture_checks`. - #[test] - #[ignore = "benchmark"] - fn texture_checks_per_submission() { - const TEXTURES: usize = 48; - const SIZE: usize = 4 << 20; - const LISTS: usize = 12; - let textures: Vec>> = (0..TEXTURES) - .map(|t| Arc::new((0..SIZE).map(|i| (i * 31 + t) as u8).collect())) - .collect(); - let submit = |dedupe: bool| { - let mut batch = Batch::default(); - let mut hashed = 0usize; - let started = std::time::Instant::now(); - for _ in 0..LISTS { - for t in &textures { - if !dedupe || batch.texture_due(t) { - std::hint::black_box(blake3::hash(t)); - hashed += 1; - } - } - } - (started.elapsed(), hashed) - }; - submit(false); // warm up - let (before, n_before) = submit(false); - let (after, n_after) = submit(true); - assert_eq!((n_before, n_after), (TEXTURES * LISTS, TEXTURES)); - println!( - "{LISTS} lists sampling {TEXTURES} textures of {} MiB: \ - before {n_before} hashes in {before:?}, after {n_after} in {after:?} ({:.1}x)", - SIZE >> 20, - before.as_secs_f64() / after.as_secs_f64() - ); - } } + diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index cfac0d8982..4627e01239 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -52,8 +52,7 @@ pub(crate) struct Staging { last: Mutex, } -/// What a texture's staging buffer holds: the hash of the memory detiled -/// (memory not tracked). +/// What a texture's staging buffer holds: the hash of the memory detiled. #[derive(Default)] struct Last { hash: Option, @@ -195,10 +194,13 @@ pub(crate) fn alias_copy(list: &HostList, from: This, to: This) { } } -/// Records, once per list, the copy of `resource`'s staging buffer into -/// its host copy, and the detiling that refreshes the staging buffer at -/// submission if the memory changed. Leaves the texture in the copy -/// destination state. +/// Has `resource`'s host copy brought up to date at the submission that +/// runs `list`: its staging buffer detiled again if the memory changed, and +/// then copied into the host texture by the submission's own upload list, +/// once for all its lists (`crate::bindless::uploads`). +/// +/// shortcut: a title copy into texture memory recorded in the same +/// submission shows from the next one on. pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) { // shortcut: a texture the host copied into keeps the host's contents // even if the title later writes its memory too. @@ -220,16 +222,35 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) if !list.first_use(texture.as_raw() as usize) { return; } - let Some(staging) = staging(resource, texture) else { + let (Some(staging), Some(copy)) = (staging(resource, texture), crate::resource::host_copy(resource)) else { return; }; - // The staging buffer lives as long as `staging`, which the deferred - // refresh below holds until the list is reset. - record(list, resource, texture, &staging); - // Once per submission however many of its lists sample the texture. - list.defer_texture(staging); + // Each list recorded the copy before (run perf7: 149 textures uploaded + // 3,195 times in a frame, 17 ms of GPU time), changed or not. + list.defer_texture(staging, copy); } +/// Records into `list` the copy of `staging` into host texture `copy`, +/// leaving it readable by shaders. +pub(crate) fn record_upload(list: &HostList, copy: &Arc, staging: &Staging) { + const COPY_DEST: u32 = 0x400; + const SHADER_RESOURCE: u32 = 0x40 | 0x80; + let move_to = |wanted| { + if let Some(b) = list.move_texture(copy, wanted) { + // SAFETY: an open list; the barrier names a live texture. + unsafe { list.list.ResourceBarrier(&[b]) }; + } + }; + move_to(COPY_DEST); + copies(list, ©.texture, staging, String::new); + move_to(SHADER_RESOURCE); + list.keep(&staging.buffer); + UPLOADS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); +} + +/// Uploads [`record_upload`] recorded. +pub(crate) static UPLOADS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + /// For textures shaders reach through the heap itself, at submission /// (`crate::bindless::uploads`): brings the staging buffer up to date and /// records its copy into `list` only if the memory changed since (or was @@ -255,6 +276,13 @@ pub(crate) fn upload_changed(list: &HostList, resource: This, texture: &ID3D12Re fn record(list: &HostList, resource: This, texture: &ID3D12Resource, staging: &Staging) { const COPY_DEST: u32 = 0x400; crate::list::ensure_state(list, resource, COPY_DEST); + copies(list, texture, staging, || format!("{resource:?}")); +} + +/// Records the copy of every subresource of `staging` into `texture` (in +/// the copy destination state); `name` names it in diagnostics notes. +#[cfg_attr(not(feature = "diagnostics"), allow(unused_variables))] +fn copies(list: &HostList, texture: &ID3D12Resource, staging: &Staging, name: impl Fn() -> String) { for (i, footprint) in staging.footprints.iter().enumerate() { #[cfg(feature = "diagnostics")] { @@ -265,7 +293,8 @@ fn record(list: &HostList, resource: This, texture: &ID3D12Resource, staging: &S list.note_read( || { format!( - "texture upload {resource:?} ({}x{}x{} f{} mips {}) sub {i} of {} from staging {gpu:#x}+{:#x}: offset {:#x} {}x{}x{} pitch {}", + "texture upload {} ({}x{}x{} f{} mips {}) sub {i} of {} from staging {gpu:#x}+{:#x}: offset {:#x} {}x{}x{} pitch {}", + name(), d.Width, d.Height, d.DepthOrArraySize, @@ -332,6 +361,12 @@ impl Staging { // double each texture's system memory. let mut read = vec![0u8; size]; crate::host::copy_mapped(read.as_mut_ptr(), self.memory, size, false); + // Its pages also hold other data the title writes (64 KiB pages, + // small textures): its own bytes decide. + let hash = blake3::hash(&read); + if last.hash.replace(hash) == Some(hash) { + return (size, false); + } self.detile(&read); #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexWatched, size as u64); From a2c50db87298258a2a558692cc66f70829c79ce7 Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 03:11:35 +0100 Subject: [PATCH 26/83] GPU: a drop counted by its reason names the pipeline's shaders The per-frame drop ranking (diagnostics) counted draws and dispatches that have a host pipeline but cannot be bound by reason alone, so a reason's hundreds of drops a frame could not be traced to the programs behind them without a traced list. The key now ends with the pipeline's shaders, as the "no host pipeline" keys already do. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/draw.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index a334928e9b..9b5ef83082 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -150,7 +150,7 @@ fn dropped(list: &HostList, pipeline: usize, kind: &str) { if why.is_empty() || crate::pipeline::host_pipeline(pipeline as This).is_none() { crate::pipeline::note_drop(pipeline as This); } else { - crate::pipeline::note_why(format!("{kind}: {why}")); + crate::pipeline::note_why(format!("{kind}: {why} {}", crate::pipeline::shaders_of(pipeline as This))); } list.note_op(|| format!("DROPPED {kind} ({why}) {}", crate::pipeline::shaders_of(pipeline as This))); if let Some(last) = FRAME.lock().unwrap_or_else(|e| e.into_inner()).last_mut() { From 59c78bb5f7c3dca36025bd01f5d24ff6628cb15b Mon Sep 17 00:00:00 2001 From: Thiago <40046468+ThiagoAlexsander@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:00:58 -0300 Subject: [PATCH 27/83] Shaders: descriptors joined by nested control flow A descriptor every lane shares, chosen by an if/else nested in another, reaches the outer join with an edge that is itself a join. Such an edge was refused with "a descriptor chosen by control flow": each edge had to be a heap load. The heap index is now computed recursively: a load's index, or a phi at the join of what each predecessor computes at its end. Co-Authored-By: Claude Opus 5.5 --- crates/victory-shader/src/emit/lower.rs | 106 +++++++++++++++++++----- 1 file changed, 85 insertions(+), 21 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index caab7ead5c..bb56c6b4c8 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -4970,28 +4970,10 @@ impl<'a> Lower<'a> { self.s.sampler_choices.push((ha, hb, phi)); Ok(ha) } - Source::Phi { block, args } => { - // Each predecessor computes its heap index at its end; the - // join picks one with a phi. + Source::Phi { .. } => { let _ = site; - let mut incoming = Vec::new(); - for (&q, arg) in self.x.p.blocks[*block].preds.iter().zip(args) { - if self.block[q].is_none() { - continue; - } - let (Some(tail), Source::Loaded { load, first }) = (self.tail[q], arg) else { - return Err("a descriptor chosen by control flow"); - }; - let at = self.edges.get(&(q, *block)).copied().unwrap_or(tail); - let here = std::mem::replace(&mut self.cur, at); - let index = self.heap_index(*load, *first, sampler); - self.cur = here; - incoming.push((index?, at)); - } - let join = self.block[*block].ok_or("a descriptor chosen by control flow")?; - let phi = self.s.m.phi(join, self.s.t.i32); - self.s.m.set_phi(phi, incoming); - let index = self.buffer_guard(src, phi, sampler, props); + let index = self.uniform_heap_index(src, sampler)?; + let index = self.buffer_guard(src, index, sampler, props); Ok(self.s.heap_handle(self.cur, index, sampler, false, props)) } Source::Select { scc, args } => { @@ -5068,6 +5050,35 @@ impl<'a> Lower<'a> { }) } + /// The heap index of a descriptor every lane shares, computed in the + /// current block. One chosen by control flow is a phi at its join of the + /// index each predecessor computes at its end; an edge may bring another + /// join's (nested if/else). + fn uniform_heap_index(&mut self, src: &Source, sampler: bool) -> Result { + match src { + Source::Loaded { load, first } => self.heap_index(*load, *first, sampler), + Source::Phi { block, args } => { + let mut incoming = Vec::new(); + for (&q, arg) in self.x.p.blocks[*block].preds.iter().zip(args) { + if self.block[q].is_none() { + continue; + } + let tail = self.tail[q].ok_or("a descriptor chosen by control flow")?; + let at = self.edges.get(&(q, *block)).copied().unwrap_or(tail); + let here = std::mem::replace(&mut self.cur, at); + let index = self.uniform_heap_index(arg, sampler); + self.cur = here; + incoming.push((index?, at)); + } + let join = self.block[*block].ok_or("a descriptor chosen by control flow")?; + let phi = self.s.m.phi(join, self.s.t.i32); + self.s.m.set_phi(phi, incoming); + Ok(phi) + } + _ => Err("a descriptor chosen by control flow"), + } + } + /// The heap index of a descriptor that may differ between lanes, /// computed in the current block (or, chosen by control flow, at the /// join). @@ -10442,6 +10453,59 @@ mod tests { } } + #[test] + fn descriptors_joined_by_nested_control_flow_lower_to_one_uniform_handle() { + // The view table at s0 (2D textures at entries 0 and 1, a raw UAV at + // dword 16) and a root constant at s1: entry 0 if s1 is 0, else + // entry 1 if it is 1, else entry 0 again, the inner if/else joined + // before the outer one. The join's edges are a load and a join. + let words = [ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0A02, + 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 + 0xBE88_03FF, + 0x0000_0092, // s_mov_b32 s8, 0x92 (an immediate sampler) + 0xBE89_0380, // s_mov_b32 s9, 0 + 0xBE8A_0380, // s_mov_b32 s10, 0 + 0xBE8B_0380, // s_mov_b32 s11, 0 + 0xBF06_8001, // s_cmp_eq_u32 s1, 0 + 0xBF84_0003, // s_cbranch_scc0 -> 0x38 + 0xF40C_0302, + 0xFA00_0000, // s_load_dwordx8 s[12:19], s[4:5], 0x0 + 0xBF82_0008, // s_branch -> 0x58 + 0xBF06_8101, // 0x38: s_cmp_eq_u32 s1, 1 + 0xBF84_0003, // s_cbranch_scc0 -> 0x4c + 0xF40C_0302, + 0xFA00_0020, // s_load_dwordx8 s[12:19], s[4:5], 0x20 + 0xBF82_0002, // s_branch -> 0x54 + 0xF40C_0302, + 0xFA00_0000, // 0x4c: s_load_dwordx8 s[12:19], s[4:5], 0x0 + 0xBE86_0301, // 0x54: s_mov_b32 s6, s1 + 0x7E04_02F0, // 0x58: v_mov_b32 v2, 0.5 + 0x7E06_02F0, // v_mov_b32 v3, 0.5 + 0x3420_0082, // v_lshlrev_b32 v16, 2, v0 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xF09C_0F08, + 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xE070_1000, + 0x800A_0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen + S_ENDPGM, + ]; + let (_, mut used) = texture_and_uav_tables(); + used.retain(|u| u.user_data == 0); + let layout = vec![root(RootType::Table, 0, 0), root(RootType::Constants, 1, 1)]; + let l = lower_with(&words, layout, used).unwrap(); + // One image handle from the joins' heap index, the same in all lanes. + assert_eq!(l.nonuniform_handles, 0); + if let Ok(mut v) = super::super::validator::Validator::load( + super::super::validator::Validator::default_path().as_deref(), + ) { + v.validate(&mut l.dxil.clone()) + .expect("DXIL validation failed"); + } + } + #[test] fn scalar_bit_tests_lower() { // Each tests one bit of a constant into SCC and branches on it (only From ff4746389a03595fecd2a5cb69e8db43ae1c532d Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 03:29:12 +0100 Subject: [PATCH 28/83] Shaders: a descriptor no lane brings along an edge needs no source there A uniform descriptor joined at a block was traced along every predecessor edge, so an edge no lane takes stopped it with the registers it would bring: `indirect_light_probes:CS_Alpha_Schedule` and `alphaResolve:CS_AlphTransmissionPrefilterMip` load a texture under the lanes that ran before `s_wqm` and skip the load when there are none; in compute every lane runs from the start, so nothing takes the skip, but the skip edge's stale input SGPRs made "a descriptor neither loaded nor built". `resource.rs` now gives such an edge (structurisation's lane conditions: the edge's reach and branch condition cannot hold) a taken edge's source, and lowering joins a 0 heap index there (`never_taken`, the same test), so nothing is computed on an edge no lane runs. Test: `a_descriptor_skipped_only_by_lanes_that_never_run_needs_no_source` (the `s_wqm` / `s_and_saveexec` / skipped load / sample shape; refused without the change). Shader list against `main`: 0 newly failing; `CS_AlphTransmissionPrefilterMip` and `shadowmask:CS_TraceShadowRays_ScreenSpaceOnlyCheckerboard` emit, `CS_Alpha_Schedule` stops later ("an address into a descriptor heap with an untracked high half": the address's high half is set inside the same skipped region). Co-Authored-By: Claude Opus 5.5 --- crates/victory-shader/src/emit/lower.rs | 54 ++++++++++++++++++++++++ crates/victory-shader/src/resource.rs | 55 +++++++++++++++++++------ 2 files changed, 97 insertions(+), 12 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index bb56c6b4c8..7f4b353fe0 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -5065,6 +5065,12 @@ impl<'a> Lower<'a> { } let tail = self.tail[q].ok_or("a descriptor chosen by control flow")?; let at = self.edges.get(&(q, *block)).copied().unwrap_or(tail); + // No lane comes this way (`resource` gave it another + // edge's source): any index will do. + if self.never_taken(q, *block) { + incoming.push((self.s.m.i32(0), at)); + continue; + } let here = std::mem::replace(&mut self.cur, at); let index = self.uniform_heap_index(arg, sampler); self.cur = here; @@ -10453,6 +10459,54 @@ mod tests { } } + #[test] + fn a_descriptor_skipped_only_by_lanes_that_never_run_needs_no_source() { + // As `indirect_light_probes:CS_Alpha_Schedule`: the texture is + // loaded under the lanes that ran before `s_wqm`, skipped when there + // are none, and sampled with the helper lanes after the join. With + // every lane running from the start nothing takes the skip, so the + // registers it would bring (no descriptor) are never read. + let words = [ + 0xBE9A_037E, // s_mov_b32 s26, exec_lo + 0xBEFE_097E, // s_wqm_b32 exec_lo, exec_lo + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0A02, + 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 + 0xBE86_3C1A, // s_and_saveexec_b32 s6, s26 + 0xBF88_0002, // s_cbranch_execz -> join + 0xF40C_0302, + 0xFA00_0000, // s_load_dwordx8 s[12:19], s[4:5], 0x0 + 0xBEFE_0306, // join: s_mov_b32 exec_lo, s6 + 0xBE88_03FF, + 0x0000_0092, // s_mov_b32 s8, 0x92 (an immediate sampler) + 0xBE89_0380, // s_mov_b32 s9, 0 + 0xBE8A_0380, // s_mov_b32 s10, 0 + 0xBE8B_0380, // s_mov_b32 s11, 0 + 0x7E04_02F0, // v_mov_b32 v2, 0.5 + 0x7E06_02F0, // v_mov_b32 v3, 0.5 + 0x3420_0082, // v_lshlrev_b32 v16, 2, v0 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xF09C_0F08, + 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0xE070_1000, + 0x800A_0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen + S_ENDPGM, + ]; + let (_, mut used) = texture_and_uav_tables(); + used.retain(|u| u.user_data == 0); + let layout = vec![root(RootType::Table, 0, 0)]; + let l = lower_with(&words, layout, used).unwrap(); + assert_eq!(l.nonuniform_handles, 0); + if let Ok(mut v) = super::super::validator::Validator::load( + super::super::validator::Validator::default_path().as_deref(), + ) { + v.validate(&mut l.dxil.clone()) + .expect("DXIL validation failed"); + } + } + #[test] fn descriptors_joined_by_nested_control_flow_lower_to_one_uniform_handle() { // The view table at s0 (2D textures at entries 0 and 1, a raw UAV at diff --git a/crates/victory-shader/src/resource.rs b/crates/victory-shader/src/resource.rs index 2f8b162c0b..0c820642f3 100644 --- a/crates/victory-shader/src/resource.rs +++ b/crates/victory-shader/src/resource.rs @@ -1161,22 +1161,53 @@ impl<'a> Tracer<'a> { } joins.push(block); let phis = &self.p.blocks[block].phis; - let args = (0..self.p.blocks[block].preds.len()) - .map(|j| { - let edge: Vec = words - .iter() - .map(|w| match phi_of(w) { - Some((_, i)) => self.origin(phis[i].args[j]), - None => *w, - }) - .collect(); - self.classify(&edge, joins, known) - }) - .collect::>(); + let preds = &self.p.blocks[block].preds; + // An edge no lane takes (a skip only helper lanes would take, say) + // brings nothing a lane reads: it takes a taken edge's source, and + // lowering joins no value there (`never_taken`). + let taken: Vec = preds.iter().map(|&q| self.edge_taken(q, block)).collect(); + let edge = |j: usize, joins: &mut Vec, known: &mut Known| { + let edge: Vec = words + .iter() + .map(|w| match phi_of(w) { + Some((_, i)) => self.origin(phis[i].args[j]), + None => *w, + }) + .collect(); + self.classify(&edge, joins, known) + }; + let args = match taken.iter().position(|&t| t) { + Some(first) if taken.contains(&false) => edge(first, joins, known).and_then(|live| { + (0..preds.len()) + .map(|j| if taken[j] { edge(j, joins, known) } else { Ok(live.clone()) }) + .collect::>() + }), + _ => (0..preds.len()).map(|j| edge(j, joins, known)).collect::>(), + }; joins.pop(); Ok(Some(Source::Phi { block, args: args? })) } + /// Whether some lane goes from block `q` to `b` (true without the + /// lanes' paths): `Lower::never_taken`'s test. + fn edge_taken(&self, q: usize, b: usize) -> bool { + let Some(lanes) = self.lanes else { + return true; + }; + let mut edge = vec![(lanes.reach[q], true)]; + if let LaneExit::Branch { + when, + taken, + not_taken, + } = lanes.exits[q] + && taken != not_taken + { + edge.push((when, taken == b)); + } + // The very test lowering makes, so both drop the same edges. + lanes.bools.meet(&edge) + } + /// Words that `s_cselect` (or `s_cmov`) picks by one SCC value, traced /// per outcome (other words are the same for both). fn select( From e8e9f0c2aef95f2d3940ec05ec687fde2b839d19 Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 03:29:12 +0100 Subject: [PATCH 29/83] Shaders: a lane mask joined with data at a uniform join is its number The title's wave-uniform BVH walks (`shadowmask:CS_TraceShadowRays_ Checkerboard`, `deferred_tiled:CS_LaserLightShadowRaytracing`, the four `rtdirectionalshadows:CS_RTDistantShadow*_Tiled`) keep the lanes of the node being visited in an SGPR: a lane mask on entry, a number popped from an LDS stack (`v_readfirstlane_b32`) on the loop's back edges, read both as a number (`v_and_b32` with the lane's bit, `s_cmp`) and as a mask. The join was refused: "a register joining a lane mask and data, read as data" (40 programs), then "a lane-mask join of an untracked mask". At a join where every branch in is uniform (SCC), every lane comes along the edge the console's wave took, so the register holds that edge's value. In compute (console lanes) a mask's number on its edge is its ballot there (`mask_dword`), exact; read as a mask, a number gives each lane its own bit (`lane_bit`, as `Atom::Opaque` does). A per-lane branch into the join (an EXEC skip, a per-lane loop exit: where lanes would take edges the wave did not; the console compiler's if/else always enters its join that way) keeps the refusal. Tests: `a_mask_joined_with_data_needs_a_uniform_join` (the per-lane loop still refused, the uniform one lowers); `synthetic_tests::a_mask_joined_with_data_at_a_uniform_loop_is_its_number` (a mask shifted through a VGPR around a uniform loop, read as a number and as each lane's bit; values checked on the GPU, hardware and WARP; fails without each half of the change). Shader list against `main`: 0 newly failing, 29 newly emit; all 40 "a register joining a lane mask and data" programs pass it (16 stop at a later mask join). Co-Authored-By: Claude Opus 5.5 --- crates/victory-shader/src/emit/lower.rs | 78 ++++++++++++++++-- .../src/emit/synthetic_tests.rs | 79 +++++++++++++++++++ 2 files changed, 152 insertions(+), 5 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 7f4b353fe0..1096ec7e81 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -7594,6 +7594,25 @@ impl<'a> Lower<'a> { all } + /// Whether every lane enters IR block `b` along the edge the console's + /// wave takes, so that an SGPR joined there holds what that edge + /// brought: every branch into it is uniform (SCC values). The wave runs + /// one path; a per-lane branch into the join (an EXEC skip, a loop's + /// per-lane exit) is where lanes would take edges the wave did not, and + /// the console compiler's if/else always skips into its join that way. + /// Lanes that left EXEC inside a uniform loop (the BVH walks) take no + /// edge into its header; the others take the wave's. + fn uniform_join(&self, b: usize) -> bool { + let st = self.x.st; + let preds = &self.x.p.blocks[b].preds; + preds.iter().filter(|&&q| self.block[q].is_some()).all(|&q| match st.exits[q] { + LaneExit::Branch { when, taken, not_taken } if taken != not_taken => { + st.bools.support(when).iter().all(|a| matches!(a, Atom::Uniform(_))) + } + _ => true, + }) + } + /// Whether no lane goes from IR block `q` to `b`. fn never_taken(&self, q: usize, b: usize) -> bool { !self.x.st.bools.meet(&self.lane_edge(q, b)) @@ -9887,6 +9906,17 @@ impl<'a> Lower<'a> { (Some(Val::Bit(_)), false) if read => { return Err(Stop::Retry(phi.value, "an SCC joined with SGPR values")); } + // A lane mask joined with data at a join every lane + // enters along one edge: the register holds the mask's + // number there (console lanes, so exact). + _ if read + && !bit + && self.mask_data == MaskData::Console + && (self.x.st.masks.contains_key(&arg) || self.x.st.highs.contains_key(&arg)) + && self.uniform_join(b) => + { + self.mask_dword(arg).map_err(|w| Stop::Retry(phi.value, w))? + } (Some(Val::Missing(why)), _) if read => { return Err(Stop::Retry(phi.value, why)); } @@ -9910,11 +9940,17 @@ impl<'a> Lower<'a> { for (n, &q) in p.blocks[b].preds.iter().enumerate() { let Some(qb) = self.tail[q] else { continue }; let qb = self.edges.get(&(q, b)).copied().unwrap_or(qb); - let m = - *self.x.st.masks.get(&phi.args[n]).ok_or_else(|| { - unsupported(offset, "a lane-mask join of an untracked mask") - })?; - let x = self.boolean(m, qb).map_err(|w| unsupported(offset, w))?; + let arg = phi.args[n]; + const UNTRACKED: Why = "a lane-mask join of an untracked mask"; + // Data joined with masks where the wave takes one edge (the BVH + // walks pop masks from memory): with console lanes the lane's + // own bit of the number, as `Atom::Opaque`. + let number = self.console_lanes && !self.x.native.wave64 && self.uniform_join(b); + let x = match (self.x.st.masks.get(&arg), self.vals.get(&arg)) { + (Some(&m), _) => self.boolean(m, qb).map_err(|w| unsupported(offset, w))?, + (None, Some(&Val::I32(word))) if number => self.lane_bit(qb, word, None), + (None, _) => return Err(unsupported(offset, UNTRACKED)), + }; incoming.push((x, qb)); } self.s.m.set_phi(v, incoming); @@ -10653,6 +10689,38 @@ mod tests { assert_eq!(refusal(&words), refusal(&direct)); } + #[test] + fn a_mask_joined_with_data_needs_a_uniform_join() { + // s6: lanes below 24, then shifted (data) on each back edge; read + // after the loop. Lanes leaving the loop at different iterations + // (per lane) see different numbers than the console's register: + // refused. The uniform loop is `synthetic_tests:: + // a_mask_joined_with_data_at_a_uniform_loop_is_its_number`. + let mut words = [ + 0x7D88_0098, // v_cmp_gt_u32 vcc_lo, 24, v0 + 0x8706_7E6A, // s_and_b32 s6, vcc_lo, exec_lo + 0xBE87_0380, // s_mov_b32 s7, 0 + 0x9006_8406, // header: s_lshr_b32 s6, s6, 4 + 0x8007_8107, // s_add_u32 s7, s7, 1 + 0x7D88_0007, // v_cmp_gt_u32 vcc_lo, s7, v0 + 0x8A7E_6A7E, // s_andn2_b32 exec_lo, exec_lo, vcc_lo + 0xBF89_FFFB, // s_cbranch_execnz header + 0xBF07_8006, // s_cmp_lg_u32 s6, 0 + 0xBF85_0001, // s_cbranch_scc1 +1 + 0xBE84_0380, // s_mov_b32 s4, 0 + S_ENDPGM, + ]; + let Err(crate::ShaderError::Unsupported { what, .. }) = lowers(&words, 1 << 7) else { + panic!("a per-lane loop's mask join translated"); + }; + assert!(what.contains("lane mask"), "{what}"); + // Leaving on a uniform condition instead: the mask's number. + words[5] = 0xBF0A_8207; // s_cmp_lt_u32 s7, 2 + words[6] = 0xBF80_0000; // s_nop 0 + words[7] = 0xBF85_FFFB; // s_cbranch_scc1 header + lowers(&words, 1 << 7).expect("a uniform loop's mask join"); + } + #[test] fn a_missing_value_on_a_path_no_lane_takes_is_dead() { let refusal = |code: &[u32]| match lowers(code, 1 << 7) { diff --git a/crates/victory-shader/src/emit/synthetic_tests.rs b/crates/victory-shader/src/emit/synthetic_tests.rs index 990a3e5942..691f7e1702 100644 --- a/crates/victory-shader/src/emit/synthetic_tests.rs +++ b/crates/victory-shader/src/emit/synthetic_tests.rs @@ -359,6 +359,85 @@ fn permutes_read_the_lane_named_and_zero_from_lanes_left_out() { } } +/// A lane mask joined with data at a uniform loop's header, as the title's +/// wave-uniform BVH walks push lane masks to memory and pop them +/// (`shadowmask:CS_TraceShadowRays_Checkerboard`): the register holds the +/// mask on entry and a number from the back edge, read both as a number and +/// as a mask. +#[test] +fn a_mask_joined_with_data_at_a_uniform_loop_is_its_number() { + // s6 = lanes below 24, shifted right by 4 and passed through a VGPR in + // each of two iterations; v4 takes each lane's bit of it on every pass. + let shader = build(&[ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0A02, + 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0x3420_0082, // v_lshlrev_b32 v16, 2, v0 + 0x7D88_0098, // v_cmp_gt_u32 vcc_lo, 24, v0 + 0x8706_7E6A, // s_and_b32 s6, vcc_lo, exec_lo + 0xBE87_0380, // s_mov_b32 s7, 0 + 0xD501_0004, + 0x0019_0280, // header: v_cndmask_b32 v4, 0, 1, s6 + 0x9006_8406, // s_lshr_b32 s6, s6, 4 + 0x7E0A_0206, // v_mov_b32 v5, s6 + 0x7E0C_0505, // v_readfirstlane_b32 s6, v5 + 0x8007_8107, // s_add_u32 s7, s7, 1 + 0xBF0A_8207, // s_cmp_lt_u32 s7, 2 + 0xBF85_FFF8, // s_cbranch_scc1 header + 0x7E06_0206, // v_mov_b32 v3, s6 + 0xE070_1000, + 0x800A_0310, // buffer_store_dword v3, v16, s[40:43], 0 offen + 0xE070_1080, + 0x800A_0410, // buffer_store_dword v4, v16, s[40:43], 0 offen offset:128 + 0xBF81_0000, // s_endpgm + ]) + .expect("lower"); + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + v.validate(&mut shader.dxil.clone()) + .expect("DXIL validation failed"); + } + let views = [ + View::Texture(1, 1, &[[0.0; 4]]), + View::Buffer { + data: &[0; 4], + stride: Stride::Structured(16), + }, + View::RawUav(64), + ]; + let mut want = vec![0x00FF_FFFF >> 8; 32]; + want.extend((0..32).map(|lane| u32::from(lane < 20))); + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); + for (label, warp) in [("hardware", false), ("warp", true)] { + let Ok(host) = Host::new(warp) else { + eprintln!("no SM 6.6 {label} device; skipped"); + continue; + }; + let Ok((root, pso)) = host.compute_pipeline(&shader) else { + assert!(warp, "{label}: no pipeline for a wave of 32"); + eprintln!("{label}: no pipeline for a wave of 32; skipped"); + continue; + }; + let ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views: &views, + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); + assert_eq!(out[0], want, "{label}"); + } +} + #[test] fn ordered_pixel_sections_use_rasterizer_ordered_views() { // A pixel program's ordered section (POPS) as the title's compiler From fbac5bb64c8e4764eaa1a6d3dc670102ec579378 Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 05:00:19 +0100 Subject: [PATCH 30/83] Shaders: descriptors joined by nested control flow stay refused for now Takes back PR #1012's recursive heap index (an edge into a descriptor's join that is itself a join). Across the title's shader list it lets one program through, `indirect_diffuse_lighting:CS_ScreenProbes_ActivateRays` (issued every cutscene frame), and that program's host pipeline does not fit the machine: the DXIL validates in 4 s, but the AMD driver's compile passed 6 GB after 64 s under a watchdog (unwatched it reached 26.7 GB commit and starved a title run, drops2). Its DXIL has 22,382 branches, 2,609 heap handles and 2,478 size queries (151k lines), against 3,857 branches for the next largest newly emitted program, which compiles in 24 s and 0.8 GB. The refusal is "a descriptor chosen by control flow" again, as on `main`; edges no lane takes still join no heap index (previous commit). The change can come back once pipelines this costly stay off the title's pipeline worker (`shortcut:` at the arm). Co-Authored-By: Claude Opus 5.5 --- crates/victory-shader/src/emit/lower.rs | 125 +++++++----------------- 1 file changed, 34 insertions(+), 91 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 1096ec7e81..d3d6800507 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -4970,10 +4970,41 @@ impl<'a> Lower<'a> { self.s.sampler_choices.push((ha, hb, phi)); Ok(ha) } - Source::Phi { .. } => { + Source::Phi { block, args } => { + // Each predecessor computes its heap index at its end; the + // join picks one with a phi. + // shortcut: an edge that is itself a join (if/else nested in + // another) stays refused: the one program it would let + // through, `indirect_diffuse_lighting:CS_ScreenProbes_ + // ActivateRays` (22k branches, 2.6k heap handles), takes the + // AMD driver over 6 GB and a minute to compile (PR #1012 did + // it; take it once pipelines that costly stay off the title's + // pipeline worker). let _ = site; - let index = self.uniform_heap_index(src, sampler)?; - let index = self.buffer_guard(src, index, sampler, props); + let mut incoming = Vec::new(); + for (&q, arg) in self.x.p.blocks[*block].preds.iter().zip(args) { + if self.block[q].is_none() { + continue; + } + let (Some(tail), Source::Loaded { load, first }) = (self.tail[q], arg) else { + return Err("a descriptor chosen by control flow"); + }; + let at = self.edges.get(&(q, *block)).copied().unwrap_or(tail); + // No lane comes this way (`resource` gave it another + // edge's source): any index will do. + if self.never_taken(q, *block) { + incoming.push((self.s.m.i32(0), at)); + continue; + } + let here = std::mem::replace(&mut self.cur, at); + let index = self.heap_index(*load, *first, sampler); + self.cur = here; + incoming.push((index?, at)); + } + let join = self.block[*block].ok_or("a descriptor chosen by control flow")?; + let phi = self.s.m.phi(join, self.s.t.i32); + self.s.m.set_phi(phi, incoming); + let index = self.buffer_guard(src, phi, sampler, props); Ok(self.s.heap_handle(self.cur, index, sampler, false, props)) } Source::Select { scc, args } => { @@ -5050,41 +5081,6 @@ impl<'a> Lower<'a> { }) } - /// The heap index of a descriptor every lane shares, computed in the - /// current block. One chosen by control flow is a phi at its join of the - /// index each predecessor computes at its end; an edge may bring another - /// join's (nested if/else). - fn uniform_heap_index(&mut self, src: &Source, sampler: bool) -> Result { - match src { - Source::Loaded { load, first } => self.heap_index(*load, *first, sampler), - Source::Phi { block, args } => { - let mut incoming = Vec::new(); - for (&q, arg) in self.x.p.blocks[*block].preds.iter().zip(args) { - if self.block[q].is_none() { - continue; - } - let tail = self.tail[q].ok_or("a descriptor chosen by control flow")?; - let at = self.edges.get(&(q, *block)).copied().unwrap_or(tail); - // No lane comes this way (`resource` gave it another - // edge's source): any index will do. - if self.never_taken(q, *block) { - incoming.push((self.s.m.i32(0), at)); - continue; - } - let here = std::mem::replace(&mut self.cur, at); - let index = self.uniform_heap_index(arg, sampler); - self.cur = here; - incoming.push((index?, at)); - } - let join = self.block[*block].ok_or("a descriptor chosen by control flow")?; - let phi = self.s.m.phi(join, self.s.t.i32); - self.s.m.set_phi(phi, incoming); - Ok(phi) - } - _ => Err("a descriptor chosen by control flow"), - } - } - /// The heap index of a descriptor that may differ between lanes, /// computed in the current block (or, chosen by control flow, at the /// join). @@ -10543,59 +10539,6 @@ mod tests { } } - #[test] - fn descriptors_joined_by_nested_control_flow_lower_to_one_uniform_handle() { - // The view table at s0 (2D textures at entries 0 and 1, a raw UAV at - // dword 16) and a root constant at s1: entry 0 if s1 is 0, else - // entry 1 if it is 1, else entry 0 again, the inner if/else joined - // before the outer one. The join's edges are a load and a join. - let words = [ - 0xBE84_0300, // s_mov_b32 s4, s0 - 0xBE85_0380, // s_mov_b32 s5, 0 - 0xF408_0A02, - 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 - 0xBE88_03FF, - 0x0000_0092, // s_mov_b32 s8, 0x92 (an immediate sampler) - 0xBE89_0380, // s_mov_b32 s9, 0 - 0xBE8A_0380, // s_mov_b32 s10, 0 - 0xBE8B_0380, // s_mov_b32 s11, 0 - 0xBF06_8001, // s_cmp_eq_u32 s1, 0 - 0xBF84_0003, // s_cbranch_scc0 -> 0x38 - 0xF40C_0302, - 0xFA00_0000, // s_load_dwordx8 s[12:19], s[4:5], 0x0 - 0xBF82_0008, // s_branch -> 0x58 - 0xBF06_8101, // 0x38: s_cmp_eq_u32 s1, 1 - 0xBF84_0003, // s_cbranch_scc0 -> 0x4c - 0xF40C_0302, - 0xFA00_0020, // s_load_dwordx8 s[12:19], s[4:5], 0x20 - 0xBF82_0002, // s_branch -> 0x54 - 0xF40C_0302, - 0xFA00_0000, // 0x4c: s_load_dwordx8 s[12:19], s[4:5], 0x0 - 0xBE86_0301, // 0x54: s_mov_b32 s6, s1 - 0x7E04_02F0, // 0x58: v_mov_b32 v2, 0.5 - 0x7E06_02F0, // v_mov_b32 v3, 0.5 - 0x3420_0082, // v_lshlrev_b32 v16, 2, v0 - 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) - 0xF09C_0F08, - 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D - 0xE070_1000, - 0x800A_0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen - S_ENDPGM, - ]; - let (_, mut used) = texture_and_uav_tables(); - used.retain(|u| u.user_data == 0); - let layout = vec![root(RootType::Table, 0, 0), root(RootType::Constants, 1, 1)]; - let l = lower_with(&words, layout, used).unwrap(); - // One image handle from the joins' heap index, the same in all lanes. - assert_eq!(l.nonuniform_handles, 0); - if let Ok(mut v) = super::super::validator::Validator::load( - super::super::validator::Validator::default_path().as_deref(), - ) { - v.validate(&mut l.dxil.clone()) - .expect("DXIL validation failed"); - } - } - #[test] fn scalar_bit_tests_lower() { // Each tests one bit of a constant into SCC and branches on it (only From f342dcfcfba9f78a5783a3b2089f758d0728754b Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 05:20:41 +0100 Subject: [PATCH 31/83] Shaders: inputs a counted v_movreld loop overwrites first need no value `PS_DownSampleBloomFilter(Karis)_557ae3d7` (the bloom downsample, 3 draws a frame in the intro cutscene) fills a register array v0.. with `v_movreld` in a uniform loop counted from a constant start to an `eq` bound. v0/v1 hold the raw barycentrics on entry, which have no host form ("barycentrics read directly"), so the loop header's phi refused the program although no lane ever reads those values: the loop's first passes overwrite them. PR #457's proof, ported onto the current lowering: the loop-carried register's only use is the unguarded `v_movreld` at index M0, M0 a copy of a scalar phi starting at a constant and stepping by 1 to an `s_cmp_eq` bound that exits through the one exit block; the register's slot lies in [start, bound), so the move writes it before anything can read it, and the entry edge's value is undefined. Every other shape keeps the refusal (the PR's 15-case test: wrong start, skipped slot, decrement, wrap, unknown start, short loop, clobbered SCC, early or divergent exit, masked write, old value as source, reads before the write or on the back edge). Shader list against f6cd0144: 0 newly failing; `PS_DownSampleBloomFilter Karis_557ae3d7` and `PS_DownSampleBloomFilter_557ae3d7` emit, validate and make pipelines (1-2 s, under 0.1 GB). Ported from PR #457 (efcd753a, 08b681c2, Jeremy Goldberg): the fill-phis arm now takes the edge's liveness from `live_edges`. Co-Authored-By: Claude Opus 5.5 --- crates/victory-shader/src/emit/lower.rs | 208 +++++++++++++++++++++++- crates/victory-shader/src/emit/mod.rs | 174 ++++++++++++++++++++ 2 files changed, 381 insertions(+), 1 deletion(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index d3d6800507..d014a85684 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -15,7 +15,7 @@ use super::shader::{Shader, VIEW_STRIDES, flags}; use crate::ShaderError; use crate::gfx10::{Dpp, Fields, NULL, Operand}; use crate::io::{Barycentric, Elsewhere, Export, Input, Interp, Io, Target}; -use crate::ir::{EXEC, Exit, Inst, Program, Reg, Value}; +use crate::ir::{Block, EXEC, Exit, Inst, Phi, Program, Reg, Value}; use crate::native::{HwStage, NativeProgram, ResourceType, RootType, StageIo, Usage, UsedResource}; use crate::resource::{Address, CODE, MEMORY, Resources, Role, Site, Source, USER_DATA}; use crate::structure::{Atom, Bool, LaneExit, Structured}; @@ -455,6 +455,40 @@ fn unsupported(offset: usize, what: Why) -> Stop { Stop::Fail(ShaderError::Unsupported { offset, what }) } +/// The scalar instruction defining an SSA value in this block and its operands. +fn scalar_def<'a, const N: usize>( + block: &'a Block, + value: Value, + op: &str, +) -> Option<(&'a Inst, [Operand; N])> { + let inst = block + .insts + .iter() + .find(|i| i.writes.iter().any(|w| w.1 == value))?; + let Fields::Sop { src, .. } = &inst.fields else { + return None; + }; + (inst.name() == op).then_some((inst, src.as_slice().try_into().ok()?)) +} + +fn sgpr_operand(inst: &Inst, operand: Operand) -> Option { + match operand { + Operand::Scalar { + code: code @ 0..=101, + dwords: 1, + } => inst.read(Reg::S(code)), + _ => None, + } +} + +fn scalar_constant(operand: Operand) -> Option { + match operand { + Operand::Const(code) => crate::resource::inline(code), + Operand::Literal(value) => Some(value), + _ => None, + } +} + /// The dwords an `s_load_dword*` reads. fn smem_dwords(name: &str) -> Option { match name.strip_prefix("s_load_dword")? { @@ -9874,6 +9908,171 @@ impl<'a> Lower<'a> { live } + /// An unguarded indexed write replaces the incoming value before a + /// consumer can observe it, either on this edge or in a counted loop. + fn overwritten_movreld_edge(&self, b: usize, phi: &Phi, edge: usize) -> Option<()> { + let Reg::V(reg) = phi.reg else { return None }; + let p = self.x.p; + let block = &p.blocks[b]; + if self.sections.contains_key(&b) + || self.sections.contains_key(&block.preds[edge]) + || p.blocks + .iter() + .flat_map(|bb| &bb.phis) + .any(|ph| ph.args.contains(&phi.value)) + { + return None; + } + let mut uses = p.blocks.iter().enumerate().flat_map(|(bb, block)| { + block.insts.iter().enumerate().filter_map(move |(i, inst)| { + inst.reads + .iter() + .any(|r| r.1 == phi.value) + .then_some((bb, i, inst)) + }) + }); + let (bb, i, mov) = uses.next()?; + if uses.next().is_some() + || bb != b + || self.x.st.guards[b][i].is_some() + || mov.name() != "v_movreld_b32" + || mov.read(phi.reg) != Some(phi.value) + { + return None; + } + let Fields::Valu(v) = &mov.fields else { + return None; + }; + let ( + Some(Operand::Vector { + reg: base, + dwords: 1, + }), + [ + Operand::Vector { + reg: src, + dwords: 1, + }, + ], + ) = (v.dst, v.src.as_slice()) + else { + return None; + }; + if v.dpp.is_some() + || v.sdwa.is_some() + || mov.read(Reg::V(*src))? == phi.value + || mov.write(phi.reg).is_none() + { + return None; + } + let index = u32::from(reg.checked_sub(base)?); + // Follow M0 to a copy of a scalar phi in this block, then the + // constant written on the corresponding predecessor. + let (copy, [src]) = scalar_def(block, mov.read(Reg::S(crate::ir::M0))?, "s_mov_b32")?; + let scalar = sgpr_operand(copy, src)?; + let index_phi = block.phis.iter().find(|ph| ph.value == scalar)?; + let (_, [initial]) = scalar_def( + &p.blocks[block.preds[edge]], + index_phi.args[edge], + "s_mov_b32", + )?; + let known = scalar_constant(initial)?; + if index == known { + return Some(()); + } + if index < known { + return None; // Reaching this slot would require the index to wrap. + } + self.counted_movreld_index(b, edge, phi, index_phi, mov, index) + } + + /// An unguarded move fills one more register on every iteration. + /// Values from before the loop can only survive in slots the index skips. + fn counted_movreld_index( + &self, + b: usize, + edge: usize, + phi: &Phi, + indices: &Phi, + mov: &Inst, + slot: u32, + ) -> Option<()> { + let p = self.x.p; + let st = self.x.st; + let block = &p.blocks[b]; + let LaneExit::Branch { + when, + taken: latch, + not_taken: exit, + } = st.exits[b] + else { + return None; + }; + let back = block.preds.iter().position(|&q| q == latch)?; + if block.preds.len() != 2 + || back == edge + || b == latch + || b == exit + || exit == latch + || self.sections.contains_key(&latch) + || st.exits[latch] != LaneExit::Jump(b) + || p.blocks[latch].preds != [b] + || p.blocks[exit].preds != [b] + || st.exits[exit] != LaneExit::End + || self.rpo[b] >= self.rpo[latch] + || self.rpo[block.preds[edge]] >= self.rpo[b] + { + return None; + } + // The indexed result may only go around the loop as its own old + // value or be consumed in the normal exit block. + let result = mov.write(phi.reg)?; + if phi.args[back] != result { + return None; + } + for (bb, block) in p.blocks.iter().enumerate() { + if bb != exit + && block + .insts + .iter() + .any(|inst| inst.reads.iter().any(|r| r.1 == result)) + { + return None; + } + if block.phis.iter().any(|other| { + other + .args + .iter() + .enumerate() + .any(|(n, &arg)| arg == result && (other.value != phi.value || n != back)) + }) { + return None; + } + } + // Follow the latch copy to the unit increment, then require that + // this very increment is compared for equality to the exit bound. + let (copy, [src]) = scalar_def(&p.blocks[latch], indices.args[back], "s_mov_b32")?; + let next = sgpr_operand(copy, src)?; + let (increment, [from, step]) = scalar_def(block, next, "s_add_i32")?; + if sgpr_operand(increment, from)? != indices.value || scalar_constant(step)? != 1 { + return None; + } + let (Atom::Uniform(scc), Bool::TRUE, Bool::FALSE) = st.bools.node(when)? else { + return None; + }; + let branch = block.insts.last()?; + if branch.name() != "s_cbranch_scc0" || branch.read(Reg::Scc) != Some(scc) { + return None; + } + let (cmp, [tested, bound]) = scalar_def(block, scc, "s_cmp_eq_u32")?; + if sgpr_operand(cmp, tested)? != next { + return None; + } + let limit = scalar_constant(bound)?; + // The initial index is below this slot. The loop must pass it before exit. + (slot < limit).then_some(()) + } + fn fill_phis(&mut self) -> Result<(), Stop> { let p = self.x.p; let live = self.live_edges(); @@ -9899,6 +10098,13 @@ impl<'a> Lower<'a> { self.s.m.i32(0) } } + // An input an unguarded counted `v_movreld` loop overwrites + // before anything reads it (PR #457). + (Some(Val::Missing("barycentrics read directly")), false) + if read && self.overwritten_movreld_edge(b, phi, n).is_some() => + { + self.s.m.undef(self.s.t.i32) + } (Some(Val::Bit(_)), false) if read => { return Err(Stop::Retry(phi.value, "an SCC joined with SGPR values")); } diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 4e1fb2f92c..43397e695b 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -634,6 +634,180 @@ mod tests { use super::*; use crate::native::{ComputeIo, StageIo}; + #[test] + fn indexed_move_initializes_an_input_before_its_first_use() { + #[derive(Debug, Clone, Copy, PartialEq, Eq)] + enum Case { + Complete, + NonzeroBase, + WrongStart, + SkippedSlot, + Decrement, + Wrap, + UnknownStart, + ShortLoop, + ClobberedScc, + EarlyExit, + DivergentExit, + MaskedWrite, + SourceIsOld, + ReadBeforeWrite, + ReadOnBackedge, + } + use Case::*; + + // A two-block do-while loop writes v[M0] from v2, then exports v1. + // On the first two passes M0 selects v0 and v1 respectively. Both + // registers initially contain raw perspective-center barycentrics. + let words = |case| { + let init = match case { + WrongStart => 0xbe80_0382, // s_mov_b32 s0, 2 + Wrap => 0xbe80_03c1, // s_mov_b32 s0, -1 + UnknownStart => 0x8000_8080, // s_add_u32 s0, 0, 0 + _ => 0xbe80_0380, // s_mov_b32 s0, 0 + }; + let mut w = vec![init, 0x7e04_0281, 0xbf82_0000]; // v_mov_b32 v2, 1; s_branch header + let latch = w.len(); + if case == EarlyExit { + w.extend([0xbf06_8000, 0xbf85_0000]); // s_cmp_eq_u32 s0, 0; s_cbranch_scc1 exit + } + w.push(0xbe80_0302); // s_mov_b32 s0, s2 + let header = w.len(); + w[2] |= (header - 3) as u32; + w.push(0xbefc_0300); // s_mov_b32 m0, s0 + w.push(match case { + SkippedSlot => 0x8102_8200, // s_add_i32 s2, s0, 2 + Decrement => 0x8102_c100, // s_add_i32 s2, s0, -1 + _ => 0x8102_8100, // s_add_i32 s2, s0, 1 + }); + if case == ReadBeforeWrite { + w.push(0x7e06_0301); + } // v_mov_b32 v3, v1 + if case == MaskedWrite { + w.extend([0x7d84_0480, 0xbe84_3c6a]); // v_cmp_eq_u32 vcc, 0, v2; s_and_saveexec_b32 s4, vcc_lo + } + w.push(match case { + SourceIsOld => 0x7e00_8501, // v_movreld_b32 v0, v1 + NonzeroBase => 0x7e02_8502, // v_movreld_b32 v1, v2 + _ => 0x7e00_8502, // v_movreld_b32 v0, v2 + }); + if case == MaskedWrite { + w.push(0x887e_047e); + } // s_or_b32 exec_lo, exec_lo, s4 + if case == ReadOnBackedge { + w.push(0x7e06_0301); + } // v_mov_b32 v3, v1 + let branch = if case == DivergentExit { + w.push(0x7d84_0480); // v_cmp_eq_u32 vcc, 0, v2 + 0xbf87_0000 // s_cbranch_vccnz latch + } else { + w.push(if matches!(case, ShortLoop | NonzeroBase) { + 0xbf06_8102 + } else { + 0xbf06_8402 + }); // s_cmp_eq_u32 s2, 1/4 + if case == ClobberedScc { + w.push(0xbf06_8000); // s_cmp_eq_u32 s0, 0 exits on the first pass + } + 0xbf84_0000 // s_cbranch_scc0 latch + }; + let rel = latch as i32 - (w.len() as i32 + 1); + w.push(branch | u32::from(rel as u16)); + let exit = w.len(); + if case == EarlyExit { + w[latch + 1] |= (exit - latch - 2) as u32; + } + let output = if matches!(case, ReadBeforeWrite | ReadOnBackedge) { + 3 + } else { + 1 + }; + w.extend([0xf800_1801, output, 0xbf81_0000]); // exp mrt0.x done vm; s_endpgm + w + }; + let target = SigElement { + name: "SV_Target".into(), + index: 0, + kind: 16, + comp: 9, + interp: 0, + row: Some(0), + col: 0, + cols: 1, + usage: 1, + half: false, + }; + let sig = super::container::signature(&[target], false); + let bytes = crate::dxbc::build(&[(FourCC::OSG1, &sig)]); + let c = Container::parse(&bytes).unwrap(); + for case in [ + Complete, + NonzeroBase, + WrongStart, + SkippedSlot, + Decrement, + Wrap, + UnknownStart, + ShortLoop, + ClobberedScc, + EarlyExit, + DivergentExit, + MaskedWrite, + SourceIsOld, + ReadBeforeWrite, + ReadOnBackedge, + ] { + let native = NativeProgram { + stage: HwStage::Ps, + wave64: false, + vgprs: 4, + layout: vec![], + used: vec![], + io: StageIo::Ps { + inputs: vec![], + input_addr: 2, + db_shader_control: 0, + patches: vec![], + }, + code: words(case).iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap(); + let st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); + let io = io::raise(&p, &native).unwrap(); + let shader = emit(&c, &native, &p, &st, &io, &res); + if matches!(case, Complete | NonzeroBase) { + let shader = shader.unwrap(); + assert!( + Container::parse(&shader.dxil) + .unwrap() + .part(FourCC::DXIL) + .is_some() + ); + #[cfg(windows)] + if let Ok(mut validator) = + validator::Validator::load(validator::Validator::default_path().as_deref()) + { + let mut dxil = shader.dxil; + validator.validate(&mut dxil).unwrap(); + eprintln!("synthetic {case:?} SDK valid bytes={}", dxil.len()); + } + } else { + eprintln!("synthetic {case:?} {:?}", shader.as_ref().err()); + assert!( + matches!( + shader, + Err(ShaderError::Unsupported { + what: "barycentrics read directly", + .. + }) + ), + "{case:?}" + ); + } + } + } + /// A pixel shader writing SV_StencilRef (channel y of `exp mrtz`). /// DXC sets ShaderFlags.StencilRef (bit 11) for a pixel shader whose /// output signature has SV_StencilRef, and the feature bit From eed1670036475ea86595ef5e5837a6ca4d5391bf Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 04:27:29 +0100 Subject: [PATCH 32/83] GPU: a listed frame's trace shows the title's barrier calls Diagnostics only. The trace of a listed frame named every command but not the barriers between them, so whether the title orders two dependent dispatches could not be read from it. Each barrier call now notes itself in its list: the enhanced form as its groups' (kind, count) pairs (0 global, 1 texture, 2 buffer), the legacy form as its barriers' kinds. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/list.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 80bc2baabc..75c383fa25 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -372,6 +372,8 @@ extern "system" fn barrier(this: This, count: u32, barriers: *const Barrier) -> { // SAFETY: the title passes `count` barriers. let barriers = unsafe { std::slice::from_raw_parts(barriers, count as usize) }; + #[cfg(feature = "diagnostics")] + list.note_op(|| format!("barrier kinds {:?}", barriers.iter().map(|b| b.kind).collect::>())); let mut host: Vec = barriers .iter() .filter_map(|b| host_barrier(list, b)) @@ -1499,6 +1501,13 @@ extern "system" fn barrier_groups(this: This, count: u32, _groups: *const u8) { && let Some(list) = host_list(this) { use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_BARRIER; + // Which kinds of barriers (0 global, 1 texture, 2 buffer) and how many. + #[cfg(feature = "diagnostics")] + if !_groups.is_null() { + // SAFETY: the title passes `count` groups of 16 bytes: kind, count, pointer. + let groups = unsafe { std::slice::from_raw_parts(_groups.cast::<[u32; 4]>(), count as usize) }; + list.note_op(|| format!("barrier groups {:?}", groups.iter().map(|g| (g[0], g[1])).collect::>())); + } // SAFETY: the same layout; no resource named. let barrier = unsafe { std::mem::transmute::(UAV_BARRIER) }; // SAFETY: an open list. From 4243a96a787a63cdc4ac943c88867fbc0631f12c Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 04:45:10 +0100 Subject: [PATCH 33/83] Shader: 16-bit typed buffer accesses pass bits through integer views On GFX10 a typed buffer access converts by the buffer format of its descriptor, and `_d16` only packs the 16-bit results: through a UINT or SINT view, `buffer_load_format_d16_*` and `buffer_store_format_d16_*` move the 16-bit integers as they are. The lowering always converted them as halves (f32 to f16 on loads, f16 to f32 on stores) through a float-typed handle, so through an integer view a store wrote a float's bit pattern into the 16-bit element and a load turned the integer's bits into a denormal and then to 0. Grand Theft Auto VI's compute graph (the 65 compute_graph_ops programs: the face network's matrix products, activations, reductions, copies; the only users of these accesses in the title's world set) keeps its halves in R16G16B16A16_UINT and R16_UINT views. Its output was bit soup that changed from frame to frame (shards6: 0x0011 0x0001 0x0015 0x006D 0x80EC ... at frame 1658, 0xD8A8 0xA388 0x2F30 0x0472 ... at 1670 in the same place), the blendshape extract turned that into the head's translations, and the main character's head came out as a flat slab or not at all. The view's format kind now rides in the view-stride table, beside the stride: bit 31 an integer format, bit 30 a signed one (VIEW_INTEGER, VIEW_SIGNED; stride readers mask them off). The host sets them for typed buffer views of UINT and SINT formats. A d16 typed load through such a view keeps each channel's low 16 bits; a d16 typed store zero- or sign-extends the 16-bit integer. Float, normalized, raw and structured views keep the conversion they had. The integer path still uses the float-typed handle and relies on the driver passing a mismatched component type's bits through (shortcut comment; checked on the RX 6700 XT and WARP by the new tests). RESULTS Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor/host.rs | 71 ++++++- crates/victory-shader/src/emit/host.rs | 8 +- crates/victory-shader/src/emit/lower.rs | 78 +++++++- crates/victory-shader/src/emit/mod.rs | 3 +- crates/victory-shader/src/emit/shader.rs | 16 +- .../victory-shader/src/emit/stride_tests.rs | 174 +++++++++++++++++- 6 files changed, 333 insertions(+), 17 deletions(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 0a816f4bab..8eb4c158f7 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -468,9 +468,10 @@ impl HostHeap { } /// Enters the byte stride of `view` (0 for none or not a buffer view) - /// for slot `index` in the view-stride table. + /// for slot `index` in the view-stride table, with the integer-format + /// bits of a typed buffer view ([`view_kind`]). fn set_stride(&self, index: u32, view: Option<&View>) { - self.write_stride(index, view.map_or(0, view_stride)); + self.write_stride(index, view.map_or(0, |v| view_stride(v) | view_kind(v))); } fn write_stride(&self, index: u32, stride: u32) { @@ -830,6 +831,51 @@ fn view_stride(view: &View) -> u32 { element.max(1) as u32 } +/// The view-stride table's format-kind bits of a buffer view: a typed view +/// (no structure stride, not raw) of an integer format gets +/// `VIEW_INTEGER`, a signed one also `VIEW_SIGNED`; anything else none. +/// Translated shaders pass 16-bit typed data of such views as bits, not as +/// halves (`victory_shader::emit`, "d16"). +fn view_kind(view: &View) -> u32 { + use victory_shader::emit::{VIEW_INTEGER, VIEW_SIGNED}; + let (unordered, words): (bool, &[u32; 10]) = match view { + View::Shader(_, Some(desc)) => (false, desc), + View::Unordered(_, _, Some(desc)) => (true, desc), + View::Placed(unordered, resource, desc) if resource[0] == 1 => match desc[..10].try_into() { + Ok(words) => (*unordered, words), + Err(_) => return 0, + }, + _ => return 0, + }; + // Buffer views only (dimension 1); a structured or raw one is no typed view. + let (format, typed) = if unordered { + let desc = uav_desc(words); + // SAFETY: a buffer view's union member. + let b = unsafe { desc.Anonymous.Buffer }; + (desc.Format.0 as u32, b.StructureByteStride == 0 && b.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 == 0) + } else { + let desc = srv_desc(words); + // SAFETY: a buffer view's union member. + let b = unsafe { desc.Anonymous.Buffer }; + (desc.Format.0 as u32, b.StructureByteStride == 0 && b.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 == 0) + }; + match (words[1] == 1 && typed).then(|| integer_format(format)).flatten() { + Some(true) => VIEW_INTEGER | VIEW_SIGNED, + Some(false) => VIEW_INTEGER, + None => 0, + } +} + +/// Whether a DXGI format is an integer one, and if so whether signed: +/// `Some(false)` for `UINT`, `Some(true)` for `SINT`, `None` otherwise. +fn integer_format(format: u32) -> Option { + match format { + 3 | 7 | 12 | 17 | 25 | 30 | 36 | 42 | 50 | 57 | 62 => Some(false), + 4 | 8 | 14 | 18 | 32 | 38 | 43 | 52 | 59 | 64 => Some(true), + _ => None, + } +} + /// A buffer view of title memory at `address` on its host copy: the first /// element moves by the copy's offset. /// Bytes per element of a buffer view. @@ -1472,6 +1518,27 @@ fn null_view(at: D3D12_CPU_DESCRIPTOR_HANDLE) { mod tests { use super::*; + /// Typed buffer views of integer formats carry their kind in the + /// view-stride table; float, normalized, raw and structured ones none. + #[test] + fn integer_typed_buffer_views_are_marked_in_the_stride_table() { + use victory_shader::emit::{VIEW_INTEGER, VIEW_SIGNED}; + // Format, dimension (buffer), first element, count, stride, counter, flags. + let uav = |format, stride, flags| View::Unordered(0, 0, Some([format, 1, 0, 0, 64, stride, 0, 0, flags, 0])); + assert_eq!(view_kind(&uav(12, 0, 0)), VIEW_INTEGER, "R16G16B16A16_UINT"); + assert_eq!(view_kind(&uav(57, 0, 0)), VIEW_INTEGER, "R16_UINT"); + assert_eq!(view_kind(&uav(59, 0, 0)), VIEW_INTEGER | VIEW_SIGNED, "R16_SINT"); + assert_eq!(view_kind(&uav(64, 0, 0)), VIEW_INTEGER | VIEW_SIGNED, "R8_SINT"); + assert_eq!(view_kind(&uav(10, 0, 0)), 0, "R16G16B16A16_FLOAT"); + assert_eq!(view_kind(&uav(58, 0, 0)), 0, "R16_SNORM"); + assert_eq!(view_kind(&uav(39, 0, 1)), 0, "raw"); + assert_eq!(view_kind(&uav(0, 16, 0)), 0, "structured"); + // Format, dimension, mapping, first element, count, stride, flags. + let srv = View::Shader(0, Some([62, 1, 5768, 0, 0, 0, 64, 0, 0, 0])); + assert_eq!(view_kind(&srv), VIEW_INTEGER, "R8_UINT"); + assert_eq!(view_stride(&uav(12, 0, 0)) | view_kind(&uav(12, 0, 0)), 8 | VIEW_INTEGER); + } + /// A placed texture's view the title writes into a heap is left null /// and noted once: heap syncs (every submission) pass it by, a draw /// reading it through a table makes it. diff --git a/crates/victory-shader/src/emit/host.rs b/crates/victory-shader/src/emit/host.rs index 76f2455004..5ab0a9e65f 100644 --- a/crates/victory-shader/src/emit/host.rs +++ b/crates/victory-shader/src/emit/host.rs @@ -1239,6 +1239,9 @@ pub enum View<'a> { Uint2TextureUav(u32, u32), /// A typed RGBA16F buffer UAV of this many elements, zeroed. HalfUav(u32), + /// A typed buffer UAV in this format, of this many elements of this many + /// bytes, zeroed. + TypedUav(DXGI_FORMAT, u32, u32), /// A constant buffer of these dwords. Cbv(&'a [u32]), /// A buffer SRV over these dwords. @@ -1543,7 +1546,7 @@ impl Host { dev.CreateShaderResourceView(&tex, None, at); keep.push(tex); } - View::RawUav(_) | View::HalfUav(_) => { + View::RawUav(_) | View::HalfUav(_) | View::TypedUav(..) => { // (dwords, format, elements, flags) let (n, format, elements, flags) = match *v { View::HalfUav(e) => ( @@ -1552,6 +1555,9 @@ impl Host { e, D3D12_BUFFER_UAV_FLAG_NONE, ), + View::TypedUav(format, e, bytes) => { + ((e * bytes).div_ceil(4), format, e, D3D12_BUFFER_UAV_FLAG_NONE) + } View::RawUav(n) => { (n, DXGI_FORMAT_R32_TYPELESS, n, D3D12_BUFFER_UAV_FLAG_RAW) } diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index d014a85684..ad8868565d 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -11,7 +11,7 @@ use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use super::UserData; use super::bitcode::{Attr, Bin, Cast, Term, V, pred}; use super::container::SigElement; -use super::shader::{Shader, VIEW_STRIDES, flags}; +use super::shader::{Shader, VIEW_INTEGER, VIEW_SIGNED, VIEW_STRIDE_BITS, VIEW_STRIDES, flags}; use crate::ShaderError; use crate::gfx10::{Dpp, Fields, NULL, Operand}; use crate::io::{Barycentric, Elsewhere, Export, Input, Interp, Io, Target}; @@ -4378,6 +4378,14 @@ impl<'a> Lower<'a> { /// The byte stride of the buffer view at heap index `index`, from the /// view-stride table (`t`[`VIEW_STRIDES`]). fn stride_at(&mut self, index: V) -> V { + let word = self.view_word(index); + let bits = self.s.m.i32(VIEW_STRIDE_BITS); + self.s.m.bin(self.cur, Bin::And, word, bits) + } + + /// Dword `index` of the view-stride table: the stride and the format + /// kind bits ([`VIEW_INTEGER`], [`VIEW_SIGNED`]). + fn view_word(&mut self, index: V) -> V { let c = self.cur; let four = self.s.m.i32(4); let at = self.s.m.bin(c, Bin::Mul, index, four); @@ -4385,6 +4393,22 @@ impl<'a> Lower<'a> { self.raw_dword(table, at) } + /// Whether the typed buffer view a handle names has an integer format, + /// and whether a signed one, from the view-stride table; `None` if the + /// handle's heap index is not known. + fn integer_view(&mut self, h: V) -> Option<(V, V)> { + let index = *self.s.view_index.get(&h)?; + let word = self.view_word(index); + let c = self.cur; + let zero = self.s.m.i32(0); + let [int, signed] = [VIEW_INTEGER, VIEW_SIGNED].map(|bit| { + let bit = self.s.m.i32(bit); + let x = self.s.m.bin(c, Bin::And, word, bit); + self.s.m.cmp(c, pred::NE, x, zero) + }); + Some((int, signed)) + } + /// Title memory at a raw GPU address (decision 0005: the unified-memory /// item). Every access to an address the program computes goes through /// here: scalar and global loads, stores and atomics, the BVH node @@ -4834,7 +4858,9 @@ impl<'a> Lower<'a> { &[table, at, iu, mask, four], ); let x = self.s.m.extract(c, r, 0); - Ok(self.as_int(x)) + let word = self.as_int(x); + let bits = self.s.m.i32(VIEW_STRIDE_BITS); + Ok(self.s.m.bin(c, Bin::And, word, bits)) } /// The used-resource entry a descriptor loaded from a table falls in. @@ -8961,9 +8987,19 @@ impl<'a> Lower<'a> { let regs = if d16 { count.div_ceil(2) } else { count }; let mut vals = self.vgprs(inst, data.as_ref().ok_or("buffer store data")?, regs as u8)?; + let typed_h = if typed { + Some(self.handle(site, src, false, (10 | u, 0x409))?) + } else { + None + }; if d16 { - // shortcut: d16 data is taken as f16 (integer formats would - // keep 16 bits), widened for the 32-bit float store. + // d16 data is f16 for float and normalized formats, widened + // for the 32-bit float store; for integer formats (the view's + // kind, from the view-stride table) the 16-bit integer, zero- + // or sign-extended (stored through the float-typed handle as + // loads read: see there). + let integer = typed_h.and_then(|h| self.integer_view(h)); + let c = self.cur; let mut wide = Vec::new(); for k in 0..count { let mut x = vals[(k / 2) as usize]; @@ -8975,7 +9011,16 @@ impl<'a> Lower<'a> { let f = self .s .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x]); - wide.push(self.as_int(f)); + let mut w = self.as_int(f); + if let Some((int, signed)) = integer { + let (k16, low) = (self.s.m.i32(16), self.s.m.i32(0xFFFF)); + let zero_ext = self.s.m.bin(c, Bin::And, x, low); + let up = self.s.m.bin(c, Bin::Shl, x, k16); + let sign_ext = self.s.m.bin(c, Bin::AShr, up, k16); + let n = self.s.m.select(c, signed, sign_ext, zero_ext); + w = self.s.m.select(c, int, n, w); + } + wide.push(w); } vals = wide; } @@ -8989,7 +9034,7 @@ impl<'a> Lower<'a> { if count != 4 || *offen || *offset != 0 { return Err("a typed buffer store of some channels or at an offset"); } - let h = self.handle(site, src, false, (10 | u, 0x409))?; + let h = typed_h.ok_or("a typed buffer store")?; let element = index.unwrap_or(self.s.m.i32(0)); args.push(h); args.extend([element, iu]); @@ -9094,6 +9139,7 @@ impl<'a> Lower<'a> { self.write(inst, Reg::V(reg), x, guard); return Ok(()); } + let mut typed_h = None; let r = if typed { if *offen || matches!(off, V::Inst(_)) || *offset != 0 { return Err("a typed buffer load at an offset"); @@ -9102,6 +9148,7 @@ impl<'a> Lower<'a> { self.s.flags |= flags::TYPED_UAV_LOADS; } let h = self.handle(site, src, false, (10 | u, 0x409))?; + typed_h = Some(h); let index = index.unwrap_or(self.s.m.i32(0)); self.s.op( c, @@ -9150,16 +9197,31 @@ impl<'a> Lower<'a> { return Err("a buffer result"); }; if d16 { - // Two f16 channels per VGPR (an odd last high half 0). + // Two 16-bit channels per VGPR (an odd last high half 0): f16 for + // float and normalized formats; for integer formats (the view's + // kind, from the view-stride table) the integer's low 16 bits. + // shortcut: an integer view is read and written through the + // float-typed handle, so its channels' bits travel as the driver + // passes a mismatched component type (unchanged on the RX 6700 + // XT and WARP, `stride_tests`); an integer-typed second handle + // for the slot would not rely on it. + let integer = typed_h.and_then(|h| self.integer_view(h)); + let c = self.cur; let k16 = self.s.m.i32(16); let i32t = self.s.t.i32; for k in 0..count.div_ceil(2) { let mut x = None; for ch in (2 * k..(2 * k + 2).min(count)).rev() { let f = self.s.m.extract(c, r, ch); - let h = self + let mut h = self .s .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]); + if let Some((int, _)) = integer { + let bits = self.as_int(f); + let low = self.s.m.i32(0xFFFF); + let low = self.s.m.bin(c, Bin::And, bits, low); + h = self.s.m.select(c, int, low, h); + } x = Some(match x { Some(hi) => { let hi = self.s.m.bin(c, Bin::Shl, hi, k16); diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 43397e695b..87d43e7edd 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -220,7 +220,8 @@ use crate::{ShaderError, io, ir, resource, structure}; pub use sampler::StaticSampler; pub use shader::{ HEAP_SAMPLERS, HEAP_VIEWS, MEMORY_SPACE, NULL_BUFFER_VIEW, ROOT_CBV_SPACE, SAMPLER_SPACE, - USER_DATA_SPACE, VIEW_MARK_NONE, VIEW_MARKS, VIEW_STRIDES, VIEW_WRITE_BITS, VIEW_WRITES, + USER_DATA_SPACE, VIEW_INTEGER, VIEW_MARK_NONE, VIEW_MARKS, VIEW_SIGNED, VIEW_STRIDE_BITS, VIEW_STRIDES, + VIEW_WRITE_BITS, VIEW_WRITES, }; /// The loop limit without an override: 2^20. diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index e68e2627c9..1e8cf3c1c4 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -14,8 +14,16 @@ pub const SAMPLER_SPACE: u32 = 0; pub const ROOT_CBV_SPACE: u32 = 1; /// The root SRV slot (`t255` in [`ROOT_CBV_SPACE`], past every title root /// parameter) of the view-stride table: dword `i` is the byte stride of -/// the buffer view at view-heap index `i`. +/// the buffer view at view-heap index `i` ([`VIEW_STRIDE_BITS`]), with +/// [`VIEW_INTEGER`] and [`VIEW_SIGNED`] for typed views of integer formats. pub const VIEW_STRIDES: u8 = 255; +/// The bits of a view-stride table dword holding the stride. +pub const VIEW_STRIDE_BITS: u32 = (1 << 30) - 1; +/// In a view-stride table dword: a typed buffer view of an integer format +/// (`UINT` or `SINT`), whose 16-bit typed accesses (`_d16`) pass bits. +pub const VIEW_INTEGER: u32 = 1 << 31; +/// With [`VIEW_INTEGER`]: a signed (`SINT`) format. +pub const VIEW_SIGNED: u32 = 1 << 30; /// Where the title-memory page table is bound: `t0` (a raw root SRV) in /// this space (see `emit` "Title memory"). pub const MEMORY_SPACE: u32 = 2; @@ -533,8 +541,10 @@ impl Shader { &[index, s, n], ); let h = self.annotate(block, h, props.0, props.1); - // Unordered typed, raw and structured buffers (kinds 10-12). - if !sampler && props.0 & 0x1000 != 0 && (10..=12).contains(&(props.0 & 0xFF)) { + // Unordered typed, raw and structured buffers (kinds 10-12), and + // typed buffers read (their format kind, `Lower::view_word`). + let kind = props.0 & 0xFF; + if !sampler && (kind == 10 || props.0 & 0x1000 != 0 && (11..=12).contains(&kind)) { self.view_index.insert(h, index); } h diff --git a/crates/victory-shader/src/emit/stride_tests.rs b/crates/victory-shader/src/emit/stride_tests.rs index fc160f5f98..20615b2e50 100644 --- a/crates/victory-shader/src/emit/stride_tests.rs +++ b/crates/victory-shader/src/emit/stride_tests.rs @@ -7,8 +7,13 @@ use windows::Win32::Graphics::Direct3D12::D3D12_SAMPLER_DESC; +use windows::Win32::Graphics::Dxgi::Common::{ + DXGI_FORMAT, DXGI_FORMAT_R16_FLOAT, DXGI_FORMAT_R16_UINT, DXGI_FORMAT_R16G16B16A16_FLOAT, + DXGI_FORMAT_R16G16B16A16_UINT, +}; + use super::host::{Dispatch, Host, Root, Stride, View}; -use super::{HostShader, StaticSampler, VIEW_STRIDES, lower, validator}; +use super::{HostShader, StaticSampler, VIEW_INTEGER, VIEW_STRIDES, lower, validator}; use crate::native::{ ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, }; @@ -573,4 +578,169 @@ fn a_sampler_chosen_by_a_uniform_branch_samples_as_chosen() { ran += 1; } assert!(ran > 0, "neither hardware nor WARP SM 6.6 device available"); -} \ No newline at end of file +} +/// User data: s0 a table with a typed buffer UAV, s1 a table with a raw +/// buffer of 2 dwords a lane, s2 a table with a raw UAV. Each lane stores +/// its 4 halves to element `lane` of the typed view (`_d16`), loads them +/// back the same way and stores what it read to dwords `2 lane, 2 lane + 1` +/// of the raw UAV. +const D16_ROUND_TRIP_WAVE32: &[u32] = &[ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0202, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], 0x0 + 0xBE86_0301, // s_mov_b32 s6, s1 + 0xBE87_0380, // s_mov_b32 s7, 0 + 0xF408_0303, + 0xFA00_0000, // s_load_dwordx4 s[12:15], s[6:7], 0x0 + 0xBE94_0302, // s_mov_b32 s20, s2 + 0xBE95_0380, // s_mov_b32 s21, 0 + 0xF408_040A, + 0xFA00_0000, // s_load_dwordx4 s[16:19], s[20:21], 0x0 + 0x3406_0083, // v_lshlrev_b32 v3, 3, v0 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xE034_1000, + 0x8003_0103, // buffer_load_dwordx2 v[1:2], v3, s[12:15], 0 offen + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0xE21C_2000, + 0x8002_0100, // buffer_store_format_d16_xyzw v[1:2], v0, s[8:11], 0 idxen + 0xE20C_2000, + 0x8002_0400, // buffer_load_format_d16_xyzw v[4:5], v0, s[8:11], 0 idxen + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0xE074_1000, + 0x8004_0403, // buffer_store_dwordx2 v[4:5], v3, s[16:19], 0 offen + 0xBF81_0000, // s_endpgm +]; + +/// User data: s0 a table with a typed buffer SRV, s1 a table with a raw UAV. +/// Each lane loads element `lane` (`_d16_x`) and stores the dword it got to +/// dword `lane` of the raw UAV. +const D16_X_LOAD_WAVE32: &[u32] = &[ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0202, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], 0x0 + 0xBE86_0301, // s_mov_b32 s6, s1 + 0xBE87_0380, // s_mov_b32 s7, 0 + 0xF408_0403, + 0xFA00_0000, // s_load_dwordx4 s[16:19], s[6:7], 0x0 + 0x3406_0082, // v_lshlrev_b32 v3, 2, v0 + 0x7E08_0280, // v_mov_b32 v4, 0 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xE200_2000, + 0x8002_0400, // buffer_load_format_d16_x v4, v0, s[8:11], 0 idxen + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0xE070_1000, + 0x8004_0403, // buffer_store_dword v4, v3, s[16:19], 0 offen + 0xBF81_0000, // s_endpgm +]; + +/// Runs `shader` (user data: tables at heap indices 0, 1, 2 in order) on +/// hardware and WARP with `views` and the view-stride table `strides`; +/// each adapter's UAV contents. +fn run_tables(shader: &HostShader, views: &[View], strides: Vec) -> Vec<(&'static str, Vec>)> { + assert_eq!(shader.root_srvs, [VIEW_STRIDES]); + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); + let mut out = Vec::new(); + for (label, warp) in [("hardware", false), ("warp", true)] { + let Ok(host) = Host::new(warp) else { + eprintln!("no SM 6.6 {label} device; skipped"); + continue; + }; + let (root, pso) = host + .compute_pipeline(shader) + .unwrap_or_else(|e| panic!("{label}: compute_pipeline failed: {e}")); + let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + for u in &shader.user_data { + // Table k is the view at heap index k (32 bytes a view). + ud[u.index as usize] = 32 * u32::from(u.slot); + } + let words = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud)), (1, Root::View { srv: true, data: strides.clone() })], + views, + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); + out.push((label, words)); + } + assert!(!out.is_empty(), "neither hardware nor WARP SM 6.6 device available"); + out +} + +/// 16-bit typed stores and loads (`_d16`) through views of integer formats +/// pass the bits (the console's buffer format decides the conversion; d16 +/// only packs 16-bit results), and through float views convert as halves: +/// Grand Theft Auto VI's face network keeps its halves in UINT views. +#[test] +fn d16_typed_buffer_accesses_pass_bits_through_integer_views() { + let shader = build( + D16_ROUND_TRIP_WAVE32, + vec![ + param(RootType::Table, 0), + param(RootType::Table, 1), + param(RootType::Table, 2), + ], + vec![ + entry(ResourceType::Uav, 4, 0), + entry(ResourceType::Srv, 4, 1), + entry(ResourceType::Uav, 4, 2), + ], + 32, + ); + // Lane l: negative zero and small, signalling NaN, denormal and + // all-ones patterns as bits; normal halves for the float view. + let bits: Vec = (0..32u32) + .flat_map(|l| [(0x8000 | l) | (0x7C01 + l) << 16, (1 + l) | (0xFFFF - l) << 16]) + .collect(); + let halves: Vec = (0..32u32) + .flat_map(|l| [(0x3C00 + l) | (0xC000 + 3 * l) << 16, (0x1400 + l) | (0x5BFF - l) << 16]) + .collect(); + let cases: [(DXGI_FORMAT, u32, &[u32]); 2] = [ + (DXGI_FORMAT_R16G16B16A16_UINT, 8 | VIEW_INTEGER, &bits), + (DXGI_FORMAT_R16G16B16A16_FLOAT, 8, &halves), + ]; + for (format, stride, data) in cases { + let views = [ + View::TypedUav(format, 32, 8), + View::Buffer { data, stride: Stride::Raw }, + View::RawUav(64), + ]; + for (label, words) in run_tables(&shader, &views, vec![stride, 4, 4]) { + assert_eq!(words[0], data, "{label} {format:?}: the typed view's bytes"); + assert_eq!(words[1], data, "{label} {format:?}: what the loads read"); + } + } +} + +/// A one-channel `_d16_x` load from a typed SRV: an integer view's 16 bits +/// as they are, a float view's half as it is. +#[test] +fn d16_x_loads_read_r16_uint_and_r16_float_views() { + let shader = build( + D16_X_LOAD_WAVE32, + vec![param(RootType::Table, 0), param(RootType::Table, 1)], + vec![entry(ResourceType::Srv, 4, 0), entry(ResourceType::Uav, 4, 1)], + 32, + ); + let pack = |h: &dyn Fn(u32) -> u32| -> Vec { (0..16u32).map(|k| h(2 * k) | h(2 * k + 1) << 16).collect() }; + let uint = |l: u32| 0xF000 | l; + let half = |l: u32| 0x3C00 + 5 * l; + let cases: [(DXGI_FORMAT, u32, Vec, Vec); 2] = [ + (DXGI_FORMAT_R16_UINT, 2 | VIEW_INTEGER, pack(&uint), (0..32).map(uint).collect()), + (DXGI_FORMAT_R16_FLOAT, 2, pack(&half), (0..32).map(half).collect()), + ]; + for (format, stride, data, want) in cases { + let views = [View::Buffer { data: &data, stride: Stride::Format(format, 2) }, View::RawUav(32)]; + for (label, words) in run_tables(&shader, &views, vec![stride, 4]) { + assert_eq!(words[0], want, "{label} {format:?}"); + } + } +} From d75491e9915535fa7aff782758c162e9f7a0c52c Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 07:13:39 +0100 Subject: [PATCH 34/83] GPU: a texture written in pages of its own is uploaded without hashing it What was wrong: since 23a4b62b every upload of a tracked texture hashed the texture's bytes (BLAKE3) to skip uploads whose bytes did not change. That pays for small textures sharing 64 KiB pages with other data the title writes, but not for textures the title rewrites every frame: the menu movie's Bink planes (3840x2160 Y plane plus chroma, 12.7 MB a frame) took 12.7-13.8 ms a frame of texture preparation in run textures8 (12.0-12.9 in integ3), against 3.7-5.2 ms before 23a4b62b (mk3, perf5). What changed: when a changed page lies wholly inside the texture (it holds nothing but texture bytes), the write itself says the texture changed: no hash, and the stored hash is forgotten. Textures whose changed pages are shared still compare their bytes. Evidence: tests `draw::tests::a_texture_owning_its_pages_is_uploaded_on_any_write` (new) and `a_texture_is_uploaded_once_per_submission_and_only_when_written` (now also: the same bytes in a shared page are not uploaded) on WARP. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/draw.rs | 34 +++++++++++++++++++++++++++++++ crates/victory-gpu/src/texture.rs | 20 ++++++++++++------ 2 files changed, 48 insertions(+), 6 deletions(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 9b5ef83082..65f68ec6df 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -2394,6 +2394,40 @@ void main(uint3 id : SV_DispatchThreadID) { let (n, x) = submit(Some(0x80)); assert_eq!(n, 1, "written: uploaded again"); assert!((x - 128.0 / 255.0).abs() < 1e-6); + assert_eq!(submit(Some(0x80)).0, 0, "the same bytes in a shared page: not uploaded"); + } + + /// A texture written in a page that holds only its own bytes is uploaded + /// without hashing them (a movie frame rewritten every frame), so even + /// the same bytes again are uploaded. + #[test] + fn a_texture_owning_its_pages_is_uploaded_on_any_write() { + let Some(host) = crate::host::host() else { + return; // no host GPU here + }; + let slots = Slots::new(2); + let read = compile_cs(READ); + let (out, _) = host.shared_buffer(64 * 64 * 16).unwrap(); + // RGBA8 128x128, linear: one whole 64 KiB page. + let address = crate::watch::tests::pool(1) as u64; + let object = texture_at_address(address, &texture_words(128, 128, 28, 0x100, 0)); + let mut desc = [0u32; 10]; + desc[..6].copy_from_slice(&[28, 4, 0x1688, 0, 0, 1]); + let view = View::Shader(object as usize, Some(desc)); + slots.make(0, &view); + let submit = || { + // SAFETY: the texture's memory, one page. + unsafe { std::ptr::write_bytes(address as *mut u8, 0x40, crate::watch::PAGE) }; + let list = host.new_list().unwrap(); + readable(&list, &used(ResourceType::Srv), &view, false); + run(&list, &slots, &read, 0, Some(&out), (8, 8)); + list.close(); + let before = crate::texture::UPLOADS.load(Ordering::Relaxed); + host.execute(&[&list]); + crate::texture::UPLOADS.load(Ordering::Relaxed) - before + }; + assert_eq!(submit(), 1); + assert_eq!(submit(), 1, "its own page written: uploaded"); } /// A depth texture with stencil (the console's 16-bit depth, the diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 4627e01239..87611de7df 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -353,7 +353,8 @@ impl Staging { let mut last = self.last.lock().unwrap_or_else(|e| e.into_inner()); let last = &mut *last; if let Some(t) = &self.tracked { - if t.take(start, start + size).is_empty() { + let ranges = t.take(start, start + size); + if ranges.is_empty() { return (0, false); } // Read through the copy, which stands unmapped pages: memory of @@ -361,11 +362,18 @@ impl Staging { // double each texture's system memory. let mut read = vec![0u8; size]; crate::host::copy_mapped(read.as_mut_ptr(), self.memory, size, false); - // Its pages also hold other data the title writes (64 KiB pages, - // small textures): its own bytes decide. - let hash = blake3::hash(&read); - if last.hash.replace(hash) == Some(hash) { - return (size, false); + // A changed page that holds only texture bytes says it changed. + // Pages it shares with other data the title writes (small + // textures): its own bytes decide. (Hashing a movie frame cost + // 8 ms a frame.) + let page = crate::watch::PAGE; + if ranges.iter().any(|&(f, e)| f.next_multiple_of(page) + page <= e) { + last.hash = None; + } else { + let hash = blake3::hash(&read); + if last.hash.replace(hash) == Some(hash) { + return (size, false); + } } self.detile(&read); #[cfg(feature = "diagnostics")] From 2a4938e66b8f142983892b27deb3648aae4a7dae Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 06:22:37 +0100 Subject: [PATCH 35/83] GPU: pages with nothing mapped are zeroed in host copies without failing copies When a copy's refresh met a page with nothing mapped (tiled memory the title unmapped, placeholders), the kernel read failed and the copy was redone by 64 KiB and then 4 KiB pieces, each failing again: 10-22 MB of unmapped memory a frame took 7-30 ms (run perf4). The tracker already learns which pages are unmapped when it fails to guard them; `take_split` now returns those runs apart, and the refresh zeroes them in the copy as the piecewise copy did, with no kernel read. Test: of a reservation with one page committed, the committed page is to copy and the other to zero. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/shadow.rs | 8 ++++- crates/victory-gpu/src/watch.rs | 58 +++++++++++++++++++++++++++++--- 2 files changed, 60 insertions(+), 6 deletions(-) diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 577ac8ffea..f7bfc2511c 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -591,11 +591,17 @@ impl Shadow { if let Some(t) = &self.tracked { #[cfg(feature = "diagnostics")] let started = std::time::Instant::now(); - let runs = t.take(from, to); + let (runs, unmapped) = t.take_split(from, to); #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::WatchUs, started.elapsed().as_micros() as u64); // Cut to the range: next to it shaders may be writing the copy. let mut copied: usize = runs.into_iter().map(|(a, b)| self.copy(a, b)).sum(); + for (a, b) in unmapped { + // SAFETY: inside the mapping (`take_split` cuts to the buffer). + unsafe { self.data.add(a - self.start as usize).write_bytes(0, b - a) }; + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::Unmapped, (b - a) as u64); + } // Parts on memory that is not the runtime's: whole, as below. for (a, b) in t.untracked(from, to) { #[cfg(feature = "diagnostics")] diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index c2d50ee78b..ae3975bcca 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -127,6 +127,9 @@ impl Changed { } } +/// Byte runs `[start, end)` in order. +pub(crate) type Runs = Vec<(usize, usize)>; + /// Title memory a host copy or texture staging takes: bytes `[start, end)`. pub(crate) struct Tracked { start: usize, @@ -387,9 +390,26 @@ impl Tracked { /// `[from, to)`, in order. A page whose part in the tracked memory lies /// only partly in `[from, to)` is copied in part and stays changed. pub(crate) fn take(&self, from: usize, to: usize) -> Vec<(usize, usize)> { + let (copy, zero) = self.take_split(from, to); + let mut runs: Vec<(usize, usize)> = copy.into_iter().chain(zero).collect(); + runs.sort_unstable(); + let mut merged: Vec<(usize, usize)> = Vec::with_capacity(runs.len()); + for (a, b) in runs { + match merged.last_mut() { + Some((_, end)) if *end == a => *end = b, + _ => merged.push((a, b)), + } + } + merged + } + + /// [`Tracked::take`], the runs on pages with nothing mapped apart: they + /// read as zeros, with no copy to try (each such page cost a dozen + /// failing kernel reads, 7-30 ms a frame in run perf4). + pub(crate) fn take_split(&self, from: usize, to: usize) -> (Runs, Runs) { let (from, to) = (from.max(self.start), to.min(self.end)); if from >= to { - return Vec::new(); + return (Vec::new(), Vec::new()); } let pages: Vec = { #[cfg(feature = "diagnostics")] @@ -400,7 +420,7 @@ impl Tracked { changed.range(from / PAGE..to.div_ceil(PAGE)).copied().collect() }; if pages.is_empty() { - return Vec::new(); + return (Vec::new(), Vec::new()); } let whole: Vec = pages .iter() @@ -421,22 +441,24 @@ impl Tracked { guard_aliases(&mut g, &others); #[cfg(feature = "diagnostics")] drop(asked); - for page in protect(&mut g, &whole) { + let mut unmapped = Vec::new(); + for page in protect_noting(&mut g, &whole, &mut unmapped) { changed.remove(&page); self.changed.taken(page); } set_dirty(self.changed.2, !changed.is_empty()); drop(changed); drop(g); - let mut runs: Vec<(usize, usize)> = Vec::new(); + let (mut copy, mut zero): (Runs, Runs) = (Vec::new(), Vec::new()); for p in pages { let (a, b) = ((p * PAGE).max(from), ((p + 1) * PAGE).min(to)); + let runs = if unmapped.contains(&p) { &mut zero } else { &mut copy }; match runs.last_mut() { Some((_, end)) if *end == a => *end = b, _ => runs.push((a, b)), } } - runs + (copy, zero) } /// Whether page `page` (a page number) changed since it was taken. @@ -519,6 +541,12 @@ impl Tracked { /// now guarded or with nothing mapped (taken either way); a page that is /// mapped but cannot be guarded is left out (it stays changed). fn protect(g: &mut Guards, pages: &[usize]) -> Vec { + protect_noting(g, pages, &mut Vec::new()) +} + +/// [`protect`], also listing in `unmapped` the pages taken because nothing +/// is mapped there. +fn protect_noting(g: &mut Guards, pages: &[usize], unmapped_pages: &mut Vec) -> Vec { #[cfg(feature = "diagnostics")] let counted = |calls: u64, pages: u64| { crate::copystat::add(crate::copystat::C::ProtectCalls, calls); @@ -571,6 +599,7 @@ fn protect(g: &mut Guards, pages: &[usize]) -> Vec { taken.push(page); } else if unmapped(page) { taken.push(page); + unmapped_pages.push(page); } } } @@ -904,6 +933,25 @@ pub(crate) mod tests { free(p); } + /// A page with nothing mapped is taken as zeros: `take_split` lists it + /// apart from the pages to copy. + #[test] + fn unmapped_pages_are_taken_apart() { + // SAFETY: a fresh write-watched reservation of two pages, the first + // committed; freed below. + let p = unsafe { + let p = VirtualAlloc(std::ptr::null(), 2 * PAGE, MEM_RESERVE | MEM_WRITE_WATCH, PAGE_READWRITE) as usize; + assert_ne!(p, 0); + assert_ne!(VirtualAlloc(p as *const _, PAGE, MEM_COMMIT, PAGE_READWRITE) as usize, 0); + p + }; + let t = track(p, 2 * PAGE, true).expect("tracked"); + assert_eq!(t.take_split(p, p + 2 * PAGE), (vec![(p, p + PAGE)], vec![(p + PAGE, p + 2 * PAGE)])); + assert!(t.take(p, p + 2 * PAGE).is_empty(), "both taken"); + drop(t); + free(p); + } + /// A page only partly in the range asked is copied in part and stays /// changed; edge pages count whole when the tracked part is covered. #[test] From 9c179ea6f78fbcd522bbaaf88b5878a07f94b6cf Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 06:55:15 +0100 Subject: [PATCH 36/83] GPU: a frame wait begun after its tick passed ends at once A frame-event wait (the title's flip wait before each present) always slept until the next tick after now, even when the frame had run long past the tick it was waiting for: in the intro cutscene, where frames take 0.5 s against a 33 ms interval, that added 0-33 ms to every frame (4 % of the submitting thread's samples, run perf3). A wait now takes the latest tick passed when that is after the last tick its kind took (still one wait per tick per kind), as an event signalled at each tick and left signalled until a wait takes it would; the next wait waits for the next tick as before, so a title that keeps up is paced as before. That a late wait returns at once on the console is an assumption: nothing at hand says what a wait begun after its event does. Diagnostics: per stats window, frame waits and those that ended at once, and presents whose flip tick was the previous present's (should stay 0). Test: after two missed ticks a flip wait ends at once on the latest one, the next on the tick after. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/frame.rs | 59 +++++++++++++++++++++++++++++---- crates/victory-gpu/src/host.rs | 1 + crates/victory-gpu/src/queue.rs | 2 ++ 3 files changed, 55 insertions(+), 7 deletions(-) diff --git a/crates/victory-gpu/src/frame.rs b/crates/victory-gpu/src/frame.rs index c87cff85b1..4a68b3533f 100644 --- a/crates/victory-gpu/src/frame.rs +++ b/crates/victory-gpu/src/frame.rs @@ -92,11 +92,17 @@ fn last(kind: u32) -> &'static AtomicU64 { &LAST[(kind as usize).min(LAST.len() - 1)] } -/// The next tick after now and after the last one a wait for `kind` took -/// (an event happens once per tick: a wait woken a little early must not -/// let the next one end on the same tick), and how long until it. A wait -/// that comes within `limit` takes the tick here, under the clock's lock, -/// so two threads waiting for one kind never take the same tick. +/// The tick a wait for `kind` ends on, and how long until it: the first +/// one after the last a wait for `kind` took (an event happens once per +/// tick: a wait woken a little early must not let the next one end on the +/// same tick), the latest one passed if that is later. A wait begun after +/// its tick passed (a frame slower than the interval) so ends at once, as +/// an event signalled at the tick and left signalled until a wait takes it +/// would (assumed: nothing we have says what a late wait does); waiting for +/// the next tick instead cost the cutscene's frames 0-33 ms each (4 % of +/// the frame thread, run perf3). A wait that +/// comes within `limit` takes the tick here, under the clock's lock, so two +/// threads waiting for one kind never take the same tick. fn next_tick(kind: u32, limit: Duration) -> (u64, Duration) { let mut clock = clock(); let c = clock.get_or_insert_with(|| Clock { @@ -106,8 +112,7 @@ fn next_tick(kind: u32, limit: Duration) -> (u64, Duration) { }); let elapsed = c.start.elapsed().as_nanos(); let interval = c.interval.as_nanos().max(1); - let tick = - (c.first + (elapsed / interval + 1) as u64).max(last(kind).load(Ordering::Relaxed) + 1); + let tick = (c.first + (elapsed / interval) as u64).max(last(kind).load(Ordering::Relaxed) + 1); let at = u128::from(tick - c.first) * interval; let wait = Duration::from_nanos(at.saturating_sub(elapsed) as u64); if wait <= limit { @@ -140,6 +145,13 @@ pub(crate) extern "system" fn wait( std::thread::sleep(wait); S_OK }; + #[cfg(feature = "diagnostics")] + { + WAITS[0].fetch_add(1, Ordering::Relaxed); + if hr == S_OK && wait.is_zero() { + WAITS[1].fetch_add(1, Ordering::Relaxed); + } + } // A frame begun on a time-out takes no tick: its flip still does. if origin && (hr == S_OK || flags & TOKEN_ON_TIMEOUT != 0) { // Tokens count frames (consecutive), not ticks. @@ -163,6 +175,29 @@ pub(crate) extern "system" fn wait( hr } +/// Diagnostics: frame waits, and those that ended at once (their tick had +/// passed); presents whose flip tick was the previous present's. +#[cfg(feature = "diagnostics")] +static WAITS: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; +#[cfg(feature = "diagnostics")] +static PRESENT_TICK: AtomicU64 = AtomicU64::new(0); + +/// Diagnostics: a frame was presented (counts presents sharing a flip tick). +#[cfg(feature = "diagnostics")] +pub(crate) fn presented() { + let flip = LAST[2].load(Ordering::Relaxed); + if flip != 0 && PRESENT_TICK.swap(flip, Ordering::Relaxed) == flip { + WAITS[2].fetch_add(1, Ordering::Relaxed); + } +} + +/// Diagnostics: logs [`WAITS`] since the last call. +#[cfg(feature = "diagnostics")] +pub(crate) fn log() { + let [waits, at_once, shared] = [0, 1, 2].map(|i| WAITS[i].swap(0, Ordering::Relaxed)); + tracing::info!("frame waits: {waits}, {at_once} of them ended at once; presents sharing a flip tick: {shared}"); +} + /// Device method: no statistics are kept, so none are returned. pub(crate) extern "system" fn statistics( _: This, @@ -228,6 +263,16 @@ mod tests { // Even when a flip wait begins on the tick another just ended on. let (tick, _) = next_tick(FLIP, Duration::ZERO); assert!(tick > flips[3]); + // A flip wait begun after its tick passed (two ticks missed) ends at + // once, on the latest tick passed; the next one waits for the next. + std::thread::sleep(Duration::from_millis(110)); + let before = Instant::now(); + assert_eq!(wait(null, FLIP, u32::MAX, std::ptr::null(), 0, &mut token), S_OK); + assert!(before.elapsed() < Duration::from_millis(10), "{:?}", before.elapsed()); + let late = LAST[2].load(Ordering::Relaxed); + assert!(late >= flips[3] + 2, "{late} after {}", flips[3]); + assert_eq!(wait(null, FLIP, u32::MAX, std::ptr::null(), 0, &mut token), S_OK); + assert_eq!(LAST[2].load(Ordering::Relaxed), late + 1); } /// Two waits for one kind that begin together (two threads) take two diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index aaedce3b21..c38451cc82 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -2550,6 +2550,7 @@ impl Meter { gpu[0], gpu[1], gpu[2], title[0], title[1], title[2] ); let copy_frames = std::mem::take(&mut self.copy_stats_frames) as f64; + crate::frame::log(); log_gpu_times(copy_frames); crate::copystat::log(copy_frames); crate::bindless::log(copy_frames); diff --git a/crates/victory-gpu/src/queue.rs b/crates/victory-gpu/src/queue.rs index 99a0d07a73..ba071b7977 100644 --- a/crates/victory-gpu/src/queue.rs +++ b/crates/victory-gpu/src/queue.rs @@ -243,6 +243,8 @@ extern "system" fn present( _parameters: *const u8, ) -> HRESULT { let frame = FRAMES.fetch_add(1, Ordering::Relaxed) + 1; + #[cfg(feature = "diagnostics")] + crate::frame::presented(); if frame.is_power_of_two() { let (draws, dispatches) = crate::list::take_counts(); #[cfg(windows)] From 5c4c685c45ba3ca1aae8d8a021dee482c171779c Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 07:45:28 +0100 Subject: [PATCH 37/83] victory: the exe's bytes are dropped once the image is mapped What was wrong: `run` kept the exe as read (114 MB) and its patched copy (another 114 MB) alive until the title exited, though nothing reads them after the loader writes the patched copy and maps it: ~228 MB of the Rust heap for the whole run (large-allocation stacks of run textures8). What changed: the read bytes are a temporary of `prepare`, and the prepared image is dropped right after `load`. The mapped image, its path (`GetModuleFileName`), title DLLs and crash reports come from the loaded image and the files, not from these buffers. Co-Authored-By: Claude Opus 5.5 --- apps/victory/src/run.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/apps/victory/src/run.rs b/apps/victory/src/run.rs index 0cf045c68c..22a72b0e08 100644 --- a/apps/victory/src/run.rs +++ b/apps/victory/src/run.rs @@ -56,8 +56,9 @@ pub fn run( // Before the import registry is first used: it holds the module only // when the host's FidelityFX serves. victory_hle::modules::fidelityfx::use_host_dir(cfg.fidelityfx_dir.as_deref()); - let original = std::fs::read(exe).with_context(|| format!("reading {}", exe.display()))?; - let prepared = victory_loader::prepare(&original)?; + let prepared = victory_loader::prepare( + &std::fs::read(exe).with_context(|| format!("reading {}", exe.display()))?, + )?; let hash = prepared.original_hash.to_hex(); let title_dir = exe.parent().unwrap_or(Path::new(".")); match victory_game::identify(&hash) { @@ -73,6 +74,8 @@ pub fn run( let images = cfg.cache_subdir("images")?; victory_hle::modules::d3d12x::use_shader_cache(cfg.cache_subdir("shaders")?); let image = victory_loader::load(&prepared, &images)?; + // Mapped: the patched bytes (the exe's size, 114 MB) are not needed. + drop(prepared); victory_hle::runtime::set_main_image(image.base()); victory_hle::runtime::set_image_path(image.base(), exe); println!( From 9337b35e1273b6910a3b14c39205b10659804084 Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 03:45:50 +0100 Subject: [PATCH 38/83] GPU: while lists using title memory miss, none of their writes go back What a list using title memory wrote stayed out of title memory only when that list itself read or wrote memory with no host copy. Lists after it compute from its results in the host copies, the BVH builder's write addresses among them (its record arrays), so their writes went back: with every builder program running (the bind fix after this one), drops1 died 97 s into the world on a title pointer holding +inf/-inf, an empty AABB's floats (title+0x35a4245, then title+0x10823c). Now any miss of such a list marks its frame (`memory::note_missed`), and from then through the next presented frame (`memory::withholding`: the next frame's lists read this one's results before its own first miss) no list using title memory sends anything back, by any path: the page table's marked pages, root-UAV byte ranges, and write marks, which shaders using title memory now set in a bitmap of their own (`shadow::view_writes(true)`). Their results stay in the host copies for the GPU. With misses in every world frame this gives the title's CPU the same view as before the builder ran; it lifts itself when the misses stop. Tests: `memory::tests::a_miss_holds_back_its_frame_and_the_next`, `shadow::tests::marks_of_shaders_using_title_memory_are_held_back`. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/draw.rs | 5 +- crates/victory-gpu/src/host.rs | 22 ++++++-- crates/victory-gpu/src/memory.rs | 48 ++++++++++++++-- crates/victory-gpu/src/shadow.rs | 94 +++++++++++++++++++++++--------- 4 files changed, 131 insertions(+), 38 deletions(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 65f68ec6df..e864572f2b 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -553,7 +553,10 @@ impl State { 0 => crate::memory::heap(), h => crate::descriptor::heap(h as This).host(), }; - let (Some(table), Some(bitmap)) = (heap.and_then(|h| h.marks()), crate::shadow::view_writes()) else { + // Shaders using title memory mark in a bitmap of their own, held + // back while their results are (`crate::memory::withholding`). + let memory = p.stages.iter().any(|s| s.memory.is_some()); + let (Some(table), Some(bitmap)) = (heap.and_then(|h| h.marks()), crate::shadow::view_writes(memory)) else { once!("a shader marking its writes without a view heap: dropped"); not_run("write marks without a view heap"); return false; diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index c38451cc82..d66a9cca24 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -1072,12 +1072,22 @@ impl Host { // One list's lock at a time: a submission may name a list twice. let mut back: Vec<(std::sync::Arc, usize, usize, bool)> = Vec::new(); let mut index: std::collections::HashMap<(usize, usize, usize), usize> = std::collections::HashMap::new(); - for list in runs { + // Shaders that read memory with no copy computed something else than + // the console's: it stays out of title memory, where it broke the + // title's own data (runs c1, c4), and so does what every list using + // title memory wrote while any misses (`crate::memory::withholding`). + // Only such lists have checks; all are asked before anything goes back. + let missed: Vec = runs + .iter() + .map(|list| list.deferred().missed.iter().any(|check| check())) + .collect(); + if missed.contains(&true) { + crate::memory::note_missed(); + } + let withholding = crate::memory::withholding(); + for (list, &missed) in runs.iter().zip(&missed) { let deferred = list.deferred(); - // Shaders that read memory with no copy computed something else - // than the console's: it stays out of title memory, where it broke - // the title's own data (runs c1, c4). - let missed = deferred.missed.iter().any(|check| check()); + let missed = missed || withholding && !deferred.missed.is_empty(); for step in &deferred.copies { if let Step::GpuWrite(shadow, address, len, _) = step { let key = (std::sync::Arc::as_ptr(shadow) as usize, *address, *len); @@ -1098,7 +1108,7 @@ impl Host { .filter(|b| !b.3) .map(|(s, a, n, _)| (s.clone(), *a, *n)) .collect(); - crate::shadow::copy_back_marks(&withheld); + crate::shadow::copy_back_marks(&withheld, withholding); for (shadow, address, len, goes_back) in &back { let (address, len) = (*address, *len); if *goes_back { diff --git a/crates/victory-gpu/src/memory.rs b/crates/victory-gpu/src/memory.rs index 5f65d58076..270037b8b2 100644 --- a/crates/victory-gpu/src/memory.rs +++ b/crates/victory-gpu/src/memory.rs @@ -163,9 +163,39 @@ pub(crate) fn note_use(pipeline: &str) { stats(|s| *s.uses.entry(pipeline.to_owned()).or_default() += 1); } +/// Frames presented, and the last one in which a list using title memory +/// read or wrote memory with no copy ([`MISS_NEVER`] if none has). +static FRAMES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); +static MISSED_IN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(MISS_NEVER); +const MISS_NEVER: u64 = u64::MAX; + +/// A list using title memory read or wrote memory with no copy. +pub(crate) fn note_missed() { + use std::sync::atomic::Ordering::Relaxed; + MISSED_IN.store(FRAMES.load(Relaxed), Relaxed); +} + +/// Whether what lists using title memory wrote stays out of title memory +/// (in the host copies, for the GPU): some such list missed memory this +/// frame or the one before. A list that missed computed from zeros, and +/// the lists after it compute from its results in the host copies, the +/// BVH builder's write addresses among them, so withholding only the lists +/// that missed broke the title's own data (run drops1: an AABB's +inf/-inf +/// in a pointer the title followed). The frame before counts too: its +/// lists' results are read in this one, before this frame's first miss. +pub(crate) fn withholding() -> bool { + use std::sync::atomic::Ordering::Relaxed; + withheld_in(FRAMES.load(Relaxed), MISSED_IN.load(Relaxed)) +} + +fn withheld_in(frame: u64, missed: u64) -> bool { + missed != MISS_NEVER && frame <= missed.saturating_add(1) +} + /// Logs what title memory did since the last call, if anything: a line per /// presented frame while shaders use it. pub(crate) fn log_frame() { + FRAMES.fetch_add(1, std::sync::atomic::Ordering::Relaxed); let s = stats(std::mem::take); if s.uses.is_empty() && s.written + s.withheld + s.withheld_bytes + s.missed_pages + s.missed_regions == 0 { return; @@ -440,10 +470,9 @@ pub(crate) fn bind(list: &HostList, key: usize) -> Option { } // What shaders computed from memory with no copy (read as zeros) is // not the console's: it does not go into title memory, where it broke - // the title's own data (garbage pointers in title threads, run c1). - // shortcut: root UAV writes of such a list still go back (their - // bytes, `Shadow::gpu_writes`). - let withheld = if pages + regions > 0 { writes.len() as u64 } else { 0 }; + // the title's own data (garbage pointers in title threads, run c1), + // nor while any list using title memory misses ([`withholding`]). + let withheld = if pages + regions > 0 || withholding() { writes.len() as u64 } else { 0 }; let mut written = 0; for &(k, at) in writes.iter().take_while(|_| withheld == 0) { let n = copies[k].copy_back_page(at as usize); @@ -475,6 +504,17 @@ pub(crate) fn bind(list: &HostList, key: usize) -> Option { mod tests { use super::*; + /// Writes of lists using title memory are held back from a frame with a + /// miss through the next one, then go back again. + #[test] + fn a_miss_holds_back_its_frame_and_the_next() { + assert!(!withheld_in(0, MISS_NEVER)); + assert!(!withheld_in(u64::MAX, MISS_NEVER)); + assert!(withheld_in(7, 7)); + assert!(withheld_in(8, 7), "the next frame reads this one's results"); + assert!(!withheld_in(9, 7)); + } + /// The shader's lookup (`victory_shader` lowering) over a table's /// dwords: the view index and the byte offset in that view. fn look_up(dwords: &[u32], address: u64) -> (u32, u32) { diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index f7bfc2511c..7fd6923cfd 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -736,9 +736,12 @@ unsafe impl Send for Bitmap {} // SAFETY: as above. unsafe impl Sync for Bitmap {} -fn bitmap() -> Option<&'static Bitmap> { - static BITMAP: std::sync::OnceLock> = std::sync::OnceLock::new(); - BITMAP +/// The bitmap of other shaders, or (`memory`) of shaders that use title +/// memory, whose marks go back only while it is not withheld +/// (`crate::memory::withholding`). +fn bitmap(memory: bool) -> Option<&'static Bitmap> { + static BITMAPS: [std::sync::OnceLock>; 2] = [const { std::sync::OnceLock::new() }; 2]; + BITMAPS[usize::from(memory)] .get_or_init(|| { let bytes = u64::from(victory_shader::emit::VIEW_WRITE_BITS / 8); let (buffer, data) = host()?.shared_buffer(bytes)?; @@ -757,40 +760,46 @@ fn bitmap() -> Option<&'static Bitmap> { } /// The host GPU address of the buffer views' written-pages bitmap, for the -/// root UAV of shaders that mark their writes. -pub(crate) fn view_writes() -> Option { - bitmap().map(|b| b.gpu) +/// root UAV of shaders that mark their writes (`memory`: shaders that use +/// title memory, see [`bitmap`]). +pub(crate) fn view_writes(memory: bool) -> Option { + bitmap(memory).map(|b| b.gpu) } /// After a submission: every page its shaders marked as written through /// views goes back ([`Shadow::copy_back_marked`]), but for pages in /// `withheld` (ranges of copies that lists whose writes stay out of title -/// memory declared); the bitmap is cleared. Before the copy-backs of +/// memory declared) and, with `memory_withheld`, pages that shaders using +/// title memory marked; the bitmaps are cleared. Before the copy-backs of /// declared ranges, which disarm the copies. // shortcut: marks do not tell lists apart: a page that a withheld list and // another both wrote through views goes back unless the withheld list // declared it. -pub(crate) fn copy_back_marks(withheld: &[(Arc, usize, usize)]) { - let Some(b) = bitmap() else { - return; - }; - #[cfg(feature = "diagnostics")] - let _timed = crate::watch::Timed(std::time::Instant::now(), crate::copystat::C::MarkedUs); - let words = (victory_shader::emit::VIEW_WRITE_BITS / 32) as usize; - // SAFETY: the mapped bitmap; the GPU is done with it (one submission - // runs at a time). - let bits = unsafe { std::slice::from_raw_parts_mut(b.data as *mut u32, words) }; - // Marks of offsets past the bitmap land in its last bit, no copy's. - bits[words - 1] = 0; +pub(crate) fn copy_back_marks(withheld: &[(Arc, usize, usize)], memory_withheld: bool) { let mut marked = Vec::new(); - let used = (marks().end as usize).div_ceil(32).min(words); - for (w, word) in bits[..used].iter_mut().enumerate() { - let mut x = std::mem::take(word); - while x != 0 { - marked.push((w * 32) as u32 + x.trailing_zeros()); - x &= x - 1; + for memory in [false, true] { + let Some(b) = bitmap(memory) else { + continue; + }; + let words = (victory_shader::emit::VIEW_WRITE_BITS / 32) as usize; + // SAFETY: the mapped bitmap; the GPU is done with it (one submission + // runs at a time). + let bits = unsafe { std::slice::from_raw_parts_mut(b.data as *mut u32, words) }; + // Marks of offsets past the bitmap land in its last bit, no copy's. + bits[words - 1] = 0; + let used = (marks().end as usize).div_ceil(32).min(words); + for (w, word) in bits[..used].iter_mut().enumerate() { + let mut x = std::mem::take(word); + while x != 0 && !(memory && memory_withheld) { + marked.push((w * 32) as u32 + x.trailing_zeros()); + x &= x - 1; + } } } + #[cfg(feature = "diagnostics")] + let _timed = crate::watch::Timed(std::time::Instant::now(), crate::copystat::C::MarkedUs); + marked.sort_unstable(); + marked.dedup(); if marked.is_empty() { return; } @@ -1340,7 +1349,7 @@ mod tests { let p = crate::watch::tests::pool(3); let len = 3 * PAGE; register(p, p as u64, len as u64); - let (Some(copy), Some(b)) = (find(p as u64, len as u64), bitmap()) else { + let (Some(copy), Some(b)) = (find(p as u64, len as u64), bitmap(false)) else { unregister(p, p as u64); return; // no host GPU here }; @@ -1366,7 +1375,7 @@ mod tests { // SAFETY: a dword of the mapped bitmap. unsafe { *bits.add(n / 32) |= 1 << (n % 32) }; } - copy_back_marks(&[]); + copy_back_marks(&[], false); // SAFETY: bytes of our pool. let read = |at: usize| unsafe { title(at).read_volatile() }; assert_eq!(read(10), 0xaa, "the shader's byte, page 0"); @@ -1379,6 +1388,37 @@ mod tests { unregister(p, p as u64); } + /// Marks of shaders using title memory stay out of title memory while + /// their results are held back, and are cleared; the other shaders' + /// marks of the same submission go back. + #[test] + fn marks_of_shaders_using_title_memory_are_held_back() { + let p = crate::watch::tests::pool(2); + let len = 2 * PAGE; + register(p, p as u64, len as u64); + let (Some(copy), Some(others), Some(memory)) = (find(p as u64, len as u64), bitmap(false), bitmap(true)) else { + unregister(p, p as u64); + return; // no host GPU here + }; + let base = copy.marks.expect("tracked memory gets mark bits") as usize; + copy.update(p, len); + copy.writing(p, len, true); + copy.write_host((p + 10) as u64, &[0xaa]); + copy.write_host((p + PAGE + 10) as u64, &[0xbb]); + // Page 0 marked by another shader, page 1 by one using title memory. + for (b, n) in [(others, base), (memory, base + 1)] { + // SAFETY: a dword of the mapped bitmap. + unsafe { *(b.data as *mut u32).add(n / 32) |= 1 << (n % 32) }; + } + copy_back_marks(&[], true); + // SAFETY: bytes of our pool. + let read = |at: usize| unsafe { ((p + at) as *const u8).read_volatile() }; + assert_eq!((read(10), read(PAGE + 10)), (0xaa, 0), "page 1 held back"); + // SAFETY: a dword of the mapped bitmap. + assert_eq!(unsafe { *(memory.data as *const u32).add((base + 1) / 32) } & 1 << ((base + 1) % 32), 0, "cleared"); + unregister(p, p as u64); + } + /// Mark bits are handed out in runs and come back joined. #[test] fn mark_runs_are_reused_and_joined() { From a3b0f36e3cfc70257ccb3e01ab308bc2a716cdb4 Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 07:34:27 +0100 Subject: [PATCH 39/83] GPU: dropping a tracker keeps guards another mapping's tracker relies on A take guards a tracked page and every other mapping of the same physical page (the runtime links them when it maps them), so that a write through the title's pool view marks the copy of its tiled heap. But when a tracker went away, every page no tracker held any more got write access back, including a page guarded for a tracker of another mapping: after an exact or buffer copy over the pool view was dropped, the title's writes there went unseen by the loose window over the tiled heap, which stayed clean with stale bytes (shards' sweep: 9,520 such pages, ~620 MB, all guarded at the window's own address; for 2,789 a newer copy held the fresh bytes). Now a page stays guarded while a linked mapping of it is held; the next write there faults once, marks that tracker and opens it. The new test fails without the change (the write through the other view goes unseen). Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/watch.rs | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index ae3975bcca..c823f982f4 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -351,7 +351,10 @@ fn runtime_pages(start: usize, end: usize, views: bool) -> Vec { impl Drop for Tracked { /// Pages no tracker holds any more get write access back, so that the - /// guard set never names memory freed and allocated again. + /// guard set never names memory freed and allocated again; unless another + /// mapping of the page is held: the guard here is that tracker's too (it + /// was set when that tracker took its page), and with it opened a write + /// here went unseen there. fn drop(&mut self) { let mut g = guards(); let mut free = Vec::new(); @@ -365,7 +368,10 @@ impl Drop for Tracked { } } for page in free { - open(&mut g, page); + let watched_elsewhere = g.alias_of.get(&page).is_some_and(|o| o.iter().any(|p| g.holders.contains_key(p))); + if !watched_elsewhere { + open(&mut g, page); + } } } } @@ -1090,6 +1096,22 @@ pub(crate) mod tests { assert_eq!(t.take(a, a + 2 * PAGE), [(a, a + PAGE)]); } + /// A tracker of one mapping going away leaves the guard its page shares + /// with a tracker of another mapping, so a write there still counts (it + /// was opened, and the pages it went unseen in stayed clean). + #[test] + fn a_tracker_dropped_on_one_mapping_leaves_the_other_guarded() { + let (a, b) = twin_views(1); + let t = track(a, PAGE, true).expect("views are tracked"); + let u = track(b, PAGE, true).expect("views are tracked"); + assert_eq!(t.take(a, a + PAGE), [(a, a + PAGE)]); + assert_eq!(u.take(b, b + PAGE), [(b, b + PAGE)]); + drop(u); + // SAFETY: the second view, guarded for `t`'s page too. + unsafe { ((b + 4) as *mut u32).write_volatile(7) }; + assert_eq!(t.take(a, a + PAGE), [(a, a + PAGE)]); + } + /// A write or mapping that runs past the end of the address space (a /// title's `fread` with a huge count) covers up to the end; the sum used /// to overflow. Up there no test has guarded blocks. From b2f6c9559601627e2bccc47bdfffc838fa42fb59 Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 08:25:56 +0100 Subject: [PATCH 40/83] GPU: upload tests count their own texture's uploads What was wrong: the upload tests read a process-wide count of texture uploads, so another test's uploads between their `before` and their submission landed in it: `a_texture_is_uploaded_once_per_submission_and_only_when_written` failed in a parallel run of the crate's tests and passed alone. What changed: each texture's staging state counts its own uploads; the tests read those of their texture (`texture::uploads`, tests only). The process-wide counter had no other reader and is gone. Evidence: the crate's tests three times in a row with 8 threads, 157 passed each time; clippy clean on both feature sets. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/draw.rs | 8 ++++---- crates/victory-gpu/src/texture.rs | 15 ++++++++++++--- 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index e864572f2b..b82900ed3d 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -2384,11 +2384,11 @@ void main(uint3 id : SV_DispatchThreadID) { run(list, &slots, &read, 0, Some(&out), (8, 8)); list.close(); } - let before = crate::texture::UPLOADS.load(Ordering::Relaxed); + let before = crate::texture::uploads(object); host.execute(&[&lists[0], &lists[1]]); // SAFETY: inside the mapped output. let texel = unsafe { (data as *const [f32; 4]).read() }; - (crate::texture::UPLOADS.load(Ordering::Relaxed) - before, texel[0]) + (crate::texture::uploads(object) - before, texel[0]) }; let (n, x) = submit(Some(0x40)); assert_eq!(n, 1, "one upload for two lists"); @@ -2425,9 +2425,9 @@ void main(uint3 id : SV_DispatchThreadID) { readable(&list, &used(ResourceType::Srv), &view, false); run(&list, &slots, &read, 0, Some(&out), (8, 8)); list.close(); - let before = crate::texture::UPLOADS.load(Ordering::Relaxed); + let before = crate::texture::uploads(object); host.execute(&[&list]); - crate::texture::UPLOADS.load(Ordering::Relaxed) - before + crate::texture::uploads(object) - before }; assert_eq!(submit(), 1); assert_eq!(submit(), 1, "its own page written: uploaded"); diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 87611de7df..794077d11f 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -50,6 +50,8 @@ pub(crate) struct Staging { /// memory, hashed instead). tracked: Option, last: Mutex, + /// Uploads [`record_upload`] recorded. + uploads: std::sync::atomic::AtomicU64, } /// What a texture's staging buffer holds: the hash of the memory detiled. @@ -245,11 +247,17 @@ pub(crate) fn record_upload(list: &HostList, copy: &Arc u64 { + let staging = crate::resource::host_copy(resource).and_then(|c| c.staging.lock().unwrap_or_else(|e| e.into_inner()).clone()); + staging.map_or(0, |s| s.uploads.load(std::sync::atomic::Ordering::Relaxed)) +} /// For textures shaders reach through the heap itself, at submission /// (`crate::bindless::uploads`): brings the staging buffer up to date and @@ -546,6 +554,7 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option> { memory, tracked: crate::watch::track(memory as usize, layout_size, true), last: Mutex::default(), + uploads: Default::default(), }); *held = Some(s.clone()); Some(s) From 38994e539d73eac4cd609c9ead80a1abc5a47d5f Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 08:10:01 +0100 Subject: [PATCH 41/83] GPU: what a frame withholds leaves the host copies at the frame's end The withholding rule keeps what lists using title memory wrote out of title memory while frames miss, but not out of the host copies: the GPU keeps reading it there, and since the title never rewrites that memory the copies kept it for good. In a later frame without misses, whose writes go back, a BVH builder program reading such stale results (its record arrays hold its destination addresses) wrote where they pointed: run textures9 died 15 s into the world on a title object holding f16 +-inf pairs, a box16 node's empty bounds, written by the root-UAV byte ranges of a frame four frames after the last miss (title+0x4b6b75). Now everything a frame withholds (the page table's marked pages, root-UAV byte ranges, write marks of shaders using title memory) is noted (`memory::drop_at_frame_end`), and at the frame's end the memory counts as changed in every host copy holding it, aliases too (`watch::retake`), so each takes title memory's bytes at its next refresh, through its tracker. Results computed from memory with no copy live through their own frame only. What the tracers lose: within a frame they still read what the builder wrote; from the next frame on they read the title's memory where the builder's results were withheld, an unbuilt BVH instead of one built from zeros. Both miss everything. Test: `shadow::tests::what_a_frame_withholds_leaves_the_copies_at_its_end` (frame N withholds a record written into a title buffer's copy and an inner buffer's copy; frame N+1 reads title memory's bytes in both; fails without the change). Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/host.rs | 1 + crates/victory-gpu/src/memory.rs | 30 ++++++++++++ crates/victory-gpu/src/shadow.rs | 79 ++++++++++++++++++++++++++------ crates/victory-gpu/src/watch.rs | 8 ++++ 4 files changed, 103 insertions(+), 15 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index d66a9cca24..d0eebce522 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -1117,6 +1117,7 @@ impl Host { } else { shadow.keep_writes(address, len); crate::memory::note_withheld(len as u64); + crate::memory::drop_at_frame_end(address, len); } } for list in runs { diff --git a/crates/victory-gpu/src/memory.rs b/crates/victory-gpu/src/memory.rs index 270037b8b2..47fcaa148f 100644 --- a/crates/victory-gpu/src/memory.rs +++ b/crates/victory-gpu/src/memory.rs @@ -192,10 +192,35 @@ fn withheld_in(frame: u64, missed: u64) -> bool { missed != MISS_NEVER && frame <= missed.saturating_add(1) } +/// Title memory whose host copies hold what shaders wrote this frame and +/// the frame withheld ([`withholding`]; ranges). +static DROPPED: Mutex> = Mutex::new(Vec::new()); + +/// Shaders wrote `[address, address + len)` of title memory in host copies +/// and the frame withheld it: at the frame's end the copies take title +/// memory's bytes again ([`retake_dropped`]). +pub(crate) fn drop_at_frame_end(address: usize, len: usize) { + DROPPED.lock().unwrap_or_else(|e| e.into_inner()).push((address, len)); +} + +/// At a frame's end: what the frame withheld leaves the host copies, so +/// that results computed from memory with no copy (garbage record arrays +/// and node pointers of the BVH builder) do not feed later frames whose +/// writes go back (a box16 node's f16 bounds over a title object, run +/// textures9). Each copy holding such memory takes it from title memory at +/// its next refresh, through its tracker. +fn retake_dropped() { + let dropped = std::mem::take(&mut *DROPPED.lock().unwrap_or_else(|e| e.into_inner())); + for (address, len) in dropped { + crate::watch::retake(address, len); + } +} + /// Logs what title memory did since the last call, if anything: a line per /// presented frame while shaders use it. pub(crate) fn log_frame() { FRAMES.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + retake_dropped(); let s = stats(std::mem::take); if s.uses.is_empty() && s.written + s.withheld + s.withheld_bytes + s.missed_pages + s.missed_regions == 0 { return; @@ -473,6 +498,11 @@ pub(crate) fn bind(list: &HostList, key: usize) -> Option { // the title's own data (garbage pointers in title threads, run c1), // nor while any list using title memory misses ([`withholding`]). let withheld = if pages + regions > 0 || withholding() { writes.len() as u64 } else { 0 }; + if withheld > 0 { + for &(_, at) in &writes { + drop_at_frame_end(at as usize, 1 << 16); + } + } let mut written = 0; for &(k, at) in writes.iter().take_while(|_| withheld == 0) { let n = copies[k].copy_back_page(at as usize); diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 7fd6923cfd..3fa5d3b459 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -776,7 +776,7 @@ pub(crate) fn view_writes(memory: bool) -> Option { // another both wrote through views goes back unless the withheld list // declared it. pub(crate) fn copy_back_marks(withheld: &[(Arc, usize, usize)], memory_withheld: bool) { - let mut marked = Vec::new(); + let (mut marked, mut held) = (Vec::new(), Vec::new()); for memory in [false, true] { let Some(b) = bitmap(memory) else { continue; @@ -790,8 +790,9 @@ pub(crate) fn copy_back_marks(withheld: &[(Arc, usize, usize)], memory_w let used = (marks().end as usize).div_ceil(32).min(words); for (w, word) in bits[..used].iter_mut().enumerate() { let mut x = std::mem::take(word); - while x != 0 && !(memory && memory_withheld) { - marked.push((w * 32) as u32 + x.trailing_zeros()); + let into = if memory && memory_withheld { &mut held } else { &mut marked }; + while x != 0 { + into.push((w * 32) as u32 + x.trailing_zeros()); x &= x - 1; } } @@ -800,23 +801,28 @@ pub(crate) fn copy_back_marks(withheld: &[(Arc, usize, usize)], memory_w let _timed = crate::watch::Timed(std::time::Instant::now(), crate::copystat::C::MarkedUs); marked.sort_unstable(); marked.dedup(); + let page_of = |m: &Marks, n: u32| { + let (&base, copy) = m.owners.range(..=n).next_back()?; + let copy = copy.upgrade()?; + let k = n - base; + (k < pages(copy.start, copy.len)).then(|| { + let page = (((copy.start >> 16) + u64::from(k)) << 16) as usize; + (copy, page) + }) + }; + // Held back: dropped from the copies at the frame's end. + if !held.is_empty() { + let m = marks(); + for (_, page) in held.into_iter().filter_map(|n| page_of(&m, n)) { + crate::memory::drop_at_frame_end(page, PAGE); + } + } if marked.is_empty() { return; } let pages: Vec<(Arc, usize)> = { let m = marks(); - marked - .iter() - .filter_map(|&n| { - let (&base, copy) = m.owners.range(..=n).next_back()?; - let copy = copy.upgrade()?; - let k = n - base; - (k < pages(copy.start, copy.len)).then(|| { - let page = (((copy.start >> 16) + u64::from(k)) << 16) as usize; - (copy, page) - }) - }) - .collect() + marked.iter().filter_map(|&n| page_of(&m, n)).collect() }; for (copy, page) in pages { if withheld @@ -1419,6 +1425,49 @@ mod tests { unregister(p, p as u64); } + /// What a frame withheld leaves every host copy of its memory at the + /// frame's end (run textures9's shape): in frame N a program using title + /// memory writes a record into the copies and the frame misses, so it + /// stays out of title memory but in the copies for the GPU; in frame + /// N+1, which misses nothing, a program reading the record must see + /// title memory's bytes, not frame N's, in a title buffer's copy and in + /// an inner buffer's copy of the same pages alike. + #[test] + fn what_a_frame_withholds_leaves_the_copies_at_its_end() { + let p = crate::watch::tests::pool(2); + let len = 2 * PAGE; + // SAFETY: a byte of our pool. + unsafe { ((p + 16) as *mut u8).write_volatile(0x11) }; + register(p, p as u64, len as u64); + register(p + 1, p as u64, PAGE as u64); + let (Some(outer), Some(inner)) = (find(p as u64, len as u64), find(p as u64 + 16, 16)) else { + unregister(p + 1, p as u64); + unregister(p, p as u64); + return; // no host GPU here + }; + assert!(!Arc::ptr_eq(&outer, &inner)); + let byte = |c: &Shadow| c.read_host(p as u64 + 16, 1)[0] & 0xff; + for c in [&outer, &inner] { + let (start, n) = c.range(); + c.update(start as usize, n as usize); + c.writing(start as usize, n as usize, false); + c.write_host(p as u64 + 16, &[0x22]); + c.keep_writes(start as usize, n as usize); + } + crate::memory::drop_at_frame_end(p + 16, 4); + assert_eq!((byte(&outer), byte(&inner)), (0x22, 0x22), "frame N: the GPU's copies keep it"); + crate::memory::log_frame(); + for c in [&outer, &inner] { + let (start, n) = c.range(); + c.update(start as usize, n as usize); + } + assert_eq!((byte(&outer), byte(&inner)), (0x11, 0x11), "frame N+1: title memory's bytes"); + // SAFETY: as above. + assert_eq!(unsafe { ((p + 16) as *const u8).read_volatile() }, 0x11, "title memory untouched"); + unregister(p + 1, p as u64); + unregister(p, p as u64); + } + /// Mark bits are handed out in runs and come back joined. #[test] fn mark_runs_are_reused_and_joined() { diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index c823f982f4..a9c147e0d8 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -722,6 +722,14 @@ pub fn title_memory_remapped(at: usize, len: usize) { } } +/// What shaders wrote into host copies of `[at, at + len)` is dropped: +/// every copy holding the memory takes it from title memory again at its +/// next refresh (the pages count as changed in each, aliases too). +pub(crate) fn retake(at: usize, len: usize) { + let (first, last) = (at / PAGE, at.saturating_add(len).div_ceil(PAGE)); + changed(&mut guards(), first, last, false); +} + /// The runtime mapped the page at `at` where `others` show it already: the /// pages are linked both ways, and if we guard it there, it is guarded here /// too (a write through the new mapping must not go unseen by the trackers From ed10c274a0a0abd005e569fb9bf5bff4484b49c6 Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 09:06:39 +0100 Subject: [PATCH 42/83] GPU: the statistics line no longer walks the process heaps The video-memory line of diagnostics builds gave the committed bytes of every process heap through HeapSummary, once per stats window. That walks the multi-gigabyte process heap under its lock: in run perf15 (stack samples every second over the intro) it was 7.7 % of the submitting thread's samples, about half a second each time, and a title audio thread was waiting in our counting allocator's alloc_zeroed for the same share meanwhile. Every measured run had one such stall per window, in the frame time of the window it fell in. The line keeps the Rust heap's bytes, which the allocator counts for free. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/copystat.rs | 21 --------------------- crates/victory-gpu/src/host.rs | 3 +-- 2 files changed, 1 insertion(+), 23 deletions(-) diff --git a/crates/victory-gpu/src/copystat.rs b/crates/victory-gpu/src/copystat.rs index 2b183647cd..792d942953 100644 --- a/crates/victory-gpu/src/copystat.rs +++ b/crates/victory-gpu/src/copystat.rs @@ -417,24 +417,3 @@ unsafe impl std::alloc::GlobalAlloc for CountingAlloc { q } } - -/// Bytes committed in every heap of the process (ours and the title's C -/// runtime share the process heap). -pub(crate) fn heaps_committed() -> u64 { - use windows_sys::Win32::System::Memory::{GetProcessHeaps, HEAP_SUMMARY, HeapSummary}; - let mut heaps = vec![std::ptr::null_mut(); 256]; - // SAFETY: a buffer of that many handles. - let n = unsafe { GetProcessHeaps(heaps.len() as u32, heaps.as_mut_ptr()) } as usize; - heaps.truncate(n.min(heaps.len())); - heaps - .iter() - .map(|&h| { - let mut s = HEAP_SUMMARY { - cb: size_of::() as u32, - ..Default::default() - }; - // SAFETY: a live heap handle and a sized structure. - if unsafe { HeapSummary(h, 0, &mut s) } != 0 { s.cbCommitted as u64 } else { 0 } - }) - .sum() -} diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index d0eebce522..f989c9b7d6 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -2543,10 +2543,9 @@ impl Meter { tracing::info!( "video memory: {local:.0} MB of a {budget:.0} MB budget on the card, \ {system:.0} MB of {system_budget:.0} MB in system memory; process commit {:.0} MB, \ - working set {:.0} MB; process heaps {:.0} MB (Rust {:.0} MB); texture staging {:.0} MB; placed textures made {:.0} MB; list upload memory {} blocks {:.0} MB", + working set {:.0} MB; Rust heap {:.0} MB; texture staging {:.0} MB; placed textures made {:.0} MB; list upload memory {} blocks {:.0} MB", commit as f64 / 1e6, working_set as f64 / 1e6, - crate::copystat::heaps_committed() as f64 / 1e6, crate::copystat::HEAP_BYTES.load(Ordering::Relaxed) as f64 / 1e6, crate::texture::STAGING_BYTES.load(Ordering::Relaxed) as f64 / 1e6, crate::resource::PLACED_BYTES.load(Ordering::Relaxed) as f64 / 1e6, From 36ca299602a2181025d912ebe318a4670b09220a Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 09:05:04 +0100 Subject: [PATCH 43/83] GPU: a retake marks the copies without opening their guards At every presented frame the copies of title memory a withholding frame's shaders wrote take it again (`retake_dropped`). `retake` did that through `changed`, which also gives write access back to every guarded 64 KiB page of the range, one VirtualProtect each, under the guard lock that title threads' guard faults wait on. Title memory did not change, so opening the guards bought nothing: the next take only re-guarded them, and title writes meanwhile went through unseen by the guard (marked anyway by the retake). Run perf15 (stack samples every second over the intro, main 38994e53): 15.4 % of the submitting thread's samples were in retake -> changed_here, waiting in the kernel, the largest item after the GPU wait (30.8 %) and the refresh copies (23.1 %). Now a retake marks the pages changed in every tracker holding them and in the trackers of their other mappings, and leaves the guards in place: the next refresh copies the pages from title memory, `take` finds them guarded already, and a later title write still faults and marks them. The test fails with the old body (the page comes back read-write). Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/watch.rs | 63 +++++++++++++++++++++++++++++++-- 1 file changed, 61 insertions(+), 2 deletions(-) diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index a9c147e0d8..a363f99d07 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -724,10 +724,28 @@ pub fn title_memory_remapped(at: usize, len: usize) { /// What shaders wrote into host copies of `[at, at + len)` is dropped: /// every copy holding the memory takes it from title memory again at its -/// next refresh (the pages count as changed in each, aliases too). +/// next refresh (the pages count as changed in each, aliases too). Title +/// memory itself did not change, so its guards stay (opened page by page, +/// they cost ~15 % of the submitting thread at each frame end, run perf15). pub(crate) fn retake(at: usize, len: usize) { let (first, last) = (at / PAGE, at.saturating_add(len).div_ceil(PAGE)); - changed(&mut guards(), first, last, false); + let g = guards(); + let others: Vec = g.alias_of.range(first..last).flat_map(|(_, o)| o.iter().copied()).collect(); + mark(&g, first, last); + for page in others { + mark(&g, page, page + 1); + } +} + +/// Pages `[first, last)` count as changed in every tracker holding them. +fn mark(g: &Guards, first: usize, last: usize) { + for (&page, holders) in g.holders.range(first..last) { + for c in holders { + let mut set = c.0.lock().unwrap_or_else(|e| e.into_inner()); + set_dirty(c.2, true); + set.insert(page); + } + } } /// The runtime mapped the page at `at` where `others` show it already: the @@ -1120,6 +1138,47 @@ pub(crate) mod tests { assert_eq!(t.take(a, a + PAGE), [(a, a + PAGE)]); } + /// A retake has every copy of the memory, and of its other mappings, + /// take it again, and leaves it guarded: a later write still counts. + #[test] + fn a_retake_marks_the_copies_and_keeps_the_guard() { + use windows_sys::Win32::System::Memory::{MEMORY_BASIC_INFORMATION, PAGE_READONLY, VirtualQuery}; + let protection = |at: usize| { + // SAFETY: plain data filled in by the query. + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + unsafe { VirtualQuery(at as *const _, &mut info, size_of_val(&info)) }; + info.Protect + }; + let (a, b) = twin_views(2); + let t = track(a, 2 * PAGE, true).expect("views are tracked"); + let u = track(b, 2 * PAGE, true).expect("views are tracked"); + assert_eq!(t.take(a, a + 2 * PAGE), [(a, a + 2 * PAGE)]); + assert_eq!(u.take(b, b + 2 * PAGE), [(b, b + 2 * PAGE)]); + assert!(t.clean() && u.clean()); + retake(a + PAGE + 16, 32); + // Marked in both copies, the second mapping's too, still guarded. + assert!(!t.clean() && !u.clean()); + assert!(t.changed((a + PAGE) / PAGE) && u.changed((b + PAGE) / PAGE)); + assert!(!t.changed(a / PAGE)); + assert_eq!(protection(a + PAGE), PAGE_READONLY); + assert_eq!(protection(b + PAGE), PAGE_READONLY); + // Taken again (the copies re-copy that page), then guarded and clean. + assert_eq!(t.take(a, a + 2 * PAGE), [(a + PAGE, a + 2 * PAGE)]); + assert_eq!(u.take(b, b + 2 * PAGE), [(b + PAGE, b + 2 * PAGE)]); + assert!(t.clean() && u.clean()); + assert_eq!(protection(a + PAGE), PAGE_READONLY); + // SAFETY: the second view, guarded all along. + unsafe { ((b + PAGE + 8) as *mut u32).write_volatile(3) }; + assert_eq!(t.take(a, a + 2 * PAGE), [(a + PAGE, a + 2 * PAGE)]); + assert_eq!(u.take(b, b + 2 * PAGE), [(b + PAGE, b + 2 * PAGE)]); + // A retake while marked and guarded, then a drop: nothing breaks. + retake(a, 2 * PAGE); + drop(u); + assert_eq!(t.take(a, a + 2 * PAGE), [(a, a + 2 * PAGE)]); + assert!(t.clean()); + } + /// A write or mapping that runs past the end of the address space (a /// title's `fread` with a huge count) covers up to the end; the sum used /// to overflow. Up there no test has guarded blocks. From 658a0d1993350029ba42b63197478a0c5a231040 Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 09:50:22 +0100 Subject: [PATCH 44/83] GPU: a retake marks host buffer copies alone, not textures' staging What was wrong: a retake (what a frame withheld leaves the host copies) marked the memory changed in every tracker holding it: host buffer copies, but also textures' staging and descriptor heaps, whose contents come from title memory, which did not change, and which shaders' writes never reach. Placed textures over withheld ranges (every world frame withholds 280-9,300 pages) were detiled and uploaded again each frame: 97 MB a frame, 19 % of all texture uploads (run evict3, by each page's last reason). What changed: trackers of host buffer copies are made by `watch::track_copy`, and a retake marks only those. Evidence: test `watch::tests::a_retake_marks_buffer_copies_alone` (a copy's and a texture's tracker over one range: the retake marks the copy's alone, a later title write marks both); the retake test now uses copies' trackers. The crate's tests twice with 8 threads. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/shadow.rs | 2 +- crates/victory-gpu/src/watch.rs | 56 +++++++++++++++++++++++++------- 2 files changed, 46 insertions(+), 12 deletions(-) diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 3fa5d3b459..01fcd28959 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -211,7 +211,7 @@ impl Shadow { /// [`Shadow::new`] of a copy in a run of a shared buffer (`data` and /// `gpu` are the run's). fn new_at(buffer: ID3D12Resource, data: *mut u8, gpu: u64, start: u64, len: u64, slice: Option) -> Arc { - let tracked = crate::watch::track(start as usize, len as usize, true); + let tracked = crate::watch::track_copy(start as usize, len as usize, true); let marks = tracked.as_ref().and_then(|_| marks().take(pages(start, len))); let shadow = Arc::new(Shadow { buffer, diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index a363f99d07..aaeaa0e9fa 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -44,8 +44,9 @@ use std::sync::{Arc, Mutex}; pub(crate) const PAGE: usize = 64 << 10; /// The pages a tracker has not taken since they changed, what it saves of -/// pages it armed, and its bit in [`DIRTY`] (none: always taken as dirty). -struct Changed(Mutex>, Mutex, Option); +/// pages it armed, its bit in [`DIRTY`] (none: always taken as dirty), and +/// whether it is a host buffer copy's (the only trackers [`retake`] marks). +struct Changed(Mutex>, Mutex, Option, bool); /// A bit per tracker, set while it holds changed pages: set and cleared /// under the tracker's lock, read without one ([`Tracked::clean`]). Dense, @@ -266,6 +267,16 @@ fn guard_aliases(g: &mut Guards, pairs: &[(usize, usize)]) { /// Only the pages of the range that are such memory are tracked; the rest is /// never guarded and is copied whole at each use, as memory with no tracker. pub(crate) fn track(start: usize, len: usize, views: bool) -> Option { + track_as(start, len, views, false) +} + +/// [`track`] for a host buffer copy: what shaders write lands in it, so a +/// [`retake`] of its memory marks it. +pub(crate) fn track_copy(start: usize, len: usize, views: bool) -> Option { + track_as(start, len, views, true) +} + +fn track_as(start: usize, len: usize, views: bool, copy: bool) -> Option { if len == 0 { return None; } @@ -288,7 +299,7 @@ pub(crate) fn track(start: usize, len: usize, views: bool) -> Option { // A tracker with untracked parts is never clean: no bit. let bit = if untracked.is_empty() { dirty_bit() } else { None }; set_dirty(bit, true); - let changed = Arc::new(Changed(Mutex::new(pages.iter().copied().collect()), Mutex::default(), bit)); + let changed = Arc::new(Changed(Mutex::new(pages.iter().copied().collect()), Mutex::default(), bit, copy)); let mut g = guards(); for &page in &pages { g.holders.entry(page).or_default().push(changed.clone()); @@ -723,10 +734,13 @@ pub fn title_memory_remapped(at: usize, len: usize) { } /// What shaders wrote into host copies of `[at, at + len)` is dropped: -/// every copy holding the memory takes it from title memory again at its -/// next refresh (the pages count as changed in each, aliases too). Title -/// memory itself did not change, so its guards stay (opened page by page, -/// they cost ~15 % of the submitting thread at each frame end, run perf15). +/// every host buffer copy holding the memory takes it from title memory +/// again at its next refresh (the pages count as changed in each, aliases +/// too). Title memory itself did not change, so its guards stay (opened page +/// by page, they cost ~15 % of the submitting thread at each frame end, run +/// perf15), and other trackers (textures' staging, heaps) are left alone: +/// shaders' writes never reach them (marked, textures over withheld ranges +/// were uploaded again for nothing: 19 % of the uploads, run evict3). pub(crate) fn retake(at: usize, len: usize) { let (first, last) = (at / PAGE, at.saturating_add(len).div_ceil(PAGE)); let g = guards(); @@ -737,10 +751,11 @@ pub(crate) fn retake(at: usize, len: usize) { } } -/// Pages `[first, last)` count as changed in every tracker holding them. +/// Pages `[first, last)` count as changed in every host buffer copy's +/// tracker holding them. fn mark(g: &Guards, first: usize, last: usize) { for (&page, holders) in g.holders.range(first..last) { - for c in holders { + for c in holders.iter().filter(|c| c.3) { let mut set = c.0.lock().unwrap_or_else(|e| e.into_inner()); set_dirty(c.2, true); set.insert(page); @@ -1151,8 +1166,8 @@ pub(crate) mod tests { info.Protect }; let (a, b) = twin_views(2); - let t = track(a, 2 * PAGE, true).expect("views are tracked"); - let u = track(b, 2 * PAGE, true).expect("views are tracked"); + let t = track_copy(a, 2 * PAGE, true).expect("views are tracked"); + let u = track_copy(b, 2 * PAGE, true).expect("views are tracked"); assert_eq!(t.take(a, a + 2 * PAGE), [(a, a + 2 * PAGE)]); assert_eq!(u.take(b, b + 2 * PAGE), [(b, b + 2 * PAGE)]); assert!(t.clean() && u.clean()); @@ -1179,6 +1194,25 @@ pub(crate) mod tests { assert!(t.clean()); } + /// A retake marks host buffer copies holding the memory, not other + /// trackers of it (a texture's staging): shaders' writes reach only the + /// copies. A title write still marks both. + #[test] + fn a_retake_marks_buffer_copies_alone() { + let p = pool(2); + let copy = track_copy(p, 2 * PAGE, true).expect("pool memory is tracked"); + let texture = track(p, 2 * PAGE, true).expect("pool memory is tracked"); + assert_eq!(copy.take(p, p + 2 * PAGE), [(p, p + 2 * PAGE)]); + assert_eq!(texture.take(p, p + 2 * PAGE), [(p, p + 2 * PAGE)]); + retake(p + PAGE, 16); + assert!(copy.changed(p / PAGE + 1), "the copy takes it again"); + assert!(!texture.changed(p / PAGE + 1) && texture.clean(), "the texture's tracker is left alone"); + assert_eq!(copy.take(p, p + 2 * PAGE), [(p + PAGE, p + 2 * PAGE)]); + // SAFETY: a page of our pool, guarded: the handler opens it. + unsafe { ((p + PAGE + 8) as *mut u8).write_volatile(1) }; + assert!(copy.changed(p / PAGE + 1) && texture.changed(p / PAGE + 1), "a title write marks both"); + } + /// A write or mapping that runs past the end of the address space (a /// title's `fread` with a huge count) covers up to the end; the sum used /// to overflow. Up there no test has guarded blocks. From 29210929d8d84915975e46209c5e84066ebdc76c Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 09:49:41 +0100 Subject: [PATCH 45/83] HLE: writes into physical pages are reported where the pages show when the write ends DirectStorage writes streamed data into physical pages through views of its own and then tells the title views showing those pages, so that the GPU side's host copies of them take the new bytes. The list of addresses was looked up when the write started. A page window's decode (zlib or BCPack) takes milliseconds, and the title maps streamed pages into its GPU heap meanwhile (CopyPageMappingsBatchX): the remap marks the copies there, a refresh can take the page before the bytes land (zeros, or part of them), and the report at the end named only the old addresses, so the copy at the new one stayed stale with a clean tracker for good. The addresses are now looked up when the write ends (PageWindow::drop, after the copy in write_physical). An address mapped during the write is reported; one that stopped showing the page during the write is not, and needs not be: the unmap itself marked the copies there, and they read the address's new contents at their next refresh. A mapping made after the report is marked by its own remap. Test page_windows_report_where_the_pages_show_when_done: a page shown at A is mapped at B and unmapped from A while a window writes it; the drop reports B only (and write_physical the same). On the previous code it reports A. Found with the meshlet culling's copies: in title runs 5-8 % of culled batches read meshlet buffers whose host copies (4 MiB windows over the GPU heap's mapped pages) held zeros where title memory held the buffer, with the tracker clean: whole batches culled, run-dependent. Co-Authored-By: Claude Opus 5.5 --- crates/victory-hle/src/modules/xmem.rs | 54 +++++++++++++++++++++++--- 1 file changed, 48 insertions(+), 6 deletions(-) diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index 495da2858f..5b515a04a7 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -441,10 +441,18 @@ fn shown_at(pages: &[usize]) -> Vec { /// view showing them (DirectStorage's page destinations). fn report_written(shown: &[usize]) { for &page in shown { + #[cfg(test)] + REPORTED.with(|r| r.borrow_mut().push(page)); drop(victory_gpu::kernel_will_write(page, PAGE)); } } +#[cfg(test)] +thread_local! { + /// The title addresses this thread's writes into physical pages reported. + static REPORTED: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; +} + static PHYSICAL: LazyLock> = LazyLock::new(|| { Mutex::new(Physical { // Page numbers are opaque to titles; 0 stays unused. @@ -622,7 +630,6 @@ pub(crate) fn write_physical(pages: &[usize], offset: usize, data: &[u8]) -> boo let Some(runs) = runs(pages, offset, data.len()) else { return false; }; - let shown = shown_at(pages.get(offset / PAGE..(offset + data.len()).div_ceil(PAGE)).unwrap_or(&[])); let (mut within, mut done) = (offset % PAGE, 0); for (slice, n) in &runs { let Some(mut view) = View::map(slice, *n) else { @@ -632,7 +639,8 @@ pub(crate) fn write_physical(pages: &[usize], offset: usize, data: &[u8]) -> boo view.bytes()[within..within + k].copy_from_slice(&data[done..done + k]); (within, done) = (0, done + k); } - report_written(&shown); + // Where the pages show once written (see `PageWindow`). + report_written(&shown_at(pages.get(offset / PAGE..(offset + data.len()).div_ceil(PAGE)).unwrap_or(&[]))); true } @@ -643,13 +651,18 @@ pub(crate) struct PageWindow { view: View, within: usize, len: usize, - /// Title views showing the pages, told when the window is done. - shown: Vec, + /// The pages (page numbers) the bytes reach: the title views showing + /// them when the window is done are told. Looked up then, not when the + /// window opens: a decode takes milliseconds, and the title may map a + /// page at another address meanwhile (its GPU heap); a copy that took + /// the page there before the bytes landed would never hear of them. An + /// address that stops showing a page meanwhile was told by the unmap. + pages: Vec, } impl Drop for PageWindow { fn drop(&mut self) { - report_written(&self.shown); + report_written(&shown_at(&self.pages)); } } @@ -674,7 +687,7 @@ pub(crate) fn page_window(pages: &[usize], offset: usize, len: usize) -> Option< view: View::map(slice, *n)?, within: offset % PAGE, len, - shown: shown_at(pages.get(offset / PAGE..(offset + len).div_ceil(PAGE)).unwrap_or(&[])), + pages: pages.get(offset / PAGE..(offset + len).div_ceil(PAGE)).unwrap_or(&[]).to_vec(), }) } @@ -1350,6 +1363,35 @@ mod tests { assert_eq!(XMemFreePhysicalPages(1, b.as_ptr()), 1); } + /// A page mapped at a second address while a window writes it is + /// reported there too when the window is done (the title maps streamed + /// pages into its GPU heap while their reads decode); an address that + /// stopped showing it meanwhile is not. + #[test] + fn page_windows_report_where_the_pages_show_when_done() { + let pages = allocate(1); + let reserve = || XMemVirtualAlloc(std::ptr::null_mut(), PAGE, MEM_RESERVE | PAGES_64K, 0, PAGE_READWRITE); + let (a, b) = (reserve(), reserve()); + assert!(!a.is_null() && !b.is_null()); + assert_eq!(XMemMapPhysicalPages(a, 1, pages.as_ptr()), a); + REPORTED.with(|r| r.borrow_mut().clear()); + let mut window = page_window(&pages, 0, 16).expect("one run"); + // Mapped at `b`, unmapped from `a`, while the bytes are written. + assert_eq!(XMemMapPhysicalPages(b, 1, pages.as_ptr()), b); + assert_eq!(XMemMapPhysicalPages(a, 1, std::ptr::null()), a); + window.bytes().fill(3); + drop(window); + assert_eq!(REPORTED.with(|r| r.borrow().clone()), [b as usize]); + // SAFETY: mapped read-write. + assert_eq!(unsafe { b.cast::().read() }, 3); + // `write_physical` the same way. + REPORTED.with(|r| r.borrow_mut().clear()); + assert!(write_physical(&pages, 0, &[4])); + assert_eq!(REPORTED.with(|r| r.borrow().clone()), [b as usize]); + assert_eq!(XMemMapPhysicalPages(b, 1, std::ptr::null()), b); + assert_eq!(XMemFreePhysicalPages(1, pages.as_ptr()), 1); + } + #[test] fn page_windows_cover_one_run_in_place() { let (a, b) = (allocate(3), allocate(1)); From fdf34ab7bac24cf8d9abc93641bddc19e02901e1 Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 06:45:00 +0100 Subject: [PATCH 46/83] GPU: texture staging buffers come from a small shared pool, not one per texture What was wrong: each uploaded texture kept an upload buffer of its own size for life, in system memory: 0.2 GB on main (run textures5), 2.6-2.8 GB once placed textures are made when shaders read them (run integ2). Making a buffer for every upload instead (066fbbeb, run textures8) released them, but the menu movie, which rewrites 12.7 MB of textures every frame, then paid ~5 ms a frame for fresh buffers: texture preparation 12.7-13.8 ms in textures8 against 8.0-8.4 in textures7. What changed: every upload is recorded at submission by the submission's own list (23a4b62b), and `Host::execute` waits for each submission, so a staging buffer is free again from the next submission on. Detiles take a buffer of the same size from a pool shared by all textures, or make one; the buffers one submission used go back to the pool before the next one's uploads, and the pool keeps at most 64 MiB of free buffers (oldest dropped). The staging state keeps only the layout, the change tracking and the last hash. The memory line no longer gives "texture staging". Evidence: textures8 (one buffer per upload) ended at 7,871 MB of system memory and 24,771 MB of commit against textures7's 8,254 and 25,130 (206 MB of staging gone), no out-of-memory and no removal in 200 s. Test `draw::tests::a_texture_owning_its_pages_is_uploaded_on_any_write` now also checks that a reused buffer carries the new bytes (WARP). Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/bindless.rs | 7 +- crates/victory-gpu/src/draw.rs | 17 ++- crates/victory-gpu/src/host.rs | 3 +- crates/victory-gpu/src/texture.rs | 186 +++++++++++++++++++---------- 4 files changed, 137 insertions(+), 76 deletions(-) diff --git a/crates/victory-gpu/src/bindless.rs b/crates/victory-gpu/src/bindless.rs index 974df96aa4..ba511b65d3 100644 --- a/crates/victory-gpu/src/bindless.rs +++ b/crates/victory-gpu/src/bindless.rs @@ -202,6 +202,7 @@ pub(crate) fn uploads( static LIST: Mutex = Mutex::new(Holder(None)); const SHADER_RESOURCE: u32 = 0x40 | 0x80; let mut guard = LIST.lock().unwrap_or_else(|e| e.into_inner()); + crate::texture::recycle(); match &guard.0 { // Closed by the last submission, which has run. Some(list) => list.reset(), @@ -212,8 +213,10 @@ pub(crate) fn uploads( let mut recorded = false; let mut staged = std::collections::HashSet::new(); for (staging, copy) in textures { - if staged.insert(Arc::as_ptr(staging)) && staging.refresh() { - crate::texture::record_upload(list, copy, staging); + if staged.insert(Arc::as_ptr(staging)) + && let Some(buffer) = staging.refresh() + { + crate::texture::record_upload(list, copy, staging, &buffer); recorded = true; #[cfg(feature = "diagnostics")] UPLOADED.fetch_add(1, Relaxed); diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index b82900ed3d..053a87c412 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -2410,7 +2410,7 @@ void main(uint3 id : SV_DispatchThreadID) { }; let slots = Slots::new(2); let read = compile_cs(READ); - let (out, _) = host.shared_buffer(64 * 64 * 16).unwrap(); + let (out, data) = host.shared_buffer(64 * 64 * 16).unwrap(); // RGBA8 128x128, linear: one whole 64 KiB page. let address = crate::watch::tests::pool(1) as u64; let object = texture_at_address(address, &texture_words(128, 128, 28, 0x100, 0)); @@ -2418,19 +2418,24 @@ void main(uint3 id : SV_DispatchThreadID) { desc[..6].copy_from_slice(&[28, 4, 0x1688, 0, 0, 1]); let view = View::Shader(object as usize, Some(desc)); slots.make(0, &view); - let submit = || { + let submit = |byte: u8| { // SAFETY: the texture's memory, one page. - unsafe { std::ptr::write_bytes(address as *mut u8, 0x40, crate::watch::PAGE) }; + unsafe { std::ptr::write_bytes(address as *mut u8, byte, crate::watch::PAGE) }; let list = host.new_list().unwrap(); readable(&list, &used(ResourceType::Srv), &view, false); run(&list, &slots, &read, 0, Some(&out), (8, 8)); list.close(); let before = crate::texture::uploads(object); host.execute(&[&list]); - crate::texture::uploads(object) - before + // SAFETY: inside the mapped output. + let texel = unsafe { (data as *const [f32; 4]).read() }; + (crate::texture::uploads(object) - before, texel[0]) }; - assert_eq!(submit(), 1); - assert_eq!(submit(), 1, "its own page written: uploaded"); + assert_eq!(submit(0x40).0, 1); + assert_eq!(submit(0x40).0, 1, "its own page written: uploaded"); + let (n, x) = submit(0x80); + assert_eq!(n, 1); + assert!((x - 128.0 / 255.0).abs() < 1e-6, "a reused staging buffer carries the new bytes: {x}"); } /// A depth texture with stencil (the console's 16-bit depth, the diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index f989c9b7d6..b532703ac1 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -2543,11 +2543,10 @@ impl Meter { tracing::info!( "video memory: {local:.0} MB of a {budget:.0} MB budget on the card, \ {system:.0} MB of {system_budget:.0} MB in system memory; process commit {:.0} MB, \ - working set {:.0} MB; Rust heap {:.0} MB; texture staging {:.0} MB; placed textures made {:.0} MB; list upload memory {} blocks {:.0} MB", + working set {:.0} MB; Rust heap {:.0} MB; placed textures made {:.0} MB; list upload memory {} blocks {:.0} MB", commit as f64 / 1e6, working_set as f64 / 1e6, crate::copystat::HEAP_BYTES.load(Ordering::Relaxed) as f64 / 1e6, - crate::texture::STAGING_BYTES.load(Ordering::Relaxed) as f64 / 1e6, crate::resource::PLACED_BYTES.load(Ordering::Relaxed) as f64 / 1e6, crate::list::UPLOADS[0].load(Ordering::Relaxed), crate::list::UPLOADS[1].load(Ordering::Relaxed) as f64 / 1e6, diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 794077d11f..70c052b54b 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -33,13 +33,15 @@ macro_rules! once { }}; } -/// A texture's upload state: the staging buffer laid out as the host -/// texture's subresources, and what was last detiled. +/// A texture's upload state: how a staging buffer lays out the host +/// texture's subresources, and what was last detiled. The buffer itself is +/// taken for each upload from a small pool shared by all textures +/// ([`staging_buffer`]; kept for each texture's life, the buffers took its +/// size again in system memory: 2.6-2.8 GB with placed textures made on +/// read, run integ2). pub(crate) struct Staging { - buffer: ID3D12Resource, - /// Its bytes. + /// A staging buffer's bytes. size: u64, - data: *mut u8, footprints: Vec, rows: Vec, layout: victory_formats::texture::Layout, @@ -54,23 +56,74 @@ pub(crate) struct Staging { uploads: std::sync::atomic::AtomicU64, } -/// What a texture's staging buffer holds: the hash of the memory detiled. +/// What was last detiled: the hash of the memory. #[derive(Default)] struct Last { hash: Option, } -/// Bytes of live staging buffers (the fps line's companion). -pub(crate) static STAGING_BYTES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); +/// Staging buffers for detiles to reuse, by size: the menu movie rewrites +/// the same textures every frame, and a fresh 12.7 MB of upload buffers a +/// frame cost ~5 ms (run textures8). Uploads run only inside +/// `Host::execute`, which waits for each submission, so the buffers of one +/// submission are free from the next on. +struct Buffers { + /// (bytes, buffer, mapping), oldest first. + free: std::collections::VecDeque<(u64, ID3D12Resource, usize)>, + free_bytes: u64, + /// Taken by the submission being prepared. + used: Vec<(u64, ID3D12Resource, usize)>, +} + +// SAFETY: the mappings are persistent mappings of the upload buffers. +unsafe impl Send for Buffers {} + +static BUFFERS: Mutex = Mutex::new(Buffers { + free: std::collections::VecDeque::new(), + free_bytes: 0, + used: Vec::new(), +}); -impl Drop for Staging { - fn drop(&mut self) { - STAGING_BYTES.fetch_sub(self.size, std::sync::atomic::Ordering::Relaxed); +/// Free staging buffers kept at most. +const KEPT_BYTES: u64 = 64 << 20; + +/// Called before a submission's uploads: the buffers of the last one are +/// free again (the oldest dropped past `KEPT_BYTES`). +pub(crate) fn recycle() { + let mut b = BUFFERS.lock().unwrap_or_else(|e| e.into_inner()); + let b = &mut *b; + for e in b.used.drain(..) { + b.free_bytes += e.0; + b.free.push_back(e); + } + while b.free_bytes > KEPT_BYTES + && let Some((n, ..)) = b.free.pop_front() + { + b.free_bytes -= n; } } -// SAFETY: the staging mapping is written only at submission, under -// `last`'s lock; the title memory is only read. +/// A free staging buffer of `size` bytes, or a new one. +fn staging_buffer(size: u64) -> Option<(ID3D12Resource, *mut u8)> { + let mut b = BUFFERS.lock().unwrap_or_else(|e| e.into_inner()); + let e = match b.free.iter().position(|e| e.0 == size) { + Some(i) => { + let e = b.free.remove(i)?; + b.free_bytes -= size; + e + } + None => { + let (buffer, data) = host()?.upload_buffer(size)?; + crate::host::name(&buffer, || "texture staging".into()); + (size, buffer, data as usize) + } + }; + let made = (e.1.clone(), e.2 as *mut u8); + b.used.push(e); + Some(made) +} + +// SAFETY: the title memory is only read, under `last`'s lock. unsafe impl Send for Staging {} // SAFETY: as above. unsafe impl Sync for Staging {} @@ -232,9 +285,14 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) list.defer_texture(staging, copy); } -/// Records into `list` the copy of `staging` into host texture `copy`, -/// leaving it readable by shaders. -pub(crate) fn record_upload(list: &HostList, copy: &Arc, staging: &Staging) { +/// Records into `list` the copy of `buffer` (laid out as `staging` says) +/// into host texture `copy`, leaving it readable by shaders. +pub(crate) fn record_upload( + list: &HostList, + copy: &Arc, + staging: &Staging, + buffer: &ID3D12Resource, +) { const COPY_DEST: u32 = 0x400; const SHADER_RESOURCE: u32 = 0x40 | 0x80; let move_to = |wanted| { @@ -244,9 +302,9 @@ pub(crate) fn record_upload(list: &HostList, copy: &Arc String) { +fn copies( + list: &HostList, + texture: &ID3D12Resource, + staging: &Staging, + buffer: &ID3D12Resource, + name: impl Fn() -> String, +) { for (i, footprint) in staging.footprints.iter().enumerate() { #[cfg(feature = "diagnostics")] { let f = footprint.Footprint; // SAFETY: live resources. - let (gpu, d) = unsafe { (staging.buffer.GetGPUVirtualAddress(), texture.GetDesc()) }; + let (gpu, d) = unsafe { (buffer.GetGPUVirtualAddress(), texture.GetDesc()) }; let len = u64::from(f.RowPitch) * u64::from(staging.rows[i]) * u64::from(f.Depth); list.note_read( || { @@ -330,7 +389,7 @@ fn copies(list: &HostList, texture: &ID3D12Resource, staging: &Staging, name: im }; let from = D3D12_TEXTURE_COPY_LOCATION { // SAFETY: as above. - pResource: unsafe { std::mem::transmute_copy(&staging.buffer) }, + pResource: unsafe { std::mem::transmute_copy(buffer) }, Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: *footprint, @@ -342,20 +401,21 @@ fn copies(list: &HostList, texture: &ID3D12Resource, staging: &Staging, name: im } impl Staging { - /// Detiles the texture memory into the staging buffer if it changed - /// since the last time (and is mapped at all): whether it did. - pub(crate) fn refresh(&self) -> bool { + /// A staging buffer with the texture memory detiled into it if it + /// changed since the last time (and is mapped at all). + pub(crate) fn refresh(&self) -> Option { use std::sync::atomic::Ordering::Relaxed; let started = std::time::Instant::now(); - let (read, changed) = self.refresh_now(); + let (read, buffer) = self.refresh_now(); let preparing = &crate::host::PREPARING; preparing[2].fetch_add(started.elapsed().as_micros() as u64, Relaxed); preparing[3].fetch_add(read as u64, Relaxed); - changed + buffer } - /// Returns the bytes of title memory read, and whether it detiled. - fn refresh_now(&self) -> (usize, bool) { + /// Returns the bytes of title memory read, and the buffer it detiled + /// into. + fn refresh_now(&self) -> (usize, Option) { let size = self.layout.size as usize; let start = self.memory as usize; let mut last = self.last.lock().unwrap_or_else(|e| e.into_inner()); @@ -363,7 +423,7 @@ impl Staging { if let Some(t) = &self.tracked { let ranges = t.take(start, start + size); if ranges.is_empty() { - return (0, false); + return (0, None); } // Read through the copy, which stands unmapped pages: memory of // big pools is too slow to ask page by page. Not kept: it would @@ -380,13 +440,16 @@ impl Staging { } else { let hash = blake3::hash(&read); if last.hash.replace(hash) == Some(hash) { - return (size, false); + return (size, None); } } - self.detile(&read); + let buffer = self.detile(&read); + if buffer.is_none() { + last.hash = None; + } #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexWatched, size as u64); - return (size, true); + return (size, buffer); } if !committed(self.memory, size) { #[cfg(feature = "diagnostics")] @@ -396,7 +459,7 @@ impl Staging { desc = ?self.layout.desc, "a sampled texture's memory is not committed" ); - return (0, false); + return (0, None); } // SAFETY: committed memory of the texture's layout size. let tiled = unsafe { std::slice::from_raw_parts(self.memory, size) }; @@ -404,17 +467,19 @@ impl Staging { #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexHashed, size as u64); if last.hash == Some(hash) { - return (size, false); + return (size, None); } - last.hash = Some(hash); - self.detile(tiled); + let buffer = self.detile(tiled); + last.hash = buffer.is_some().then_some(hash); #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexChanged, size as u64); - (size, true) + (size, buffer) } - /// Detiles `tiled` (the texture's memory) into the staging buffer. - fn detile(&self, tiled: &[u8]) { + /// Detiles `tiled` (the texture's memory) into a new staging buffer + /// (`None` if none could be made or a subresource could not be read). + fn detile(&self, tiled: &[u8]) -> Option { + let (buffer, data) = staging_buffer(self.size)?; #[cfg(feature = "diagnostics")] if tiled.iter().all(|&b| b == 0) { tracing::debug!( @@ -433,17 +498,16 @@ impl Staging { // SAFETY: `subresource_len` clamps `len` to `self.size - footprint.Offset`, // keeping the slice strictly inside the mapped staging buffer even when // GetCopyableFootprints does not pad the final row of the last subresource. - let linear = unsafe { - std::slice::from_raw_parts_mut(self.data.add(footprint.Offset as usize), len) - }; + let linear = unsafe { std::slice::from_raw_parts_mut(data.add(footprint.Offset as usize), len) }; if let Err(e) = self.layout .detile(tiled, mip, slice, linear, pitch, pitch * rows as usize) { tracing::warn!(?e, mip, slice, "texture not detiled"); - return; + return None; } } + Some(buffer) } } @@ -533,20 +597,10 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option> { Some(&mut total), ); } - let (buffer, data) = host.upload_buffer(total)?; - crate::host::name(&buffer, || { - format!( - "staging of {resource:?} {}x{}x{} f{}", - d.Width, d.Height, d.DepthOrArraySize, d.Format.0 - ) - }); tracing::debug!(?desc, total, "texture contents uploaded from title memory"); - STAGING_BYTES.fetch_add(total, std::sync::atomic::Ordering::Relaxed); let layout_size = layout.size as usize; let s = Arc::new(Staging { - buffer, size: total, - data, footprints, rows, layout, From cc5f961259009926aa0139391b294b00bb20b593 Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 07:05:47 +0100 Subject: [PATCH 47/83] GPU: a texture re-detiles only the subresources whose pages changed What was wrong: a tracked texture whose memory changed anywhere was read whole, detiled whole and copied whole into its host texture. Streamed textures change mip by mip, so each arriving mip re-read every other one: up to 430 MB of texture reads a frame in run integ2. What changed: each subresource knows the bytes of the texture's memory it lies in (its first and last texel's offsets in the layout, rounded out to the layout's blocks). A refresh reads only the subresources that the changed ranges touch, keeps those whose bytes changed (per-subresource hashes; none when a whole changed page lies in the subresource's span, as for the whole texture before), detiles and copies only those. The untracked path, which hashes the whole memory, still uploads every subresource. Evidence: test `draw::tests::a_write_into_one_mip_uploads_that_mip_alone` (a 512x512 two-mip texture: both mips at first, then mip 1 alone after a write into it, mip 0 keeping its texels) and the other draw tests on WARP. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/bindless.rs | 4 +- crates/victory-gpu/src/draw.rs | 44 +++++++++ crates/victory-gpu/src/texture.rs | 153 ++++++++++++++++++++++------- 3 files changed, 162 insertions(+), 39 deletions(-) diff --git a/crates/victory-gpu/src/bindless.rs b/crates/victory-gpu/src/bindless.rs index ba511b65d3..aaa4fa4db3 100644 --- a/crates/victory-gpu/src/bindless.rs +++ b/crates/victory-gpu/src/bindless.rs @@ -214,9 +214,9 @@ pub(crate) fn uploads( let mut staged = std::collections::HashSet::new(); for (staging, copy) in textures { if staged.insert(Arc::as_ptr(staging)) - && let Some(buffer) = staging.refresh() + && let Some(upload) = staging.refresh() { - crate::texture::record_upload(list, copy, staging, &buffer); + crate::texture::record_upload(list, copy, staging, &upload); recorded = true; #[cfg(feature = "diagnostics")] UPLOADED.fetch_add(1, Relaxed); diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 053a87c412..e1c410cb22 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -2438,6 +2438,50 @@ void main(uint3 id : SV_DispatchThreadID) { assert!((x - 128.0 / 255.0).abs() < 1e-6, "a reused staging buffer carries the new bytes: {x}"); } + /// A title write into one mip of a texture uploads that mip alone (the + /// pages of the others did not change), and the others keep their + /// contents. + #[test] + fn a_write_into_one_mip_uploads_that_mip_alone() { + let Some(host) = crate::host::host() else { + return; // no host GPU here + }; + let slots = Slots::new(2); + let read = compile_cs(READ); + let (out, data) = host.shared_buffer(64 * 64 * 16).unwrap(); + // RGBA8 512x512 with two mips, linear, in memory the journal follows. + let address = crate::watch::tests::pool(32) as u64; + let mut words = texture_words(512, 512, 28, 0x100, 0); + words[7] = 1 | 2 << 16; + let object = texture_at_address(address, &words); + let (_, desc) = crate::resource::texture_memory(object).unwrap(); + let layout = crate::resource::texture_layout(&desc).unwrap().planes[0].layout.clone(); + let mip1 = layout.mips[1].offset as usize; + // SAFETY: the texture's memory (its layout's size). + unsafe { std::ptr::write_bytes(address as *mut u8, 0x40, layout.size as usize) }; + let mut view = [0u32; 10]; + view[..6].copy_from_slice(&[28, 4, 0x1688, 0, 0, 2]); + let view = View::Shader(object as usize, Some(view)); + slots.make(0, &view); + let submit = || { + let list = host.new_list().unwrap(); + readable(&list, &used(ResourceType::Srv), &view, false); + run(&list, &slots, &read, 0, Some(&out), (8, 8)); + list.close(); + let before = crate::texture::copied(object); + host.execute(&[&list]); + // SAFETY: inside the mapped output. + let texel = unsafe { (data as *const [f32; 4]).read() }; + (crate::texture::copied(object) - before, texel[0]) + }; + assert_eq!(submit().0, 2, "both mips at first"); + // SAFETY: mip 1's bytes (256x256 texels of 4 bytes). + unsafe { std::ptr::write_bytes((address as usize + mip1) as *mut u8, 0x80, 256 * 256 * 4) }; + let (n, x) = submit(); + assert_eq!(n, 1, "mip 1 alone"); + assert!((x - 64.0 / 255.0).abs() < 1e-6, "mip 0 kept: {x}"); + } + /// A depth texture with stencil (the console's 16-bit depth, the /// host's 32-bit float) written through unordered views of its planes, /// then read as depth and stencil: the 16-bit depth arrives as the diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 70c052b54b..ba41fb4e62 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -51,15 +51,43 @@ pub(crate) struct Staging { /// The memory's pages changed since detiled (none: not the runtime's /// memory, hashed instead). tracked: Option, + /// Per subresource, the bytes of the texture's memory it lies in (from + /// its start, whole layout blocks); empty where the layout gives none. + spans: Vec<(usize, usize)>, last: Mutex, - /// Uploads [`record_upload`] recorded. + /// Uploads [`record_upload`] recorded, and the subresources they + /// copied. uploads: std::sync::atomic::AtomicU64, + copied: std::sync::atomic::AtomicU64, } -/// What was last detiled: the hash of the memory. +/// What was last detiled: the hash of the memory (not tracked), or of each +/// subresource's bytes (tracked). #[derive(Default)] struct Last { hash: Option, + hashes: Vec>, +} + +/// Per subresource of `layout` (`mips` per array slice; a 3D texture's +/// are its mips), the bytes of the texture's memory it lies in, rounded out +/// to the layout's blocks; empty if the layout cannot say. +fn spans(layout: &victory_formats::texture::Layout, count: u32, mips: u32) -> Vec<(usize, usize)> { + use victory_formats::texture::Dimension; + let d = &layout.desc; + let block = layout.alignment.max(256); + (0..count) + .map(|i| { + let (mip, slice) = (i % mips, i / mips); + let m = layout.mips.get(mip as usize)?; + let (z0, z1) = if d.dimension == Dimension::Tex3d { (0, m.depth.max(1) - 1) } else { (slice, slice) }; + let first = layout.offset(mip, 0, 0, z0).ok()?; + let last = layout.offset(mip, m.width.max(1) - 1, m.height.max(1) - 1, z1).ok()? + u64::from(d.element_bytes); + let (from, to) = (first / block * block, last.div_ceil(block) * block); + Some((from as usize, (to.min(layout.size)) as usize)) + }) + .collect::>>() + .unwrap_or_default() } /// Staging buffers for detiles to reuse, by size: the menu movie rewrites @@ -291,7 +319,7 @@ pub(crate) fn record_upload( list: &HostList, copy: &Arc, staging: &Staging, - buffer: &ID3D12Resource, + (buffer, subresources): &(ID3D12Resource, Vec), ) { const COPY_DEST: u32 = 0x400; const SHADER_RESOURCE: u32 = 0x40 | 0x80; @@ -302,10 +330,11 @@ pub(crate) fn record_upload( } }; move_to(COPY_DEST); - copies(list, ©.texture, staging, buffer, String::new); + copies(list, ©.texture, staging, buffer, subresources, String::new); move_to(SHADER_RESOURCE); list.keep(buffer); staging.uploads.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + staging.copied.fetch_add(subresources.len() as u64, std::sync::atomic::Ordering::Relaxed); } /// The uploads [`record_upload`] recorded into `resource`'s host texture @@ -317,6 +346,13 @@ pub(crate) fn uploads(resource: This) -> u64 { staging.map_or(0, |s| s.uploads.load(std::sync::atomic::Ordering::Relaxed)) } +/// The subresources those uploads copied (tests, as [`uploads`]). +#[cfg(test)] +pub(crate) fn copied(resource: This) -> u64 { + let staging = crate::resource::host_copy(resource).and_then(|c| c.staging.lock().unwrap_or_else(|e| e.into_inner()).clone()); + staging.map_or(0, |s| s.copied.load(std::sync::atomic::Ordering::Relaxed)) +} + /// For textures shaders reach through the heap itself, at submission /// (`crate::bindless::uploads`): brings the staging buffer up to date and /// records its copy into `list` only if the memory changed since (or was @@ -329,28 +365,31 @@ pub(crate) fn upload_changed(list: &HostList, resource: This, texture: &ID3D12Re let Some(staging) = staging(resource, texture) else { return false; }; - let Some(buffer) = staging.refresh() else { + let Some((buffer, subresources)) = staging.refresh() else { return false; }; const COPY_DEST: u32 = 0x400; crate::list::ensure_state(list, resource, COPY_DEST); - copies(list, texture, &staging, &buffer, || format!("{resource:?}")); + copies(list, texture, &staging, &buffer, &subresources, || format!("{resource:?}")); list.keep(&buffer); true } -/// Records the copy of every subresource of `buffer` (laid out as -/// `staging` says) into `texture` (in the copy destination state); `name` -/// names it in diagnostics notes. +/// Records the copy of `subresources` of `buffer` (laid out as `staging` +/// says) into `texture` (in the copy destination state); `name` names it +/// in diagnostics notes. #[cfg_attr(not(feature = "diagnostics"), allow(unused_variables))] fn copies( list: &HostList, texture: &ID3D12Resource, staging: &Staging, buffer: &ID3D12Resource, + subresources: &[u32], name: impl Fn() -> String, ) { - for (i, footprint) in staging.footprints.iter().enumerate() { + for &i in subresources { + let i = i as usize; + let footprint = &staging.footprints[i]; #[cfg(feature = "diagnostics")] { let f = footprint.Footprint; @@ -402,8 +441,9 @@ fn copies( impl Staging { /// A staging buffer with the texture memory detiled into it if it - /// changed since the last time (and is mapped at all). - pub(crate) fn refresh(&self) -> Option { + /// changed since the last time (and is mapped at all), and the + /// subresources that changed (only those are detiled and to be copied). + pub(crate) fn refresh(&self) -> Option<(ID3D12Resource, Vec)> { use std::sync::atomic::Ordering::Relaxed; let started = std::time::Instant::now(); let (read, buffer) = self.refresh_now(); @@ -414,8 +454,9 @@ impl Staging { } /// Returns the bytes of title memory read, and the buffer it detiled - /// into. - fn refresh_now(&self) -> (usize, Option) { + /// into with the subresources detiled. + fn refresh_now(&self) -> (usize, Option<(ID3D12Resource, Vec)>) { + let all = || (0..self.footprints.len() as u32).collect::>(); let size = self.layout.size as usize; let start = self.memory as usize; let mut last = self.last.lock().unwrap_or_else(|e| e.into_inner()); @@ -425,31 +466,63 @@ impl Staging { if ranges.is_empty() { return (0, None); } + // Only the subresources in the pages that changed (streamed + // textures change page by page; a whole re-read and detile of + // each cost up to 430 MB a frame, run integ2). + let n = self.footprints.len(); + let span = |i: usize| self.spans.get(i).copied().unwrap_or((0, size)); + let touched: Vec = (0..n) + .filter(|&i| { + let (a, b) = span(i); + ranges.iter().any(|&(f, e)| f - start < b && a < e - start) + }) + .collect(); // Read through the copy, which stands unmapped pages: memory of // big pools is too slow to ask page by page. Not kept: it would // double each texture's system memory. let mut read = vec![0u8; size]; - crate::host::copy_mapped(read.as_mut_ptr(), self.memory, size, false); - // A changed page that holds only texture bytes says it changed. - // Pages it shares with other data the title writes (small - // textures): its own bytes decide. (Hashing a movie frame cost - // 8 ms a frame.) - let page = crate::watch::PAGE; - if ranges.iter().any(|&(f, e)| f.next_multiple_of(page) + page <= e) { - last.hash = None; - } else { - let hash = blake3::hash(&read); - if last.hash.replace(hash) == Some(hash) { - return (size, None); + let mut bytes = 0; + let mut done: Vec<(usize, usize)> = Vec::new(); + for &i in &touched { + let (a, b) = span(i); + if !done.contains(&(a, b)) { + // SAFETY: inside the buffer of the texture's size. + crate::host::copy_mapped(unsafe { read.as_mut_ptr().add(a) }, self.memory.wrapping_add(a), b - a, false); + (bytes, _) = (bytes + b - a, done.push((a, b))); } } - let buffer = self.detile(&read); + // A changed page that holds only the subresource's bytes says it + // changed. Pages it shares with other data the title writes + // (small textures): its own bytes decide. (Hashing a movie frame + // cost 8 ms a frame.) + let page = crate::watch::PAGE; + last.hashes.resize(n, None); + let fresh: Vec = touched + .into_iter() + .filter(|&i| { + let (a, b) = span(i); + let (a0, b0) = (start + a, start + b); + if ranges.iter().any(|&(f, e)| f.max(a0).next_multiple_of(page) + page <= e.min(b0)) { + last.hashes[i] = None; + return true; + } + let hash = blake3::hash(&read[a..b]); + last.hashes[i].replace(hash) != Some(hash) + }) + .map(|i| i as u32) + .collect(); + if fresh.is_empty() { + return (bytes, None); + } + let buffer = self.detile(&read, &fresh); if buffer.is_none() { - last.hash = None; + for &i in &fresh { + last.hashes[i as usize] = None; + } } #[cfg(feature = "diagnostics")] - crate::copystat::add(crate::copystat::C::TexWatched, size as u64); - return (size, buffer); + crate::copystat::add(crate::copystat::C::TexWatched, bytes as u64); + return (bytes, buffer.map(|b| (b, fresh))); } if !committed(self.memory, size) { #[cfg(feature = "diagnostics")] @@ -469,16 +542,18 @@ impl Staging { if last.hash == Some(hash) { return (size, None); } - let buffer = self.detile(tiled); + let every = all(); + let buffer = self.detile(tiled, &every); last.hash = buffer.is_some().then_some(hash); #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexChanged, size as u64); - (size, buffer) + (size, buffer.map(|b| (b, every))) } - /// Detiles `tiled` (the texture's memory) into a new staging buffer - /// (`None` if none could be made or a subresource could not be read). - fn detile(&self, tiled: &[u8]) -> Option { + /// Detiles `subresources` of `tiled` (the texture's memory) into a + /// staging buffer (`None` if none could be had or a subresource could + /// not be read). + fn detile(&self, tiled: &[u8], subresources: &[u32]) -> Option { let (buffer, data) = staging_buffer(self.size)?; #[cfg(feature = "diagnostics")] if tiled.iter().all(|&b| b == 0) { @@ -490,8 +565,9 @@ impl Staging { } else { tracing::debug!(memory = ?self.memory, desc = ?self.layout.desc, "a sampled texture detiled"); } - for (i, (footprint, &rows)) in self.footprints.iter().zip(&self.rows).enumerate() { - let (mip, slice) = (i as u32 % self.mips, i as u32 / self.mips); + for &i in subresources { + let (footprint, rows) = (&self.footprints[i as usize], self.rows[i as usize]); + let (mip, slice) = (i % self.mips, i / self.mips); let f = footprint.Footprint; let pitch = f.RowPitch as usize; let len = subresource_len(footprint.Offset, pitch, rows, f.Depth, self.size); @@ -599,6 +675,7 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option> { } tracing::debug!(?desc, total, "texture contents uploaded from title memory"); let layout_size = layout.size as usize; + let spans = spans(&layout, count, u32::from(d.MipLevels)); let s = Arc::new(Staging { size: total, footprints, @@ -607,8 +684,10 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option> { mips: u32::from(d.MipLevels), memory, tracked: crate::watch::track(memory as usize, layout_size, true), + spans, last: Mutex::default(), uploads: Default::default(), + copied: Default::default(), }); *held = Some(s.clone()); Some(s) From 58b5255838d8366cf879263fbdf96296be6ac239 Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 06:12:19 +0100 Subject: [PATCH 48/83] Shaders: an address half set on every taken edge into its join is known An address's high half proven to be 0 (a table or heap address) had to be that constant itself or an `s_addc` of it. `indirect_light_probes: CS_Alpha_Schedule` sets its table pointer's high half (s25 = 0) inside the region that only a skip no lane takes bypasses (compute: every lane runs from the start, so the pre-`s_wqm` lanes are all of them); the skip edge would bring a stale input SGPR, and the join stopped tracking: "an address into a descriptor heap with an untracked high half". A phi whose args on the edges some lane takes (`edge_taken`, the test the previous change uses for descriptors) all have one origin holds that value in every lane that reads it; the address's high half check now looks through such a phi. Only the proof changes: the address lowered is the traced one. Test: `an_address_half_set_where_only_lanes_that_never_run_skip_is_known` (refused without the change). CS_Alpha_Schedule translates. Co-Authored-By: Claude Opus 5.5 --- crates/victory-shader/src/emit/lower.rs | 29 +++++++++++++++++++++++++ crates/victory-shader/src/resource.rs | 19 ++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index ad8868565d..b60e639bce 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -10759,6 +10759,35 @@ mod tests { } } + #[test] + fn an_address_half_set_where_only_lanes_that_never_run_skip_is_known() { + // As `indirect_light_probes:CS_Alpha_Schedule` after its texture: a + // table address whose high half (s25 = 0) is set inside the region + // that only a skip no lane takes bypasses; the skip edge would bring + // the stale input s25. + let words = [ + 0xBE9A_037E, // s_mov_b32 s26, exec_lo + 0xBEFE_097E, // s_wqm_b32 exec_lo, exec_lo + 0xBE98_0300, // s_mov_b32 s24, s0 + 0xBE86_3C1A, // s_and_saveexec_b32 s6, s26 + 0xBF88_0001, // s_cbranch_execz -> join + 0xBE99_0380, // s_mov_b32 s25, 0 + 0xBEFE_0306, // join: s_mov_b32 exec_lo, s6 + 0xF408_0A0C, + 0xFA00_0040, // s_load_dwordx4 s[40:43], s[24:25], 0x40 + 0x3420_0082, // v_lshlrev_b32 v16, 2, v0 + 0x7E06_0280, // v_mov_b32 v3, 0 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xE070_1000, + 0x800A_0310, // buffer_store_dword v3, v16, s[40:43], 0 offen + S_ENDPGM, + ]; + let (_, mut used) = texture_and_uav_tables(); + used.retain(|u| u.user_data == 0); + let layout = vec![root(RootType::Table, 0, 0)]; + lower_with(&words, layout, used).expect("the high half is 0 wherever a lane runs"); + } + #[test] fn a_descriptor_skipped_only_by_lanes_that_never_run_needs_no_source() { // As `indirect_light_probes:CS_Alpha_Schedule`: the texture is diff --git a/crates/victory-shader/src/resource.rs b/crates/victory-shader/src/resource.rs index 0c820642f3..d3513e2eee 100644 --- a/crates/victory-shader/src/resource.rs +++ b/crates/victory-shader/src/resource.rs @@ -950,6 +950,25 @@ impl<'a> Tracer<'a> { || matches!(hi, Term::Value(v) if self.sop2(v, &["s_addc_u32"]).is_some_and( |(_, [a, b])| a == want && b == Term::Const(0) || b == want && a == Term::Const(0) )) + || self.joined_on_taken_edges(hi) == Some(want) + } + + /// What phi `t` holds in every lane that reads it: the one value its + /// args bring along the edges some lane takes (a register set inside a + /// region that only a skip no lane takes bypasses, as + /// `indirect_light_probes:CS_Alpha_Schedule`'s table address). + fn joined_on_taken_edges(&self, t: Term) -> Option { + let Term::Value(v) = t else { return None }; + let (b, i) = self.phis[v.0 as usize]?; + let block = &self.p.blocks[b]; + let mut taken = block.phis[i] + .args + .iter() + .zip(&block.preds) + .filter(|&(_, &q)| self.edge_taken(q, b)) + .map(|(&a, _)| self.origin(a)); + let first = taken.next()?; + taken.all(|x| x == first).then_some(first) } /// `hi` adds something (with carry) to `high`: `s_addc_u32` or From e790217a0e75fdbc23896d0eac929d6447d36f98 Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 06:37:50 +0100 Subject: [PATCH 49/83] Shaders: an image descriptor read only for its size takes it from the host `PS_PuddleDetect` (35 programs; in the intro cutscene ~14 draws a frame, half of them indirect) loads a bindless texture's descriptor whole and reads only its width, height and base level from dwords 1-3, never sampling it, so no use tells the view's kind and the program stopped on "a descriptor read only as data". The host's view addresses (`t1` of the memory space) grow from 8 to 16 bytes a slot: a console descriptor's dwords 0-3 as far as the host knows them. Buffer views keep their title address in dwords 0-1; texture views (shader, unordered and placed ones) get the image descriptor's size fields: width - 1 and height - 1 of the resource's level 0 (dword 1 bits 30-31, dword 2 bits 0-13 and 14-29), an identity swizzle, the view's first and last level (dword 3 bits 12-15, 16-19) and the image type (bits 28-31). The shader answers dwords 1-3 from the table only for an 8-dword load at a whole descriptor (the compiler loads image descriptors whole); shorter loads keep dwords 2 and on refused, so buffer record counts and formats are not guessed. Address, format and tiling bits of a texture's words read 0 (`shortcut:`). Tests: `a_texture_view_gives_its_image_descriptor_size_fields` (the encoding); the title-memory GPU test reads an image descriptor's size words through the table. Shader list: all 35 `PS_PuddleDetect` emit and validate; the cutscene's two variants make pipelines. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor/host.rs | 117 ++++++++++++++++-- crates/victory-gpu/src/resource.rs | 10 ++ crates/victory-shader/src/emit/lower.rs | 28 +++-- .../victory-shader/src/emit/memory_tests.rs | 24 +++- crates/victory-shader/src/emit/mod.rs | 17 ++- crates/victory-shader/src/emit/shader.rs | 5 +- 6 files changed, 167 insertions(+), 34 deletions(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 8eb4c158f7..2a0120a36b 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -50,10 +50,10 @@ pub(crate) struct HostHeap { /// view there, `VIEW_MARK_NONE` for none. Mapped at the address kept /// beside it. marks: Option<(ID3D12Resource, usize)>, - /// Per title slot, the title address of the buffer view it holds, as a - /// buffer descriptor's dwords 0 and 1 (shaders reading a descriptor's - /// address as data, `crate::memory`): the buffer, its mapping and host - /// address, made on first use. + /// Per title slot, the console descriptor's dwords 0-3 as far as the + /// host knows them (shaders reading a descriptor as data, `crate::memory`; + /// [`write_address`]): the buffer, its mapping and host address, made on + /// first use. addresses: std::sync::OnceLock>, /// What the title slots view that title memory feeds (`crate::bindless`). pub(crate) viewed: std::sync::Arc, @@ -542,7 +542,7 @@ impl HostHeap { /// on first use from the slots made so far. pub(crate) fn view_addresses(&self) -> Option { let made = self.addresses.get_or_init(|| { - let (buffer, data) = host()?.upload_buffer(u64::from(self.count) * 8)?; + let (buffer, data) = host()?.upload_buffer(u64::from(self.count) * 16)?; crate::host::name(&buffer, || "view addresses".into()); let data = data as usize; let made = self.made.lock().unwrap_or_else(|e| e.into_inner()); @@ -891,14 +891,83 @@ fn element_size(desc: &D3D12_SHADER_RESOURCE_VIEW_DESC) -> u64 { } } -/// Writes slot `index`'s view address into the view addresses at `data`: -/// a buffer view's title address (dword 0 low, dword 1 bits 0-15 high); -/// zeros for anything else. +/// Writes slot `index`'s words into the view addresses at `data`, 16 bytes +/// a slot: a buffer view's title address (dword 0 low, dword 1 bits 0-15 +/// high), a texture view's size fields ([`texture_words`]), zeros for +/// anything else. fn write_address(data: usize, index: usize, view: Option<&View>) { let address = view.and_then(buffer_range).map_or(0, |(a, _)| a); - let words = [address as u32, (address >> 32) as u32 & 0xFFFF]; - // SAFETY: the mapped view addresses hold 8 bytes per title slot. - unsafe { ((data + 8 * index) as *mut [u32; 2]).write_unaligned(words) }; + let words = match view.and_then(texture_words) { + Some(words) => words, + None => [address as u32, (address >> 32) as u32 & 0xFFFF, 0, 0], + }; + // SAFETY: the mapped view addresses hold 16 bytes per title slot. + 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 +/// view's first and last level (bits 12-15, 16-19) and the image type (bits +/// 28-31). `None` for buffers and samplers. +// shortcut: the address, format and tiling fields read 0 (no translated +// shader reads them: the shader refuses such reads where it can tell), +// and the swizzle is the identity whatever the view's component mapping. +fn texture_words(view: &View) -> Option<[u32; 4]> { + let (resource, desc, unordered) = match view { + View::Shader(r, desc) => (crate::resource::texture_desc(*r as crate::object::This)?, *desc, false), + View::Unordered(r, _, desc) => (crate::resource::texture_desc(*r as crate::object::This)?, *desc, true), + View::Placed(unordered, resource, desc) if resource[0] != 1 => { + (*resource, desc[..10].try_into().ok(), *unordered) + } + _ => return None, + }; + Some(image_words(&resource, desc.as_ref(), unordered)) +} + +/// [`texture_words`] of a texture of resource description `resource` (as +/// words) through a view of description `desc` (none: the resource's own). +fn image_words(resource: &[u32; 14], desc: Option<&[u32; 10]>, unordered: bool) -> [u32; 4] { + let width = u64::from(resource[4]) | u64::from(resource[5]) << 32; + let height = resource[6]; + let (depth, mips) = (resource[7] & 0xFFFF, resource[7] >> 16); + let (samples, dimension) = (resource[9], resource[0]); + // Mip count 0: the whole chain. + let deepest = if dimension == 4 { depth } else { 1 }; + let chain = 64 - (width.max(u64::from(height)).max(u64::from(deepest)) | 1).leading_zeros(); + let mips = if mips == 0 { chain } else { mips }; + // Image types: 8 1D, 9 2D, 10 3D, 11 cube, 12 1D array, 13 2D array, + // 14 2D MSAA, 15 2D MSAA array. + let (ty, first, count) = match desc { + // Shader and unordered view dimensions number alike up to 3D (8). + Some(d) => { + let ty = [0, 0, 8, 12, 9, 13, 14, 15, 10, 11, 11].get(d[1] as usize).copied().unwrap_or(0); + match (unordered, d[1]) { + (_, 6 | 7) => (ty, 0, 1), + (true, _) => (ty, d[4], 1), + (false, _) => (ty, d[4], if d[5] == u32::MAX { mips.saturating_sub(d[4]) } else { d[5] }), + } + } + None => { + let array = depth > 1; + let ty = match dimension { + 2 if array => 12, + 2 => 8, + 3 if samples > 1 => 14 + u32::from(array), + 3 => 9 + 4 * u32::from(array), + _ => 10, + }; + (ty, 0, if unordered { 1 } else { mips }) + } + }; + let (w, h) = (width.saturating_sub(1) as u32, height.saturating_sub(1)); + let last = first + count.max(1) - 1; + [ + 0, + (w & 3) << 30, + (w >> 2 & 0x3FFF) | (h & 0xFFFF) << 14, + 0xFAC | (first & 0xF) << 12 | (last & 0xF) << 16 | ty << 28, + ] } /// The title memory a buffer shader or unordered access view reads: its @@ -1742,4 +1811,30 @@ mod tests { heap.release(last, 1); assert_eq!(heap.dynamic(2), None); } + + /// A texture view's size words are the console image descriptor's + /// fields: level 0's size of the resource, the view's levels, its type. + #[test] + fn a_texture_view_gives_its_image_descriptor_size_fields() { + // A 1000x600 2D texture of 10 levels, then an array of 6 with the + // whole chain (mip count 0, 1024 wide: 11 levels). + let mut texture = [0u32; 14]; + (texture[0], texture[4], texture[6], texture[7], texture[9]) = (3, 1000, 600, 1 | 10 << 16, 1); + let mut array = texture; + (array[4], array[7]) = (1024, 6); + let mut view = [0u32; 10]; + // Levels 2-4 of the texture: width - 1 = 999 (0b11_1110_0111). + (view[1], view[4], view[5]) = (4, 2, 3); + let words = image_words(&texture, Some(&view), false); + assert_eq!(words, [0, 3 << 30, 249 | 599 << 14, 0xFAC | 2 << 12 | 4 << 16 | 9 << 28]); + // Its whole chain from level 1. + (view[4], view[5]) = (1, u32::MAX); + assert_eq!(image_words(&texture, Some(&view), false)[3], 0xFAC | 1 << 12 | 9 << 16 | 9 << 28); + // An unordered view of level 3: that level alone. + let uav = [0, 4, 0, 0, 3, 0, 0, 0, 0, 0]; + assert_eq!(image_words(&texture, Some(&uav), true)[3], 0xFAC | 3 << 12 | 3 << 16 | 9 << 28); + // The array's own view: a 2D array, levels 0-10. + let words = image_words(&array, None, false); + assert_eq!(words[1..], [3 << 30, 255 | 599 << 14, 0xFAC | 10 << 16 | 13 << 28]); + } } diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index 67ad4812ab..640532c9d0 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -1331,6 +1331,16 @@ pub(crate) fn texture_memory(this: This) -> Option<(*const u8, ResourceDesc)> { (r.desc.dimension != BUFFER).then(|| (r.data().cast_const(), r.desc)) } +/// A texture's description as words (the layout of placed views' +/// resource descriptions); `None` for buffers. +pub(crate) fn texture_desc(this: This) -> Option<[u32; 14]> { + let (_, desc) = texture_memory(this)?; + let mut words = [0u32; 14]; + // SAFETY: 56 bytes in the description's layout. + unsafe { words.as_mut_ptr().cast::().write_unaligned(desc) }; + Some(words) +} + /// A texture's format as the title gave it. pub(crate) fn title_format(this: This) -> Option { (!this.is_null()).then(|| resource(this).desc.format) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index b60e639bce..71d74aceb3 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -42,7 +42,8 @@ pub(crate) struct Lowered { pub memory: bool, /// Writes there (the written-pages bitmap). pub memory_writes: bool, - /// Reads buffer views' addresses from descriptors (the view addresses). + /// Reads buffer views' addresses or texture views' sizes from + /// descriptors (the view addresses). pub view_addresses: bool, /// Takes descriptors from the resource heap itself (root type 5, not /// a table), and whether as unordered access views. @@ -4540,12 +4541,18 @@ impl<'a> Lower<'a> { /// A descriptor load from a table or heap whose dwords the program only /// reads as numbers: the base address of a buffer view (dwords 0 and 1, - /// as a pointer to title memory: the BVH's address in its SRV). They - /// come from the host's view addresses, `t1` in - /// [`super::shader::MEMORY_SPACE`]: two dwords per heap index. + /// as a pointer to title memory: the BVH's address in its SRV) or, for + /// a whole image descriptor (eight dwords), also the size fields of + /// dwords 1-3 (width, height, first and last level, type: size queries + /// of a texture the program never samples). They come from the host's + /// view addresses, `t1` in [`super::shader::MEMORY_SPACE`]: four dwords + /// per heap index. // shortcut: dword 1 holds the address bits only (stride and swizzle read - // 0); the other dwords stop the program when read; the table offset's - // computed part is taken as whole descriptors (32-byte multiples). + // 0) or a texture's width bits, dword 3 a texture's size fields (format, + // tiling and swizzle choice read 0 or the identity); dword 4 on and a + // buffer's dwords 2-3 (record count, format) stop the program when read; + // the table offset's computed part is taken as whole descriptors + // (32-byte multiples). fn view_addresses(&mut self, inst: &Inst, site: Site, code: u8, count: u32) -> Result<(), Why> { const OTHER: Why = "a descriptor read only as data"; let a = *self.scalar.get(&site).ok_or("a descriptor read only as data")?; @@ -4555,14 +4562,17 @@ impl<'a> Lower<'a> { ) { return Err("a descriptor read only as data"); } + // The compiler loads image descriptors whole, buffer ones as four + // dwords. + let known = if count == 8 && a.offset.is_multiple_of(32) { 4 } else { 2 }; let views = self.s.view_addresses_handle(); for k in 0..count { let word = (a.offset / 4 + k) % 8; - let val = if word < 2 { + let val = if word < known { let index = self.heap_index(site, k as u8, false)?; let c = self.cur; - let three = self.s.m.i32(3); - let at = self.s.m.bin(c, Bin::Shl, index, three); + let four = self.s.m.i32(4); + let at = self.s.m.bin(c, Bin::Shl, index, four); let w = self.s.m.i32(4 * word); let at = self.s.m.bin(c, Bin::Add, at, w); Val::I32(self.raw_dword(views, at)) diff --git a/crates/victory-shader/src/emit/memory_tests.rs b/crates/victory-shader/src/emit/memory_tests.rs index f500a0e982..748d950408 100644 --- a/crates/victory-shader/src/emit/memory_tests.rs +++ b/crates/victory-shader/src/emit/memory_tests.rs @@ -5,7 +5,8 @@ //! global and a scalar load, follows a pointer it loaded with another //! scalar load, stores through a pointer it computes (64-bit multiply-add) //! and does float min/max atomics, reads through the address it takes -//! from a buffer view's descriptor (the host's view addresses), reads +//! from a buffer view's descriptor and an image descriptor's size fields +//! (the host's view addresses), reads //! pointers into memory no copy holds (zeros, marked missed) and stores and //! loads through a root UAV (title memory in such a program). @@ -104,6 +105,14 @@ fn program() -> HostShader { w.extend(global(12, 9, 1, 0, 6, 0x24)); // global_load_dword v9, v1, s[6:7] w.push(S_WAITCNT_ALL); w.extend(buffer_store_dword(9, 8, 20)); + // The image descriptor at heap index 2 loaded whole and read only for + // its size fields (dwords 1-3). + w.extend(s_load(3, 28, 4, 0x40)); // s[28:35] + w.push(S_WAITCNT_ALL); + for (k, at) in [(29, 24), (30, 28), (31, 32)] { + w.push(v_mov_b32(5, k)); + w.extend(buffer_store_dword(5, 8, at)); + } w.push(S_ENDPGM); let native = NativeProgram { stage: HwStage::Cs, @@ -241,9 +250,12 @@ fn title_memory_is_read_and_written_at_computed_addresses() { memory[0x80 / 4] = 1.0f32.to_bits(); memory[0x84 / 4] = (-1.0f32).to_bits(); let value = 0xCAFE_F00D; - // Heap index 1 (the memory's view) has the title address. - let mut view_addresses = vec![0u32; 2 * 5]; - view_addresses[2..4].copy_from_slice(&[TITLE as u32, (TITLE >> 32) as u32]); + // Heap index 1 (the memory's view) has the title address, index 2 a + // texture's size fields. + let mut view_addresses = vec![0u32; 4 * 5]; + view_addresses[4..6].copy_from_slice(&[TITLE as u32, (TITLE >> 32) as u32]); + let image = [0xC000_0000, 0x0957_C0F9, 0x9004_2FAC]; + view_addresses[9..12].copy_from_slice(&image); let mut ran = 0; for (label, warp) in [("hardware", false), ("warp", true)] { let Ok(host) = Host::new(warp) else { @@ -275,7 +287,7 @@ fn title_memory_is_read_and_written_at_computed_addresses() { (3, Root::View { srv: true, data: view_addresses.clone() }), ], views: &[ - View::RawUav(6), + View::RawUav(9), View::Memory(&memory), View::Pair, View::NullPair, @@ -288,7 +300,7 @@ fn title_memory_is_read_and_written_at_computed_addresses() { .unwrap_or_else(|e| panic!("{label}: {e}")); assert_eq!( out[0], - [0x1111_1111, 0x2222_2222, 0x2222_2222, 0, 0, 0x3333_3333], + [0x1111_1111, 0x2222_2222, 0x2222_2222, 0, 0, 0x3333_3333, image[0], image[1], image[2]], "{label}: reads" ); assert_eq!(out[1][0x40 / 4], value, "{label}: the store"); diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 87d43e7edd..835a2e09ba 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -142,9 +142,14 @@ //! a copy holding each such address. //! * **View addresses** ([`HostShader::view_addresses`]): a buffer //! descriptor's dwords 0-1 read as numbers (the BVH SRV's base address) -//! come from the root SRV `t1` in [`MEMORY_SPACE`]: per resource-heap -//! index, two dwords, the buffer view's title address (high dword bits -//! 0-15; stride bits 0), zeros for no buffer view. +//! and an image descriptor's dwords 1-3 read only for sizes come from the +//! root SRV `t1` in [`MEMORY_SPACE`]: per resource-heap index, four +//! dwords, a console descriptor's first four as far as the host knows +//! them: a buffer view's title address (high dword bits 0-15; stride bits +//! 0), a texture view's width and height - 1 (dword 1 bits 30-31, dword 2 +//! bits 0-13 and 14-29), first and last level (dword 3 bits 12-15, 16-19) +//! and type (bits 28-31) with an identity swizzle; zeros for anything +//! else. //! * **Write marks** ([`HostShader::view_marks`], with //! [`Options::view_marks`]; added 2026-11-25): every store or atomic //! through an unordered buffer view from the heap (tables, the heap @@ -292,9 +297,9 @@ pub struct HostShader { /// Whether the host binds the page bitmap `u0` in [`MEMORY_SPACE`] /// (pages written and pages missed): whenever [`HostShader::memory`]. pub memory_writes: bool, - /// Whether it reads buffer views' title addresses from their - /// descriptors: the host binds the view addresses `t1` in - /// [`MEMORY_SPACE`] (module notes, "Title memory"). + /// Whether it reads buffer views' title addresses or texture views' + /// sizes from their descriptors: the host binds the view addresses `t1` + /// in [`MEMORY_SPACE`] (module notes, "View addresses"). pub view_addresses: bool, /// Whether it takes descriptors from the resource heap at indices it /// computes (root type 5, not through a table): the host cannot tell diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index 1e8cf3c1c4..58c3c6cd60 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -377,8 +377,9 @@ impl Shader { } /// The handle of the view addresses (`t1` in [`MEMORY_SPACE`], a raw - /// buffer: per resource-heap index, a buffer view's title address as a - /// buffer descriptor's dwords 0 and 1), made in the entry block. + /// buffer: per resource-heap index, a descriptor's dwords 0-3 as far as + /// the host knows them, `emit` "View addresses"), made in the entry + /// block. pub fn view_addresses_handle(&mut self) -> V { if let Some(h) = self.view_addresses { return h; From 889b87182b9fe5d1cfc20e4874e04b526e8d5c77 Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 06:54:08 +0100 Subject: [PATCH 50/83] Shaders: a scalar VALU result takes no EXEC guard `indirect_light_probes:CS_IrradianceCache_Shade_823aad37` (the GI irradiance cache, in the intro cutscene 2 dispatches a frame and 2 indirect ones) stopped on "a lane-mask join of an untracked mask". The lowering evaluated every VALU instruction's guard before its operation, also for `v_readlane_b32` and `v_readfirstlane_b32`, whose scalar result is written whatever EXEC holds and never used the guard. At 0x14bf0 the program restores spilled masks with `v_readlane` under an EXEC taken from s[6:7], a join of a restored mask and, on the edge where every lane skips the region, the constant 0; the next instruction sets EXEC again. Building that EXEC as a lane condition was the only demand for the join. `valu` now takes the guard only for vector destinations (compares, which write lane masks, are lowered before it as before). Test: `a_scalar_result_needs_no_exec` (that shape; refused without the change). Shader list against 10d24b19: 0 newly failing; IrradianceCache_Shade emits and makes a pipeline (4 s, 0.3 GB; the validator refuses it as other compute programs with implicit-LOD samples). Co-Authored-By: Claude Opus 5.5 --- crates/victory-shader/src/emit/lower.rs | 28 ++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 71d74aceb3..f1d4c9781b 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -5320,7 +5320,12 @@ impl<'a> Lower<'a> { } return r; } - let mut guard = self.guard(b, i)?; + // A scalar result (`v_readlane`, `v_readfirstlane`) is written + // whatever EXEC holds. + let mut guard = match v.dst { + Some(Operand::Scalar { .. }) => None, + _ => self.guard(b, i)?, + }; if let Some(d) = v.dpp { let (x, enable) = self.dpp(inst, d)?; guard = match (guard, enable) { @@ -10971,6 +10976,27 @@ mod tests { lowers(&words, 1 << 7).expect("a uniform loop's mask join"); } + #[test] + fn a_scalar_result_needs_no_exec() { + // s6 is 0 where every lane skips and the saved EXEC where some run: + // no lane mask at the per-lane join. EXEC taken from it guards only + // a `v_readlane` (written whatever EXEC holds) before it is restored + // (`CS_IrradianceCache_Shade`). + let words = [ + 0xBE86_0380, // s_mov_b32 s6, 0 + 0x7D88_0090, // v_cmp_gt_u32 vcc_lo, 16, v0 + 0xBE84_3C6A, // s_and_saveexec_b32 s4, vcc_lo + 0xBF88_0001, // s_cbranch_execz +1 + 0xBE86_0304, // s_mov_b32 s6, s4 + 0xBEFE_0306, // s_mov_b32 exec_lo, s6 + 0xD760_0002, // v_readlane_b32 s2, v0, 3 + 0x0001_0700, + 0xBEFE_0304, // s_mov_b32 exec_lo, s4 + S_ENDPGM, + ]; + lowers(&words, 1 << 7).expect("a lane read under an EXEC with no mask"); + } + #[test] fn a_missing_value_on_a_path_no_lane_takes_is_dead() { let refusal = |code: &[u32]| match lowers(code, 1 << 7) { From 4a3166e680397dccb4185da01a7f22ef5e8ed074 Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 07:44:37 +0100 Subject: [PATCH 51/83] Shaders: lanes skipping a compare's region read 0 of its lane mask A lane mask made by a compare inside a region some lanes skip, joined after it with whatever the register held on the skip edge (the compiler reuses the register: a float, a descriptor word), stopped programs on "a lane-mask join of an untracked mask". The console wave runs one path: where some lane ran the region, the skipping lanes read their bit of the compare, 0 (a compare writes 0 for inactive lanes); the compiler merges no value for them, so where the whole wave skips they hold none either. A lane-mask phi at a per-lane join now takes false along an edge bringing data when some edge brings a mask and no lane taking the data edge is in any of those masks (proved on the lane conditions, `Bools::meet`). Masks that do hold such lanes (a saved EXEC) stay refused: the console would give those lanes 1. Test: `a_compare_mask_joined_with_data_on_the_skip_edge_is_0_there` (the shape on hardware and WARP; the saved-EXEC variant refused). Shader list against bcebd1ce: 0 newly failing; newly emitted `rtdirectionalshadows:CS_RTShadowTrace32TemporalHQ_OneOver4RPP` and `_OneOver2RPP_TiledFarOnly`, `shadowmask:CS_TraceShadowRays_FullAdaptive`. The other 13 `RTShadowTrace*HQ` stay refused: their register is reused on paths that reach a real mask read. Co-Authored-By: Claude Opus 5.5 --- crates/victory-shader/src/emit/lower.rs | 29 +++++++ .../src/emit/synthetic_tests.rs | 79 +++++++++++++++++++ 2 files changed, 108 insertions(+) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index f1d4c9781b..ff3b526149 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -7689,6 +7689,32 @@ impl<'a> Lower<'a> { !self.x.st.bools.meet(&self.lane_edge(q, b)) } + /// Whether, at a per-lane join `b` of a lane mask whose register holds + /// data along edge `n`, some edge brings a mask and no lane taking edge + /// `n` is in any of them (a compare inside a region those lanes skip). + /// The console wave runs one path: on a mask edge, the lanes of edge `n` + /// read their bit of that mask, 0. The compiler merges no value for them, + /// so it holds none for them either where the whole wave skips (the data + /// there is a reused register): 0 is theirs. + fn no_mask_lane_on_edge(&self, b: usize, args: &[Value], n: usize) -> bool { + let st = self.x.st; + let preds = &self.x.p.blocks[b].preds; + let on_n = self.lane_edge(preds[n], b); + let mut some = false; + for (k, arg) in args.iter().enumerate() { + let Some(&m) = st.masks.get(arg).filter(|_| k != n) else { + continue; + }; + some = true; + let mut lanes = on_n.clone(); + lanes.push((m, true)); + if st.bools.meet(&lanes) { + return false; + } + } + some + } + /// Whether IR block `b` can reach itself. fn on_cycle(&self, b: usize) -> bool { let blocks = &self.x.p.blocks; @@ -10228,6 +10254,9 @@ impl<'a> Lower<'a> { let x = match (self.x.st.masks.get(&arg), self.vals.get(&arg)) { (Some(&m), _) => self.boolean(m, qb).map_err(|w| unsupported(offset, w))?, (None, Some(&Val::I32(word))) if number => self.lane_bit(qb, word, None), + (None, _) if !self.uniform_join(b) && self.no_mask_lane_on_edge(b, &phi.args, n) => { + self.s.m.bool(false) + } (None, _) => return Err(unsupported(offset, UNTRACKED)), }; incoming.push((x, qb)); diff --git a/crates/victory-shader/src/emit/synthetic_tests.rs b/crates/victory-shader/src/emit/synthetic_tests.rs index 691f7e1702..8e7c33b675 100644 --- a/crates/victory-shader/src/emit/synthetic_tests.rs +++ b/crates/victory-shader/src/emit/synthetic_tests.rs @@ -438,6 +438,85 @@ fn a_mask_joined_with_data_at_a_uniform_loop_is_its_number() { } } +/// A lane mask a compare makes inside a region the other lanes skip, joined +/// with data in the same register on the skip edge (a reused register): the +/// skipping lanes read 0, their bit of the compare, as on the console. A +/// mask holding lanes outside its edge (the saved EXEC) stays refused. +#[test] +fn a_compare_mask_joined_with_data_on_the_skip_edge_is_0_there() { + let mut words = vec![ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0A02, + 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0x3420_0082, // v_lshlrev_b32 v16, 2, v0 + 0xBE86_0385, // s_mov_b32 s6, 5 + 0x7D88_0090, // v_cmp_gt_u32 vcc_lo, 16, v0 + 0xBE88_3C6A, // s_and_saveexec_b32 s8, vcc_lo + 0xBF88_0002, // s_cbranch_execz +2 + 0xD4C4_0006, + 0x0002_0088, // v_cmp_gt_u32 s6, 8, v0 + 0xBEFE_0308, // s_mov_b32 exec_lo, s8 + 0xD501_0003, + 0x0019_0280, // v_cndmask_b32 v3, 0, 1, s6 + 0xE070_1000, + 0x800A_0310, // buffer_store_dword v3, v16, s[40:43], 0 offen + 0xBF81_0000, // s_endpgm + ]; + let shader = build(&words).expect("lower"); + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + v.validate(&mut shader.dxil.clone()) + .expect("DXIL validation failed"); + } + let views = [ + View::Texture(1, 1, &[[0.0; 4]]), + View::Buffer { + data: &[0; 4], + stride: Stride::Structured(16), + }, + View::RawUav(32), + ]; + let want: Vec = (0..32).map(|lane| u32::from(lane < 8)).collect(); + { + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); + for (label, warp) in [("hardware", false), ("warp", true)] { + let Ok(host) = Host::new(warp) else { + eprintln!("no SM 6.6 {label} device; skipped"); + continue; + }; + let Ok((root, pso)) = host.compute_pipeline(&shader) else { + assert!(warp, "{label}: no pipeline for a wave of 32"); + eprintln!("{label}: no pipeline for a wave of 32; skipped"); + continue; + }; + let ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views: &views, + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); + assert_eq!(out[0], want, "{label}"); + } + } + // The saved EXEC instead (every lane): the skipping lanes' bit would be + // 1 on the console. + words[10..12].copy_from_slice(&[0xBE86_0308, 0xBF80_0000]); // s_mov_b32 s6, s8; s_nop 0 + let Err(crate::ShaderError::Unsupported { what, .. }) = build(&words) else { + panic!("a mask holding lanes off its edge joined with data translated"); + }; + assert!(what.contains("lane-mask join"), "{what}"); +} + #[test] fn ordered_pixel_sections_use_rasterizer_ordered_views() { // A pixel program's ordered section (POPS) as the title's compiler From 47cde30fe290a3e0a0d9b1d24b27873db1e44970 Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 07:44:38 +0100 Subject: [PATCH 52/83] Shaders: a test of register arrays indexed in waterfall loops `tiled_lighting:CS_PrescalarizeLightLoop` builds its per-tile light masks in v3-v14 with `v_movrels`/`v_movreld` whose M0 each lane takes from its own group index (clamped 0-11 by `v_med3_u32`) in waterfall loops over the lanes. The new GPU test runs that shape twice (the second pass reads what the first wrote) and checks every element of every lane, on hardware and WARP. It passes: the lowering of the shape is right; what the program writes in the title depends on its inputs. Co-Authored-By: Claude Opus 5.5 --- .../src/emit/synthetic_tests.rs | 100 ++++++++++++++++++ 1 file changed, 100 insertions(+) diff --git a/crates/victory-shader/src/emit/synthetic_tests.rs b/crates/victory-shader/src/emit/synthetic_tests.rs index 8e7c33b675..9258629cc0 100644 --- a/crates/victory-shader/src/emit/synthetic_tests.rs +++ b/crates/victory-shader/src/emit/synthetic_tests.rs @@ -517,6 +517,106 @@ fn a_compare_mask_joined_with_data_on_the_skip_edge_is_0_there() { assert!(what.contains("lane-mask join"), "{what}"); } +/// A register array (v3-v14) indexed through M0 in waterfall loops, as +/// `tiled_lighting:CS_PrescalarizeLightLoop` builds its per-tile light +/// masks: each lane's index (clamped to 0-11 by `v_med3_u32`) becomes M0 in +/// the loop pass that handles the lanes holding it; a `v_movrels` reads the +/// lane's array element, a `v_movreld` writes it back with the lane's bit +/// added. Twice, so the second pass reads what the first wrote. +#[test] +fn relative_moves_in_waterfall_loops_reach_each_lane_s_element() { + let mut w = vec![ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0A02, + 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0x3420_0082, // v_lshlrev_b32 v16, 2, v0 + ]; + w.extend((3..15u32).map(|k| 0x7E00_0280 | k << 17)); // v_mov_b32 vk, 0 + w.extend([ + 0x2C38_0081, // v_lshrrev_b32 v28, 1, v0 + 0xD559_001C, + 0x022D_011C, // v_med3_u32 v28, v28, 0, 11 + 0x7E3A_0281, // v_mov_b32 v29, 1 + 0x343A_3B00, // v_lshlrev_b32 v29, v0, v29 + ]); + let pass = [ + 0xBEA4_037E, // s_mov_b32 s36, exec_lo + 0x7E4C_051C, // read: v_readfirstlane_b32 s38, v28 + 0xD4C2_0006, + 0x0002_3826, // v_cmp_eq_u32 s6, s38, v28 + 0xBE86_3C06, // s_and_saveexec_b32 s6, s6 + 0xBEFC_0326, // s_mov_b32 m0, s38 + 0x7E3E_8703, // v_movrels_b32 v31, v3 + 0x897E_067E, // s_xor_b32 exec_lo, exec_lo, s6 + 0xBF89_FFF8, // s_cbranch_execnz read + 0xBEFE_0324, // s_mov_b32 exec_lo, s36 + 0x383A_3B1F, // v_or_b32 v29, v31, v29 + 0x7E4C_051C, // write: v_readfirstlane_b32 s38, v28 + 0xD4C2_0006, + 0x0002_3826, // v_cmp_eq_u32 s6, s38, v28 + 0xBE86_3C06, // s_and_saveexec_b32 s6, s6 + 0xBEFC_0326, // s_mov_b32 m0, s38 + 0x7E06_851D, // v_movreld_b32 v3, v29 + 0x897E_067E, // s_xor_b32 exec_lo, exec_lo, s6 + 0xBF89_FFF8, // s_cbranch_execnz write + 0xBEFE_0324, // s_mov_b32 exec_lo, s36 + ]; + w.extend(pass); + w.extend([0x7E3A_02FF, 0x8000_0000]); // v_mov_b32 v29, 0x80000000 + w.extend(pass); + for k in 3..15u32 { + // buffer_store_dword vk, v16, s[40:43], 0 offen offset:128 * (k - 3) + w.extend([0xE070_1000 | (128 * (k - 3)), 0x800A_0010 | k << 8]); + } + w.push(0xBF81_0000); // s_endpgm + let shader = build(&w).expect("lower"); + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + v.validate(&mut shader.dxil.clone()) + .expect("DXIL validation failed"); + } + let views = [ + View::Texture(1, 1, &[[0.0; 4]]), + View::Buffer { + data: &[0; 4], + stride: Stride::Structured(16), + }, + View::RawUav(12 * 32), + ]; + let want: Vec = (0..12u32) + .flat_map(|k| (0..32u32).map(move |lane| if (lane >> 1).min(11) == k { 1 << lane | 0x8000_0000 } else { 0 })) + .collect(); + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); + for (label, warp) in [("hardware", false), ("warp", true)] { + let Ok(host) = Host::new(warp) else { + eprintln!("no SM 6.6 {label} device; skipped"); + continue; + }; + let Ok((root, pso)) = host.compute_pipeline(&shader) else { + assert!(warp, "{label}: no pipeline for a wave of 32"); + eprintln!("{label}: no pipeline for a wave of 32; skipped"); + continue; + }; + let ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views: &views, + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); + assert_eq!(out[0], want, "{label}"); + } +} + #[test] fn ordered_pixel_sections_use_rasterizer_ordered_views() { // A pixel program's ordered section (POPS) as the title's compiler From 52d14b1098b8cbc4d22bad05a2ea07793b2727be Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 04:17:16 +0100 Subject: [PATCH 53/83] GPU, Shader: placed textures made when shaders read their heap slots Views of textures the title placed itself (device 0x230, no resource object; its streamed textures) were left null until a draw read them through a table: making all of them never fits the card (run textures1: 12-16k such slots at ~12.5k addresses, 8.4-8.9 GB of console bytes), and shaders index the heap themselves, so materials sampling through the heap read black. Translations made with `emit::Options::view_marks` now also mark reads: every image instruction reading a texture shader view from the heap sets bit `VIEW_READS` + the view's heap index in the views' marks bitmap (after the written pages), where still clear (a load first, an atomic OR only then). After each submission the host takes the newly set marks and makes the views of those slots that were left null, so the next submission reads the texture; a slot made null again is forgotten so its next read marks it again. Placed textures stop being made past 3 GiB of console bytes (`shortcut:`, no eviction yet). Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor.rs | 35 ++++++ crates/victory-gpu/src/descriptor/host.rs | 4 + crates/victory-gpu/src/host.rs | 5 + crates/victory-gpu/src/shadow.rs | 51 +++++++- crates/victory-shader/src/emit/lower.rs | 55 +++++++- .../victory-shader/src/emit/memory_tests.rs | 119 ++++++++++++++++++ crates/victory-shader/src/emit/mod.rs | 10 +- crates/victory-shader/src/emit/shader.rs | 15 +++ 8 files changed, 288 insertions(+), 6 deletions(-) diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 84ce54358f..88d6d21162 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -196,6 +196,41 @@ pub(crate) fn sync_heaps() { } } +/// Makes the views of slots `slots` that were left null (textures the title +/// placed itself) in every shader-visible view heap, now that shaders read +/// them (`crate::shadow::take_reads`), while placed textures take under +/// [`PLACED_CAP`] bytes. +/// shortcut: past the cap, views read later stay null; nothing is released +/// for them (placed textures are kept until the end); add eviction by the +/// read marks if the cap is reached. +#[cfg(windows)] +pub(crate) fn make_read(slots: &[u32]) { + if crate::resource::PLACED_BYTES.load(std::sync::atomic::Ordering::Relaxed) >= PLACED_CAP { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::warn!("placed textures reached their cap: views shaders read now stay null")); + return; + } + let heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner()); + for &(start, _, at) in heaps.iter() { + // SAFETY: registered heaps are live (removed when dropped). + let heap = unsafe { &*(at as *const Heap) }; + let (Some(Some(host)), Some(step)) = (heap.host.get(), increment(heap.desc.kind)) else { + continue; + }; + if heap.desc.kind != VIEWS_KIND { + continue; + } + for &i in slots.iter().filter(|&&i| i < heap.desc.count) { + host.mirror(i, start + u64::from(i) * u64::from(step), true); + } + } +} + +/// Console bytes of placed textures past which views shaders read stay +/// null: the 12 GB card held 6.5 GB without them (run textures2). +#[cfg(windows)] +const PLACED_CAP: u64 = 3 << 30; + /// Gives back dynamic slots of the host heap behind the title heap at /// `heap`, if that heap still exists. #[cfg(windows)] diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 2a0120a36b..3d63fcaca1 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -709,6 +709,10 @@ impl HostHeap { // staging copy) for each of the ~20,000 the title has views of // ran the host out of memory (run b2). let later = !for_draw && is_placed_texture(&view); + if later { + // Made once a shader reads it (`crate::shadow::take_reads`). + crate::shadow::forget_read(index); + } made[index as usize] = key; let (kept, mark) = if later { (None, None) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index b532703ac1..9aa0ebf791 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -1109,6 +1109,11 @@ impl Host { .map(|(s, a, n, _)| (s.clone(), *a, *n)) .collect(); crate::shadow::copy_back_marks(&withheld, withholding); + // Texture views left null that shaders read: made for what follows. + let read = crate::shadow::take_reads(); + if !read.is_empty() { + crate::descriptor::make_read(&read); + } for (shadow, address, len, goes_back) in &back { let (address, len) = (*address, *len); if *goes_back { diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 01fcd28959..fb36b57b9d 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -743,9 +743,11 @@ fn bitmap(memory: bool) -> Option<&'static Bitmap> { static BITMAPS: [std::sync::OnceLock>; 2] = [const { std::sync::OnceLock::new() }; 2]; BITMAPS[usize::from(memory)] .get_or_init(|| { - let bytes = u64::from(victory_shader::emit::VIEW_WRITE_BITS / 8); + // Written pages, then one read mark per heap index. + let bits = victory_shader::emit::VIEW_READS + victory_shader::emit::HEAP_VIEWS; + let bytes = u64::from(bits / 8); let (buffer, data) = host()?.shared_buffer(bytes)?; - crate::host::name(&buffer, || "views' written pages".into()); + crate::host::name(&buffer, || "views' written pages and read slots".into()); // SAFETY: our mapped buffer of `bytes` bytes. unsafe { std::ptr::write_bytes(data, 0, bytes as usize) }; // SAFETY: a live buffer. @@ -766,6 +768,51 @@ pub(crate) fn view_writes(memory: bool) -> Option { bitmap(memory).map(|b| b.gpu) } +/// Heap slots whose texture views shaders read: the marks seen so far (a +/// slot's stays set in the bitmap until [`forget_read`]), and the slots to +/// clear at the next [`take_reads`]. +static READS: Mutex<(Vec, Vec)> = Mutex::new((Vec::new(), Vec::new())); + +/// After a submission: the heap slots its shaders first read texture views +/// at (`victory_shader::emit`, "Read marks"), each once until +/// [`forget_read`]. Clears the slots forgotten since first. +pub(crate) fn take_reads() -> Vec { + let Some(b) = bitmap() else { + return Vec::new(); + }; + let words = (victory_shader::emit::HEAP_VIEWS / 32) as usize; + let first = (victory_shader::emit::VIEW_READS / 32) as usize; + // SAFETY: the mapped bitmap's read marks; the GPU is done with them + // (one submission runs at a time). + let bits = unsafe { std::slice::from_raw_parts_mut((b.data as *mut u32).add(first), words) }; + let mut reads = READS.lock().unwrap_or_else(|e| e.into_inner()); + let (seen, forgotten) = &mut *reads; + seen.resize(words, 0); + for slot in forgotten.drain(..) { + let (w, bit) = ((slot / 32) as usize, 1u32 << (slot % 32)); + if w < words { + bits[w] &= !bit; + seen[w] &= !bit; + } + } + let mut new = Vec::new(); + for (w, (x, s)) in bits.iter().zip(seen.iter_mut()).enumerate() { + let mut fresh = *x & !*s; + *s |= fresh; + while fresh != 0 { + new.push(w as u32 * 32 + fresh.trailing_zeros()); + fresh &= fresh - 1; + } + } + new +} + +/// Heap slot `slot` now holds a texture view left null: its next read is +/// marked again. +pub(crate) fn forget_read(slot: u32) { + READS.lock().unwrap_or_else(|e| e.into_inner()).1.push(slot); +} + /// After a submission: every page its shaders marked as written through /// views goes back ([`Shadow::copy_back_marked`]), but for pages in /// `withheld` (ranges of copies that lists whose writes stay out of title diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index ff3b526149..f7d7656c6d 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -4913,8 +4913,18 @@ impl<'a> Lower<'a> { .max_by_key(|u| u.table_offset_dwords) } - /// A handle for the descriptor `src` read at `site`. - fn handle( + /// A handle for the descriptor `src` read at `site`; a texture shader + /// view's heap index is noted for the instruction's read mark (handles + /// are made once per block, often before the instruction). + fn handle(&mut self, site: Site, src: &Source, sampler: bool, props: (u32, u32)) -> Result { + let h = self.handle_made(site, src, sampler, props)?; + if let Some(&index) = self.s.texture_index.get(&h) { + self.s.texture_reads.push(index); + } + Ok(h) + } + + fn handle_made( &mut self, site: Site, src: &Source, @@ -7771,7 +7781,48 @@ impl<'a> Lower<'a> { .op(c, "legacyF32ToF16", Attr::ReadNone, self.s.t.i32, 130, &[f]) } + /// An image instruction, its reads of texture views marked (module + /// notes, "Read marks") after it. fn image(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> { + self.s.texture_reads.clear(); + let lowered = self.image_op(inst, b, i); + for index in std::mem::take(&mut self.s.texture_reads) { + if lowered.is_ok() { + self.mark_view_read(index); + } + } + lowered + } + + /// Sets the read mark of resource-heap index `index` (module notes, + /// "Read marks") where it is still clear. Nothing without + /// [`Parts::view_marks`]. + fn mark_view_read(&mut self, index: V) { + if !self.x.view_marks { + return; + } + let k = |l: &mut Self, v: u32| l.s.m.i32(v); + let bitmap = self.s.view_writes_handle(); + let c = self.cur; + let (base, k5, k2, k31, one, zero) = + (k(self, super::VIEW_READS), k(self, 5), k(self, 2), k(self, 31), k(self, 1), k(self, 0)); + let n = self.s.m.bin(c, Bin::Add, index, base); + let word = self.s.m.bin(c, Bin::LShr, n, k5); + let word = self.s.m.bin(c, Bin::Shl, word, k2); + let bit = self.s.m.bin(c, Bin::And, n, k31); + let bit = self.s.m.bin(c, Bin::Shl, one, bit); + // Most reads find their slot marked: a load, not an atomic. + let old = self.raw_dword(bitmap, word); + let set = self.s.m.bin(c, Bin::And, old, bit); + let clear = self.s.m.cmp(c, pred::EQ, set, zero); + let at = self.begin_guarded(Some(clear)); + let iu = self.s.m.undef(self.s.t.i32); + // Operation 2 is OR. + self.s.op(self.cur, "atomicBinOp.i32", Attr::NoUnwind, self.s.t.i32, 78, &[bitmap, k2, word, iu, iu, bit]); + self.end_guarded(at, &[]); + } + + fn image_op(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> { let Fields::Image { data, addr, diff --git a/crates/victory-shader/src/emit/memory_tests.rs b/crates/victory-shader/src/emit/memory_tests.rs index 748d950408..2fef8983eb 100644 --- a/crates/victory-shader/src/emit/memory_tests.rs +++ b/crates/victory-shader/src/emit/memory_tests.rs @@ -625,3 +625,122 @@ fn writes_through_views_mark_their_pages() { } assert!(ran > 0, "neither hardware nor WARP SM 6.6 device available"); } + +/// Reads of texture views from the heap mark their heap index (`emit`, +/// "Read marks"): an `image_load` through a table whose user data places it +/// at heap index 1 sets exactly bit [`super::VIEW_READS`] + 1. +#[test] +fn texture_reads_mark_their_heap_index() { + let mut w = vec![s_mov_b32(5, ZERO as u8)]; + w.extend(s_load(3, 12, 4, 0)); + w.push(S_WAITCNT_ALL); + w.extend((0..2).map(|v| v_mov_b32(v, ZERO))); + // image_load v[2:5], v[0:1], s[12:19] dmask:0xf dim:2D unorm + w.extend([0xF000_1F08, 0x0003_0200]); + w.push(S_WAITCNT_ALL); + w.push(S_ENDPGM); + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 8, + layout: vec![RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 4, + slot: 0, + }], + used: vec![UsedResource { + kind: ResourceType::Srv, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 8, + user_data: 4, + slot: 0, + }], + io: StageIo::Cs(ComputeIo { + rsrc2: 5 << 1, + threads: [1, 1, 1], + }), + code: w.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + let st = structure::structure(&p).expect("structure"); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("track"); + let io = io::raise(&p, &native).expect("io::raise"); + let l = lower::lower(&lower::Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: Vec::new(), + outputs: Vec::new(), + prims: Vec::new(), + mesh_stride: 0, + view_marks: true, + }) + .expect("lower"); + assert!(l.view_marks, "reads marked"); + let shader = HostShader { + stage: HwStage::Cs, + dxil: l.dxil, + user_data: l.user_data, + samplers: l.samplers, + static_samplers: Vec::new(), + root_cbvs: l.root_cbvs, + root_srvs: l.root_srvs, + root_uavs: l.root_uavs, + memory: l.memory, + memory_writes: l.memory_writes, + view_addresses: l.view_addresses, + heap: l.heap, + heap_writes: l.heap_writes, + view_marks: l.view_marks, + }; + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + v.validate(&mut shader.dxil.clone()).expect("DXIL validation failed"); + } + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); + let words = (super::VIEW_READS + 64) / 32; + let texel = [[0.5f32; 4]]; + let mut ran = 0; + for (label, warp) in [("hardware", false), ("warp", true)] { + let Ok(host) = Host::new(warp) else { + eprintln!("no SM 6.6 {label} device; skipped"); + continue; + }; + let (root, pso) = host.compute_pipeline(&shader).expect("pipeline"); + let mut ud = vec![0u32; shader.user_data_dwords() as usize]; + for u in &shader.user_data { + // The table at heap index 1 (a byte offset in the heap). + ud[u.index as usize] = 32; + } + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![ + (0, Root::Constants(ud)), + (1, Root::View { srv: true, data: vec![super::VIEW_MARK_NONE; 4] }), + (2, Root::Uav(words)), + ], + views: &[View::Texture(1, 1, &texel), View::Texture(1, 1, &texel)], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{label}: {e}")); + let bits = &out[0]; + let marked: Vec = (0..bits.len() * 32).filter(|&b| bits[b / 32] >> (b % 32) & 1 != 0).collect(); + assert_eq!(marked, [super::VIEW_READS as usize + 1], "{label}: the slot read"); + ran += 1; + } + assert!(ran > 0, "neither hardware nor WARP SM 6.6 device available"); +} diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 835a2e09ba..3865d47668 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -166,6 +166,12 @@ //! a view the bit of its first byte's page as base with that byte's //! offset in its page as phase. Writes at computed addresses mark the //! page-table bitmap instead ("Title memory"). +//! * **Read marks** (with [`Options::view_marks`]; added 2026-11-25): +//! every image instruction that reads a texture shader view from the +//! resource heap (tables or the heap itself) also sets bit +//! [`VIEW_READS`] + the view's heap index in the same bitmap, after the +//! written pages, where still clear: the host makes views it left null +//! until a shader reads them (textures the title placed itself). //! //! Entry points: [`translate`] (container bytes as the title passes them //! at pipeline creation → [`HostShader`]), [`emit`] (the same with the @@ -225,8 +231,8 @@ use crate::{ShaderError, io, ir, resource, structure}; pub use sampler::StaticSampler; pub use shader::{ HEAP_SAMPLERS, HEAP_VIEWS, MEMORY_SPACE, NULL_BUFFER_VIEW, ROOT_CBV_SPACE, SAMPLER_SPACE, - USER_DATA_SPACE, VIEW_INTEGER, VIEW_MARK_NONE, VIEW_MARKS, VIEW_SIGNED, VIEW_STRIDE_BITS, VIEW_STRIDES, - VIEW_WRITE_BITS, VIEW_WRITES, + USER_DATA_SPACE, VIEW_INTEGER, VIEW_MARK_NONE, VIEW_MARKS, VIEW_READS, VIEW_SIGNED, VIEW_STRIDE_BITS, + VIEW_STRIDES, VIEW_WRITE_BITS, VIEW_WRITES, }; /// The loop limit without an override: 2^20. diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index 58c3c6cd60..bd42a194e7 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -48,6 +48,10 @@ pub const VIEW_MARK_NONE: u32 = u32::MAX; /// Bits in the written-pages bitmap of buffer views; marks past it go to /// the last bit. pub const VIEW_WRITE_BITS: u32 = 1 << 22; +/// The first bit of the read marks of texture views (`emit`, "Read +/// marks"), after the written pages in the same bitmap: one bit per +/// resource-heap index, [`HEAP_VIEWS`] of them. +pub const VIEW_READS: u32 = VIEW_WRITE_BITS; /// `ShaderFlags` bits (metadata) and their `SFI0` feature bits. pub(crate) mod flags { @@ -126,6 +130,11 @@ pub(crate) struct Shader { /// The heap index of each handle of an unordered buffer view (writes /// through it are marked by the index's view-mark entry). pub view_index: std::collections::HashMap, + /// The heap index of each handle of a texture shader view (its reads + /// are marked, `emit` "Read marks"), and those the instruction being + /// lowered uses. + pub texture_index: std::collections::HashMap, + pub texture_reads: Vec, pub flags: u64, /// Heap handles made with a non-uniform index. pub nonuniform_handles: u32, @@ -190,6 +199,8 @@ impl Shader { view_marks: None, view_writes: None, view_index: std::collections::HashMap::new(), + texture_index: std::collections::HashMap::new(), + texture_reads: Vec::new(), flags: 0, nonuniform_handles: 0, threads: None, @@ -548,6 +559,10 @@ impl Shader { if !sampler && (kind == 10 || props.0 & 0x1000 != 0 && (11..=12).contains(&kind)) { self.view_index.insert(h, index); } + // Texture shader views (kinds 1-9). + if !sampler && props.0 & 0x1000 == 0 && (1..=9).contains(&kind) { + self.texture_index.insert(h, index); + } h } From 2d6c0dfcb637d818ecc35172c7cd32cf609eed38 Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 06:41:21 +0100 Subject: [PATCH 54/83] Shader: read marks only for texture views taken from the heap itself Every image instruction reading a texture view from the resource heap loaded the read-marks bitmap word (system memory) after it, tables included. A view read through a table cannot be a slot left null: the host makes table slots for the draw. Marks are now emitted only where the program takes the descriptor from the heap itself. Test: `heap_direct_texture_reads_mark_their_heap_index` (a table read marks nothing, a heap-direct read sets exactly its slot's bit). Co-Authored-By: Claude Opus 5.5 --- crates/victory-shader/src/emit/lower.rs | 12 +- .../victory-shader/src/emit/memory_tests.rs | 116 ++++++++++-------- crates/victory-shader/src/emit/mod.rs | 5 +- 3 files changed, 73 insertions(+), 60 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index f7d7656c6d..c4b4b381fc 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -4913,12 +4913,16 @@ impl<'a> Lower<'a> { .max_by_key(|u| u.table_offset_dwords) } - /// A handle for the descriptor `src` read at `site`; a texture shader - /// view's heap index is noted for the instruction's read mark (handles - /// are made once per block, often before the instruction). + /// A handle for the descriptor `src` read at `site`; the heap index of + /// a texture shader view the program takes from the heap itself is noted + /// for the instruction's read mark (handles are made once per block, + /// often before the instruction). A view read through a table needs + /// none: the host makes the slot for the draw. fn handle(&mut self, site: Site, src: &Source, sampler: bool, props: (u32, u32)) -> Result { let h = self.handle_made(site, src, sampler, props)?; - if let Some(&index) = self.s.texture_index.get(&h) { + if let Some(&index) = self.s.texture_index.get(&h) + && self.is_heap_direct(src) + { self.s.texture_reads.push(index); } Ok(h) diff --git a/crates/victory-shader/src/emit/memory_tests.rs b/crates/victory-shader/src/emit/memory_tests.rs index 2fef8983eb..9946d9c9f8 100644 --- a/crates/victory-shader/src/emit/memory_tests.rs +++ b/crates/victory-shader/src/emit/memory_tests.rs @@ -626,32 +626,62 @@ fn writes_through_views_mark_their_pages() { assert!(ran > 0, "neither hardware nor WARP SM 6.6 device available"); } -/// Reads of texture views from the heap mark their heap index (`emit`, -/// "Read marks"): an `image_load` through a table whose user data places it -/// at heap index 1 sets exactly bit [`super::VIEW_READS`] + 1. +/// Reads of texture views the program takes from the resource heap itself +/// mark their heap index (`emit`, "Read marks"): an `image_load` of the view +/// at heap byte offset 32 (index 1) sets exactly bit [`super::VIEW_READS`] + +/// 1. The same read through a table marks nothing (a table read makes its +/// slot on the host). #[test] -fn texture_reads_mark_their_heap_index() { - let mut w = vec![s_mov_b32(5, ZERO as u8)]; - w.extend(s_load(3, 12, 4, 0)); - w.push(S_WAITCNT_ALL); - w.extend((0..2).map(|v| v_mov_b32(v, ZERO))); - // image_load v[2:5], v[0:1], s[12:19] dmask:0xf dim:2D unorm - w.extend([0xF000_1F08, 0x0003_0200]); - w.push(S_WAITCNT_ALL); - w.push(S_ENDPGM); - let native = NativeProgram { - stage: HwStage::Cs, - wave64: false, - vgprs: 8, - layout: vec![RootParam { - root: RootType::Table, - table_offset_dwords: 0, - sgprs: 1, - base_register: 0, - user_data: 4, - slot: 0, - }], - used: vec![UsedResource { +fn heap_direct_texture_reads_mark_their_heap_index() { + let lower_with = |root: RootType, used: Vec, offset: u32| { + let mut w = vec![s_mov_b32(5, ZERO as u8)]; + w.extend(s_load(3, 12, 4, offset)); + w.push(S_WAITCNT_ALL); + w.extend((0..2).map(|v| v_mov_b32(v, ZERO))); + // image_load v[2:5], v[0:1], s[12:19] dmask:0xf dim:2D unorm + w.extend([0xF000_1F08, 0x0003_0200]); + w.push(S_WAITCNT_ALL); + w.push(S_ENDPGM); + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 8, + layout: vec![RootParam { + root, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 4, + slot: 0, + }], + used, + io: StageIo::Cs(ComputeIo { + rsrc2: 5 << 1, + threads: [1, 1, 1], + }), + code: w.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + let st = structure::structure(&p).expect("structure"); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("track"); + let io = io::raise(&p, &native).expect("io::raise"); + lower::lower(&lower::Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: Vec::new(), + outputs: Vec::new(), + prims: Vec::new(), + mesh_stride: 0, + view_marks: true, + }) + .expect("lower") + }; + let table = lower_with( + RootType::Table, + vec![UsedResource { kind: ResourceType::Srv, root: RootType::Table, table_offset_dwords: 0, @@ -661,30 +691,11 @@ fn texture_reads_mark_their_heap_index() { user_data: 4, slot: 0, }], - io: StageIo::Cs(ComputeIo { - rsrc2: 5 << 1, - threads: [1, 1, 1], - }), - code: w.iter().flat_map(|w| w.to_le_bytes()).collect(), - }; - let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); - let st = structure::structure(&p).expect("structure"); - let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("track"); - let io = io::raise(&p, &native).expect("io::raise"); - let l = lower::lower(&lower::Parts { - native: &native, - p: &p, - st: &st, - io: &io, - res: &res, - inputs: Vec::new(), - outputs: Vec::new(), - prims: Vec::new(), - mesh_stride: 0, - view_marks: true, - }) - .expect("lower"); - assert!(l.view_marks, "reads marked"); + 0, + ); + assert!(!table.view_marks, "a table read marks nothing"); + let l = lower_with(RootType::ResourceHeap, Vec::new(), 32); + assert!(l.view_marks && l.heap, "a heap-direct read is marked"); let shader = HostShader { stage: HwStage::Cs, dxil: l.dxil, @@ -716,11 +727,8 @@ fn texture_reads_mark_their_heap_index() { continue; }; let (root, pso) = host.compute_pipeline(&shader).expect("pipeline"); - let mut ud = vec![0u32; shader.user_data_dwords() as usize]; - for u in &shader.user_data { - // The table at heap index 1 (a byte offset in the heap). - ud[u.index as usize] = 32; - } + // The heap's base is 0 in the user data (`emit`, "Binding"). + let ud = vec![0u32; shader.user_data_dwords() as usize]; let out = host .dispatch( &root, diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 3865d47668..429389529d 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -167,8 +167,9 @@ //! offset in its page as phase. Writes at computed addresses mark the //! page-table bitmap instead ("Title memory"). //! * **Read marks** (with [`Options::view_marks`]; added 2026-11-25): -//! every image instruction that reads a texture shader view from the -//! resource heap (tables or the heap itself) also sets bit +//! every image instruction that reads a texture shader view the program +//! takes from the resource heap itself (not through a table, whose slots +//! the host makes for the draw) also sets bit //! [`VIEW_READS`] + the view's heap index in the same bitmap, after the //! written pages, where still clear: the host makes views it left null //! until a shader reads them (textures the title placed itself). From 80d8cf5333cd7d32b4be63d4bff9d78fc5a4f6d0 Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 08:22:59 +0100 Subject: [PATCH 55/83] GPU: read marks are taken from both written-page bitmaps What was wrong: shaders that use title memory got a bitmap of their own (the withholding rule), but `take_reads` still read one bitmap through `bitmap()`, which no longer exists: the stack did not compile, and reading only one bitmap would lose the reads those shaders mark. What changed: `take_reads` ORs the read-mark words of both bitmaps and clears a forgotten slot's mark in both. Evidence: test `host::tests::read_marks_of_both_bitmaps_are_taken` (a read marked in each bitmap is taken, each once; a forgotten slot's mark is cleared and its next read taken again). Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/host.rs | 22 ++++++++++++++++++++ crates/victory-gpu/src/shadow.rs | 35 +++++++++++++++++++++++--------- 2 files changed, 47 insertions(+), 10 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 9aa0ebf791..5dfe70eafa 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -393,6 +393,28 @@ mod tests { use super::*; + /// Shaders that use title memory mark their reads in their own bitmap: + /// read marks of both bitmaps are taken, each slot once until it is + /// forgotten, and a forgotten slot's next read is taken again. + #[test] + fn read_marks_of_both_bitmaps_are_taken() { + let Some(host) = host() else { return }; + // No submission takes the marks meanwhile. + let _one = host.submitted.lock().unwrap_or_else(|e| e.into_inner()); + let (plain, memory) = (victory_shader::emit::HEAP_VIEWS - 2, victory_shader::emit::HEAP_VIEWS - 1); + crate::shadow::tests::mark_read(false, plain); + crate::shadow::tests::mark_read(true, memory); + let taken = crate::shadow::take_reads(); + assert!(taken.contains(&plain), "a plain shader's read"); + assert!(taken.contains(&memory), "a read by a shader that uses title memory"); + let again = crate::shadow::take_reads(); + assert!(!again.contains(&plain) && !again.contains(&memory), "each once"); + crate::shadow::forget_read(memory); + assert!(!crate::shadow::take_reads().contains(&memory), "forgotten: its mark cleared"); + crate::shadow::tests::mark_read(true, memory); + assert!(crate::shadow::take_reads().contains(&memory), "read again after it was forgotten"); + } + #[test] fn list_scratch_grows_to_fit_and_reuses_fenced_chunks() { let Some(host) = host() else { return }; diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index fb36b57b9d..795e4a499c 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -777,27 +777,32 @@ static READS: Mutex<(Vec, Vec)> = Mutex::new((Vec::new(), Vec::new())) /// at (`victory_shader::emit`, "Read marks"), each once until /// [`forget_read`]. Clears the slots forgotten since first. pub(crate) fn take_reads() -> Vec { - let Some(b) = bitmap() else { - return Vec::new(); - }; let words = (victory_shader::emit::HEAP_VIEWS / 32) as usize; let first = (victory_shader::emit::VIEW_READS / 32) as usize; - // SAFETY: the mapped bitmap's read marks; the GPU is done with them - // (one submission runs at a time). - let bits = unsafe { std::slice::from_raw_parts_mut((b.data as *mut u32).add(first), words) }; + // Both bitmaps: shaders that use title memory mark their reads in theirs. + let mut maps: Vec<&mut [u32]> = [false, true] + .into_iter() + .filter_map(bitmap) + // SAFETY: the mapped bitmap's read marks; the GPU is done with them + // (one submission runs at a time). + .map(|b| unsafe { std::slice::from_raw_parts_mut((b.data as *mut u32).add(first), words) }) + .collect(); + if maps.is_empty() { + return Vec::new(); + } let mut reads = READS.lock().unwrap_or_else(|e| e.into_inner()); let (seen, forgotten) = &mut *reads; seen.resize(words, 0); for slot in forgotten.drain(..) { let (w, bit) = ((slot / 32) as usize, 1u32 << (slot % 32)); if w < words { - bits[w] &= !bit; + maps.iter_mut().for_each(|bits| bits[w] &= !bit); seen[w] &= !bit; } } let mut new = Vec::new(); - for (w, (x, s)) in bits.iter().zip(seen.iter_mut()).enumerate() { - let mut fresh = *x & !*s; + for (w, s) in seen.iter_mut().enumerate() { + let mut fresh = maps.iter().fold(0, |x, bits| x | bits[w]) & !*s; *s |= fresh; while fresh != 0 { new.push(w as u32 * 32 + fresh.trailing_zeros()); @@ -1228,9 +1233,19 @@ pub(crate) fn near(va: u64) -> String { } #[cfg(test)] -mod tests { +pub(crate) mod tests { use super::*; + /// A shader's read mark of heap slot `slot` in the bitmap of shaders + /// that use title memory (`memory`) or of the others. + pub(crate) fn mark_read(memory: bool, slot: u32) { + let b = bitmap(memory).expect("a host GPU"); + let bit = victory_shader::emit::VIEW_READS + slot; + // SAFETY: a bit of the mapped bitmap; no submission runs (the caller + // holds the submission lock). + unsafe { *(b.data as *mut u32).add((bit / 32) as usize) |= 1 << (bit % 32) }; + } + /// The title writes a constant under a range an earlier list of the /// submission declared as written by shaders: the refresh before the /// submission runs still brings it to the copy, a shader's write still From 672e7169e52f7e3c1377756aaa726b9672abcc4e Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 08:14:15 +0100 Subject: [PATCH 56/83] Shader: the read-mark test's doc comment is no list Clippy (doc_lazy_continuation) took the wrapped "1." for a list item. Co-Authored-By: Claude Opus 5.5 --- crates/victory-shader/src/emit/memory_tests.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/victory-shader/src/emit/memory_tests.rs b/crates/victory-shader/src/emit/memory_tests.rs index 9946d9c9f8..c228e98ecf 100644 --- a/crates/victory-shader/src/emit/memory_tests.rs +++ b/crates/victory-shader/src/emit/memory_tests.rs @@ -628,9 +628,9 @@ fn writes_through_views_mark_their_pages() { /// Reads of texture views the program takes from the resource heap itself /// mark their heap index (`emit`, "Read marks"): an `image_load` of the view -/// at heap byte offset 32 (index 1) sets exactly bit [`super::VIEW_READS`] + -/// 1. The same read through a table marks nothing (a table read makes its -/// slot on the host). +/// at heap byte offset 32 (index 1) sets exactly the bit one past +/// [`super::VIEW_READS`]. The same read through a table marks nothing (a +/// table read makes its slot on the host). #[test] fn heap_direct_texture_reads_mark_their_heap_index() { let lower_with = |root: RootType, used: Vec, offset: u32| { From 69d1e8e79a700a6f7e176b1f8f4184209ec0c75c Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 08:49:11 +0100 Subject: [PATCH 57/83] GPU: host textures fed from title memory are given up when unused, and past the card's budget What was wrong: a host texture, once made, lived as long as its title texture; placed textures (made when shaders read them) for the whole run. The title views far more textures than one frame reads (8.4-8.9 GB of placed textures left null in run textures1), so making them as they are read only grows video memory until the card pages or the process runs out of commit (30.8-32.2 GB with the read marks alone). What changed: a title texture's host texture can be given up and made again on its next use (the owner is a resettable slot; host copies are returned owned). Host textures fed from title memory (no render target, depth or unordered access, nothing written by host copies) carry use stamps: a list of the title's naming them (tables, copies; our own upload lists do not stamp), and, at each pass, every read mark set since the last pass on a heap slot viewing them (the marks are then cleared; a slot's read is reported as new only once, so stamping on the first read alone gave up textures read every frame: run evict1 gave up and made again hundreds a frame). Once per presented frame, before a submission, those unused for 120 s and 300 presented frames are given up (shorter idle times gave up textures read again within a minute, runs evict2 to evict4), and past 90 % of the card's budget the least recently used others until 85 %. Giving one up first gives every heap slot viewing it a null view of its kind (retired until the running submission has run; the record stays noted, so heap syncs pass it by and a draw's or shader's read makes it again), then the title textures let go of it; lists recorded before hold it until they are reset, so no GPU work reads it freed. The next use makes it again from title memory (a fresh upload). Uploads of heap-viewed textures skip those not made. GPU-written textures are never given up; they go with their title texture. The cap on placed texture bytes is gone (the budget bounds video memory instead). Measured, 240 s of the intro cutscene each. With giving up (run evict2) against without (noevict1, the same tree with the pass off): card memory flat at 7.6-9.5 GB against 6.4 GB rising to 10.4 GB (86 % of the budget) at the end; host textures 6.1-7.8 GB against 5.2 GB rising to 8.6 GB; process commit 26.2 GB against 27.7 GB on average (29.7 GB and rising at the end). With the rest of its stack (run evict6) against main (perf13): median world frame 1,206 ms against 475 ms; frames uploading under 50 MB of textures 559 ms (+18 %, run evict4); a new shot's uploads cost 3-4 ms of frame per MB. Evidence: tests `host::tests::textures_read_every_frame_stay_and_title_lists_stamp_theirs`, `host::tests::heap_reads_since_the_last_pass_name_their_textures`, `draw::tests::a_texture_given_up_is_made_again_with_its_bytes_and_recorded_lists_keep_it`, `descriptor::host::tests::a_slot_viewing_a_texture_given_up_is_made_again_when_read`, `resource::tests::only_textures_fed_from_title_memory_are_given_up` and `resource::tests::idle_textures_go_and_past_the_budget_the_least_recently_used`; the crate's tests three times with 8 threads. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/bindless.rs | 15 +- crates/victory-gpu/src/descriptor.rs | 47 ++- crates/victory-gpu/src/descriptor/host.rs | 118 ++++++- crates/victory-gpu/src/draw.rs | 51 ++- crates/victory-gpu/src/host.rs | 126 +++++++- crates/victory-gpu/src/list.rs | 32 +- crates/victory-gpu/src/queue.rs | 3 +- crates/victory-gpu/src/resource.rs | 376 ++++++++++++++++++++-- crates/victory-gpu/src/shadow.rs | 25 ++ crates/victory-gpu/src/texture.rs | 4 +- 10 files changed, 718 insertions(+), 79 deletions(-) diff --git a/crates/victory-gpu/src/bindless.rs b/crates/victory-gpu/src/bindless.rs index aaa4fa4db3..864f25219b 100644 --- a/crates/victory-gpu/src/bindless.rs +++ b/crates/victory-gpu/src/bindless.rs @@ -154,9 +154,9 @@ fn seen(view: &View) -> Option { let placed = crate::descriptor::host::placed_texture(view); let view = placed.as_ref().unwrap_or(view); if let View::Shader(resource, _) = view - && let Some(texture) = crate::resource::host_resource(*resource as This) + && let Some(texture) = crate::resource::made_copy(*resource as This) { - return crate::texture::title_written(texture).then_some(Seen::Texture(*resource)); + return crate::texture::title_written(&texture.texture).then_some(Seen::Texture(*resource)); } // The copy the host view reads. let (shadow, address, len) = match *view { @@ -207,7 +207,11 @@ pub(crate) fn uploads( // Closed by the last submission, which has run. Some(list) => list.reset(), // Made open. - None => guard.0 = Some(crate::host::host()?.new_list().ok()?), + None => { + let list = crate::host::host()?.new_list().ok()?; + list.set_ours(); + guard.0 = Some(list); + } } let list = guard.0.as_ref()?; let mut recorded = false; @@ -231,10 +235,11 @@ pub(crate) fn uploads( if !done.insert(r) { continue; } - let Some(texture) = crate::resource::host_resource(r as This) else { + // Not made (given up, or never read): nothing to bring up. + let Some(texture) = crate::resource::made_copy(r as This) else { continue; }; - if crate::texture::upload_changed(list, r as This, texture) { + if crate::texture::upload_changed(list, r as This, &texture.texture) { crate::list::ensure_state(list, r as This, SHADER_RESOURCE); recorded = true; #[cfg(feature = "diagnostics")] diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 88d6d21162..871522e5fa 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -197,19 +197,11 @@ pub(crate) fn sync_heaps() { } /// Makes the views of slots `slots` that were left null (textures the title -/// placed itself) in every shader-visible view heap, now that shaders read -/// them (`crate::shadow::take_reads`), while placed textures take under -/// [`PLACED_CAP`] bytes. -/// shortcut: past the cap, views read later stay null; nothing is released -/// for them (placed textures are kept until the end); add eviction by the -/// read marks if the cap is reached. +/// placed itself, textures given up) in every shader-visible view heap, now +/// that shaders read them (`crate::shadow::take_reads`), and stamps what +/// they view as used (`crate::resource::evict`). #[cfg(windows)] pub(crate) fn make_read(slots: &[u32]) { - if crate::resource::PLACED_BYTES.load(std::sync::atomic::Ordering::Relaxed) >= PLACED_CAP { - static ONCE: std::sync::Once = std::sync::Once::new(); - ONCE.call_once(|| tracing::warn!("placed textures reached their cap: views shaders read now stay null")); - return; - } let heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner()); for &(start, _, at) in heaps.iter() { // SAFETY: registered heaps are live (removed when dropped). @@ -222,14 +214,41 @@ pub(crate) fn make_read(slots: &[u32]) { } for &i in slots.iter().filter(|&&i| i < heap.desc.count) { host.mirror(i, start + u64::from(i) * u64::from(step), true); + host.stamp_read(i); + } + } +} + +/// The host textures (raw pointers) that slots `slots` of the +/// shader-visible view heaps view. +#[cfg(windows)] +pub(crate) fn read_textures(slots: &[u32]) -> std::collections::HashSet { + let heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner()); + let mut textures = std::collections::HashSet::new(); + for &(_, _, at) in heaps.iter() { + // SAFETY: registered heaps are live (removed when dropped). + let heap = unsafe { &*(at as *const Heap) }; + if let (Some(Some(host)), VIEWS_KIND) = (heap.host.get(), heap.desc.kind) { + textures.extend(host.textures_at(slots)); } } + textures } -/// Console bytes of placed textures past which views shaders read stay -/// null: the 12 GB card held 6.5 GB without them (run textures2). +/// Every shader-visible view heap's slots viewing one of the host textures +/// `textures` (raw pointers) are left null, made again when read +/// (`crate::resource::evict` gives those textures up). #[cfg(windows)] -const PLACED_CAP: u64 = 3 << 30; +pub(crate) fn evict(textures: &std::collections::HashSet) { + let heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner()); + for &(_, _, at) in heaps.iter() { + // SAFETY: registered heaps are live (removed when dropped). + let heap = unsafe { &*(at as *const Heap) }; + if let (Some(Some(host)), VIEWS_KIND) = (heap.host.get(), heap.desc.kind) { + host.evict(textures); + } + } +} /// Gives back dynamic slots of the host heap behind the title heap at /// `heap`, if that heap still exists. diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 3d63fcaca1..f2092e722f 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -31,6 +31,9 @@ pub(crate) struct HostHeap { /// read there is a GPU page fault (the console reads stale memory). /// With it the view's own copy of title memory, if it has one. kept: Mutex>, + /// The slots each kept texture is viewed in (by its raw pointer), for + /// textures given up ([`HostHeap::evict`]). + by_texture: Mutex>>, /// Where the search for free dynamic slots starts, and which are taken /// (by lists not yet reset). next: Mutex<(u32, Vec)>, @@ -194,6 +197,7 @@ impl HostHeap { sampler, made: Mutex::new(vec![0; count as usize]), kept: Mutex::new(vec![None; (count + extra) as usize]), + by_texture: Mutex::default(), next: Mutex::new((0, vec![false; extra as usize])), pairs: Mutex::new((count + extra, Vec::new())), pairs_end: match victory_shader::emit::NULL_BUFFER_VIEW { @@ -517,6 +521,23 @@ impl HostHeap { let mut kept = self.kept.lock().unwrap_or_else(|e| e.into_inner()); if let Some(slot) = kept.get_mut(index as usize) { let old = std::mem::replace(slot, resource); + // Textures (views without a copy of title memory) by slot. + let raw = |k: &Kept| k.as_ref().filter(|k| k.1.is_none()).map(|k| windows::core::Interface::as_raw(&k.0) as usize); + let (was, now) = (raw(&old), raw(slot)); + if was != now { + let mut by = self.by_texture.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(was) = was + && let Some(slots) = by.get_mut(&was) + { + slots.retain(|&i| i != index); + if slots.is_empty() { + by.remove(&was); + } + } + if let Some(now) = now { + by.entry(now).or_default().push(index); + } + } #[cfg(feature = "diagnostics")] if let Some((old, _)) = &old && !self.sampler @@ -696,7 +717,7 @@ impl HostHeap { // (heap syncs revisit it at every submission). let lazy = || { for_draw - && is_placed_texture(&view) + && is_texture(&view) && self.kept.lock().unwrap_or_else(|e| e.into_inner())[index as usize].is_none() }; if made[index as usize] != key || lazy() { @@ -752,6 +773,58 @@ impl HostHeap { Some(text) } + /// Slots viewing one of the host textures `textures` (raw pointers), + /// which are given up: each gets a null view of its kind and holds the + /// texture no more (retired until the running submission has run), its + /// record stays noted so heap syncs leave it, and the next draw reading + /// it through a table or shader reading it through the heap (its read + /// mark, cleared) makes it again. + pub(crate) fn evict(&self, textures: &std::collections::HashSet) { + let slots: Vec = { + let by = self.by_texture.lock().unwrap_or_else(|e| e.into_inner()); + textures.iter().filter_map(|t| by.get(t)).flatten().copied().collect() + }; + let made = self.made.lock().unwrap_or_else(|e| e.into_inner()); + for index in slots { + let key = made.get(index as usize).copied().unwrap_or(0); + let view = (key != 0).then(|| view_at(key as u32, (key >> 32) as u32)).flatten(); + match &view { + Some(v) => null_for(v, self.cpu(index)), + None => null_view(self.cpu(index)), + } + self.keep(index, None); + if index < self.count { + self.viewed.set(index, view.as_ref(), false); + crate::shadow::forget_read(index); + } + } + } + + /// The host textures (raw pointers) slots `slots` view. + pub(crate) fn textures_at(&self, slots: &[u32]) -> Vec { + let kept = self.kept.lock().unwrap_or_else(|e| e.into_inner()); + slots + .iter() + .filter_map(|&i| kept.get(i as usize)?.as_ref().filter(|k| k.1.is_none())) + .map(|k| windows::core::Interface::as_raw(&k.0) as usize) + .collect() + } + + /// A shader read slot `index` through the heap: the texture it views + /// was used now. + pub(crate) fn stamp_read(&self, index: u32) { + let key = self.made.lock().unwrap_or_else(|e| e.into_inner()).get(index as usize).copied().unwrap_or(0); + let Some(view) = (key != 0).then(|| view_at(key as u32, (key >> 32) as u32)).flatten() else { + return; + }; + let view = placed_texture(&view).unwrap_or(view); + if let View::Shader(r, _) = view + && let Some(t) = crate::resource::made_copy(r as crate::object::This) + { + t.stamp(); + } + } + /// Whether slot `index` was made from a record (tests). #[cfg(test)] pub(crate) fn made(&self, index: u32) -> bool { @@ -1407,6 +1480,13 @@ fn is_placed_texture(view: &View) -> bool { matches!(view, View::Placed(_, resource, _) if resource[0] != 1) } +/// Whether `view` is a shader view of a texture (one placed in memory, or a +/// resource object's): such a slot left null is made when read. +fn is_texture(view: &View) -> bool { + is_placed_texture(view) + || matches!(view, View::Shader(r, _) if crate::resource::texture_memory(*r as crate::object::This).is_some()) +} + /// A shader view of a texture the title placed in memory itself, as a view /// of the resource made for that memory (on first use). pub(crate) fn placed_texture(view: &View) -> Option { @@ -1644,6 +1724,42 @@ mod tests { assert!(host.kept(0), "made for the draw"); } + /// A slot viewing a texture given up (`crate::resource::evict`) holds it + /// no more: heap syncs pass it by, a draw reading it through a table + /// makes it again. + #[test] + fn a_slot_viewing_a_texture_given_up_is_made_again_when_read() { + if host().is_none() { + return; // no host GPU here + } + let null = std::ptr::null(); + let heap_desc: [u32; 8] = [0, 4, 1, 0, 0, 0, 0, 0]; + let mut heap = null; + let iid = crate::object::guid(0x8efb471d, 0x616c, 0x4f49, [0x90, 0xf7, 0x12, 0x7b, 0xb7, 0x63, 0xfa, 0x51]); + assert_eq!(crate::descriptor::create_heap(null, heap_desc.as_ptr().cast(), &iid, &mut heap), 0); + let title_heap = crate::descriptor::heap(heap); + // A 4x1 RGBA8 texture, linear, in memory of its own, and a 2D view. + let memory = vec![0u8; 1 << 16]; + let address = memory.as_ptr() as u64; + let words: [u32; 14] = [3, 0, 0, 0, 4, 0, 1, 1 | 1 << 16, 28, 1, 0, 0x100, 0, 0]; + let mut view = [0u32; 16]; + view[..6].copy_from_slice(&[28, 4, 0x1688, 0, 0, 1]); + (view[10], view[11]) = (address as u32, (address >> 32) as u32); + crate::descriptor::create_placed_srv(null, &words, &view, title_heap.start); + let host = title_heap.host().expect("a host view heap"); + assert!(host.mirror(0, title_heap.start, true).is_some()); + assert!(host.kept(0), "made for the draw"); + let texture = crate::resource::texture_at(address, &words).expect("its resource"); + assert!(crate::resource::give_up_now(texture)); + assert!(!host.kept(0), "the slot holds it no more"); + assert!(host.made(0), "its record stays noted"); + assert!(host.mirror(0, title_heap.start, false).is_some()); + assert!(!host.kept(0), "heap syncs pass it by"); + assert!(host.mirror(0, title_heap.start, true).is_some()); + assert!(host.kept(0), "made again for the draw"); + assert!(crate::resource::made_copy(texture).is_some(), "with a host texture again"); + } + /// A heap sync makes the slots whose records the title changed as bytes /// (a copy of another slot's record, a record cleared) and passes the /// others by. diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index e1c410cb22..ba35ed921d 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -337,7 +337,7 @@ impl State { self.targets.push(record.resource as usize); #[cfg(feature = "diagnostics")] crate::capture::note_target(list, record.resource); - rtvs.push(host.rtv(texture, record.desc().as_ref())); + rtvs.push(host.rtv(&texture, record.desc().as_ref())); } self.depth = 0; let dsv = crate::descriptor::dsv_record(depth).and_then(|record| { @@ -345,7 +345,7 @@ impl State { self.depth = record.resource as usize; #[cfg(feature = "diagnostics")] crate::capture::note_target(list, record.resource); - Some(host.dsv(texture, record.depth_desc().as_ref())) + Some(host.dsv(&texture, record.depth_desc().as_ref())) }); // SAFETY: an open list; the views were just made. unsafe { @@ -1319,7 +1319,7 @@ impl State { // SAFETY: an open list. unsafe { list.list.ResourceBarrier(&[all]) }; crate::list::ensure_state(list, r as This, COPY_SOURCE); - let read = crate::capture::read_back(&host.device, &list.list, t); + let read = crate::capture::read_back(&host.device, &list.list, &t); crate::list::ensure_state(list, r as This, UNORDERED); let Some((buffer, f)) = read else { continue }; list.keep(&buffer); @@ -1759,9 +1759,9 @@ fn readable(list: &HostList, u: &UsedResource, view: &View, marked: bool) { match (view, u.kind) { (View::Shader(resource, _), ResourceType::Srv) => { if let Some(t) = crate::resource::host_resource(*resource as This) - && crate::texture::title_written(t) + && crate::texture::title_written(&t) { - crate::texture::upload(list, *resource as This, t); + crate::texture::upload(list, *resource as This, &t); } crate::list::ensure_state(list, *resource as This, SHADER_RESOURCE); #[cfg(feature = "diagnostics")] @@ -2400,6 +2400,47 @@ void main(uint3 id : SV_DispatchThreadID) { assert_eq!(submit(Some(0x80)).0, 0, "the same bytes in a shared page: not uploaded"); } + /// A texture fed from title memory given up (`resource::evict`) while a + /// recorded list names it: the list still reads it, and the next use + /// makes it again with its bytes from title memory. + #[test] + fn a_texture_given_up_is_made_again_with_its_bytes_and_recorded_lists_keep_it() { + let Some(host) = crate::host::host() else { + return; // no host GPU here + }; + let slots = Slots::new(2); + let read = compile_cs(READ); + let (out, data) = host.shared_buffer(64 * 64 * 16).unwrap(); + let address = crate::watch::tests::pool(1) as u64; + let object = texture_at_address(address, &texture_words(64, 64, 28, 0x100, 0)); + // SAFETY: the texture's memory, 256-byte rows of 64 texels. + unsafe { std::ptr::write_bytes(address as *mut u8, 0x40, 64 * 64 * 4) }; + let mut desc = [0u32; 10]; + desc[..6].copy_from_slice(&[28, 4, 0x1688, 0, 0, 1]); + let view = View::Shader(object as usize, Some(desc)); + let record = || { + slots.make(0, &view); + let list = host.new_list().unwrap(); + readable(&list, &used(ResourceType::Srv), &view, false); + run(&list, &slots, &read, 0, Some(&out), (8, 8)); + list.close(); + list + }; + // SAFETY: inside the mapped output. + let texel = || unsafe { (data as *const [f32; 4]).read() }[0]; + let list = record(); + assert!(crate::resource::give_up_now(object), "fed from title memory"); + assert!(crate::resource::made_copy(object).is_none(), "its title texture let go"); + host.execute(&[&list]); + assert!((texel() - 64.0 / 255.0).abs() < 1e-6, "the recorded list read it"); + // SAFETY: inside the mapped output. + unsafe { std::ptr::write_bytes(data, 0, 16) }; + let list = record(); + host.execute(&[&list]); + assert!((texel() - 64.0 / 255.0).abs() < 1e-6, "made again with its bytes"); + assert_eq!(crate::texture::uploads(object), 1, "uploaded into the new one"); + } + /// A texture written in a page that holds only its own bytes is uploaded /// without hashing them (a movie frame rewritten every frame), so even /// the same bytes again are uploaded. diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 5dfe70eafa..74e4967845 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -346,8 +346,7 @@ fn log_gpu_times(frames: f64) { /// (on the card) and non-local (system memory the GPU reads), as the /// system's memory manager sees them: use over budget makes it page /// allocations at submissions. -#[cfg(feature = "diagnostics")] -fn video_memory() -> Option<[(f64, f64); 2]> { +pub(crate) fn video_memory() -> Option<[(f64, f64); 2]> { static ADAPTER: OnceLock> = OnceLock::new(); let adapter = ADAPTER .get_or_init(|| { @@ -415,6 +414,105 @@ mod tests { assert!(crate::shadow::take_reads().contains(&memory), "read again after it was forgotten"); } + /// The textures shaders read through the heap since the last eviction + /// pass are named again at each pass (a slot's read is reported as new + /// only once), and the marks are cleared for the next. + #[test] + fn heap_reads_since_the_last_pass_name_their_textures() { + let Some(host) = host() else { return }; + let null = std::ptr::null(); + let heap_desc: [u32; 8] = [0, 4, 1, 0, 0, 0, 0, 0]; + let mut heap = null; + let iid = crate::object::guid(0x8efb471d, 0x616c, 0x4f49, [0x90, 0xf7, 0x12, 0x7b, 0xb7, 0x63, 0xfa, 0x51]); + assert_eq!(crate::descriptor::create_heap(null, heap_desc.as_ptr().cast(), &iid, &mut heap), 0); + let title_heap = crate::descriptor::heap(heap); + // A 4x1 RGBA8 texture, linear, in memory of its own, and a 2D view. + let memory = vec![0u8; 1 << 16]; + let address = memory.as_ptr() as u64; + let words: [u32; 14] = [3, 0, 0, 0, 4, 0, 1, 1 | 1 << 16, 28, 1, 0, 0x100, 0, 0]; + let mut view = [0u32; 16]; + view[..6].copy_from_slice(&[28, 4, 0x1688, 0, 0, 1]); + (view[10], view[11]) = (address as u32, (address >> 32) as u32); + crate::descriptor::create_placed_srv(null, &words, &view, title_heap.start); + let heap_host = title_heap.host().expect("a host view heap"); + assert!(heap_host.mirror(0, title_heap.start, true).is_some()); + let texture = crate::resource::texture_at(address, &words).expect("its resource"); + let raw = windows::core::Interface::as_raw(&crate::resource::made_copy(texture).unwrap().texture) as usize; + // No submission takes the marks meanwhile. + let _one = host.submitted.lock().unwrap_or_else(|e| e.into_inner()); + for _ in 0..2 { + crate::shadow::tests::mark_read(false, 0); + let slots = crate::shadow::reads_since(); + assert!(slots.contains(&0), "the slot read"); + assert!(crate::descriptor::read_textures(&slots).contains(&raw), "its texture named"); + assert!(!crate::shadow::reads_since().contains(&0), "the marks cleared"); + } + } + + /// The idle rule against the heap reads that thrashed (run evict1): a + /// texture shaders read through the heap in every frame stays over more + /// frames and time than the idle limits; one read once is given up. A + /// list of the title's naming a texture (a table read, a copy) stamps it + /// as used; a list of ours (uploads) does not. + #[test] + fn textures_read_every_frame_stay_and_title_lists_stamp_theirs() { + let Some(host) = host() else { return }; + let null = std::ptr::null(); + let heap_desc: [u32; 8] = [0, 8, 1, 0, 0, 0, 0, 0]; + let mut heap = null; + let iid = crate::object::guid(0x8efb471d, 0x616c, 0x4f49, [0x90, 0xf7, 0x12, 0x7b, 0xb7, 0x63, 0xfa, 0x51]); + assert_eq!(crate::descriptor::create_heap(null, heap_desc.as_ptr().cast(), &iid, &mut heap), 0); + let title_heap = crate::descriptor::heap(heap); + let step = 32; + // Two 4x1 RGBA8 textures, linear, in memory of their own, viewed at + // slots 5 and 6. + let memory = vec![0u8; 1 << 17]; + let words: [u32; 14] = [3, 0, 0, 0, 4, 0, 1, 1 | 1 << 16, 28, 1, 0, 0x100, 0, 0]; + let heap_host = title_heap.host().expect("a host view heap"); + let textures: Vec = [5u32, 6] + .iter() + .map(|&slot| { + let address = memory.as_ptr() as u64 + u64::from(slot) * (1 << 13); + let mut view = [0u32; 16]; + view[..6].copy_from_slice(&[28, 4, 0x1688, 0, 0, 1]); + (view[10], view[11]) = (address as u32, (address >> 32) as u32); + let at = title_heap.start + u64::from(slot) * step; + crate::descriptor::create_placed_srv(null, &words, &view, at); + assert!(heap_host.mirror(slot, at, true).is_some()); + crate::resource::texture_at(address, &words).expect("its resource") + }) + .collect(); + let owned: Vec<_> = textures.iter().map(|&t| crate::resource::owned(t).expect("may be given up")).collect(); + let (idle_frames, idle_ms) = (crate::resource::IDLE_FRAMES, crate::resource::IDLE_MS); + { + // No submission takes the marks meanwhile. + let _one = host.submitted.lock().unwrap_or_else(|e| e.into_inner()); + // Passes a third of the idle limits apart, over three times them. + for k in 0..10 { + crate::shadow::tests::mark_read(false, 5); + if k == 0 { + crate::shadow::tests::mark_read(false, 6); + } + let read = crate::descriptor::read_textures(&crate::shadow::reads_since()); + crate::resource::evict_among(&owned, &read, 1000 + k * idle_frames / 3, 1_000_000 + k * idle_ms / 3, 0); + assert!(crate::resource::made_copy(textures[0]).is_some(), "read every frame: stays (frame {k})"); + } + } + assert!(crate::resource::made_copy(textures[1]).is_none(), "read once: given up"); + drop(owned); + // A title list naming the texture stamps it, an upload list does not. + let copy = crate::resource::host_copy(textures[0]).unwrap(); + for (ours, stamped) in [(true, false), (false, true)] { + copy.unstamp(); + let list = host.new_list().unwrap(); + if ours { + list.set_ours(); + } + let _ = list.transition(textures[0], 0x40); + assert_eq!(copy.last_used() != (0, 0), stamped, "ours: {ours}"); + } + } + #[test] fn list_scratch_grows_to_fit_and_reuses_fenced_chunks() { let Some(host) = host() else { return }; @@ -593,6 +691,9 @@ pub(crate) struct HostList { /// A copy of ours replaced the list's compute root signature and /// pipeline: draws and dispatches set theirs again. rebind: std::sync::atomic::AtomicBool, + /// A list of ours (uploads), whose uses are no use of the title's + /// (`crate::resource::evict`). + ours: std::sync::atomic::AtomicBool, /// The list that runs those transitions just before this one. prelude: (ID3D12CommandAllocator, ID3D12GraphicsCommandList), /// The pipelines the list binds, for reports of slow submissions. @@ -894,6 +995,7 @@ impl Host { states: Mutex::default(), twins: Mutex::default(), rebind: false.into(), + ours: false.into(), prelude: (prelude_allocator, prelude), pipelines: Mutex::default(), id, @@ -918,6 +1020,9 @@ impl Host { let faults = crate::copystat::page_faults(); #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::Submissions, 1); + // Host textures the title has not used for a while (or past the + // card's budget) are given up first: the last submission has run. + crate::resource::evict_unused(); // Descriptors the title copied into its heaps itself, before the // heaps' views are brought up to date below. #[cfg(feature = "diagnostics")] @@ -1552,15 +1657,17 @@ impl HostList { &self, resource: crate::object::This, wanted: u32, - ) -> Option<(&'static ID3D12Resource, u32)> { - let texture = crate::resource::host_resource(resource)?; + ) -> Option<(ID3D12Resource, u32)> { + // One host texture for the whole move (`crate::resource::evict` may + // give it up meanwhile; this list then holds it). let copy = crate::resource::host_copy(resource)?; + let texture = copy.texture.clone(); if let Some(Some(twin)) = copy.twin.get() && crate::twin::route(self, ©, twin, wanted) { return None; } - let wanted = legal_state(texture, wanted); + let wanted = legal_state(&texture, wanted); self.track(©, wanted).map(|before| (texture, before)) } @@ -1572,6 +1679,9 @@ impl HostList { match states.entry(std::sync::Arc::as_ptr(copy) as usize) { std::collections::hash_map::Entry::Vacant(v) => { copy.note_used(); + if !self.ours.load(Ordering::Relaxed) { + copy.stamp(); + } v.insert((wanted, wanted, copy.clone())); None } @@ -1618,6 +1728,12 @@ impl HostList { } } + /// The list is one of ours (uploads): what it uses is no use of the + /// title's. + pub(crate) fn set_ours(&self) { + self.ours.store(true, Ordering::Relaxed); + } + /// A copy of ours replaced the compute root signature and pipeline. pub(crate) fn need_rebind(&self) { self.rebind.store(true, Ordering::Relaxed); diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 75c383fa25..9801e0ba54 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -326,7 +326,7 @@ fn host_barrier(list: &crate::host::HostList, b: &Barrier) -> Option { flags: 0, first: texture.as_raw().cast_const().cast(), second: 0xffff_ffff | (u64::from(before) << 32), - last: u64::from(crate::host::legal_state(texture, wanted)), + last: u64::from(crate::host::legal_state(&texture, wanted)), }) } 1 => Some(Barrier { @@ -408,8 +408,8 @@ extern "system" fn barrier(this: This, count: u32, barriers: *const Barrier) -> pub(crate) fn ensure_state(list: &crate::host::HostList, resource: This, state: u32) { use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_STATES as State; if let Some((texture, before)) = list.transition(resource, state) { - let state = crate::host::legal_state(texture, state); - let barrier = crate::host::transition(texture, State(before as i32), State(state as i32)); + let state = crate::host::legal_state(&texture, state); + let barrier = crate::host::transition(&texture, State(before as i32), State(state as i32)); // SAFETY: an open list and a live texture. unsafe { list.list.ResourceBarrier(&[barrier]) }; } @@ -463,8 +463,8 @@ extern "system" fn copy_resource(this: This, dst: This, src: This) { crate::resource::host_resource(dst), crate::resource::host_resource(src), ) { - if crate::texture::title_written(from) { - crate::texture::upload(list, src, from); + if crate::texture::title_written(&from) { + crate::texture::upload(list, src, &from); } ensure_state(list, dst, COPY_DEST); ensure_state(list, src, COPY_SOURCE); @@ -472,7 +472,7 @@ extern "system" fn copy_resource(this: This, dst: This, src: This) { #[cfg(feature = "diagnostics")] list.note_op(|| format!("copy resource {src:?} to {dst:?}")); // SAFETY: an open list and live textures. - unsafe { list.list.CopyResource(to, from) }; + unsafe { list.list.CopyResource(&to, &from) }; } else if let (Some((to, a)), Some((from, b))) = ( crate::resource::buffer_bytes(dst), crate::resource::buffer_bytes(src), @@ -558,8 +558,8 @@ extern "system" fn copy_texture_region( let Some(texture) = crate::resource::host_resource(src.resource) else { return; }; - if crate::texture::title_written(texture) { - crate::texture::upload(list, src.resource, texture); + if crate::texture::title_written(&texture) { + crate::texture::upload(list, src.resource, &texture); } ensure_state(list, src.resource, COPY_SOURCE); from.resource = texture.as_raw().cast_const().cast(); @@ -667,8 +667,8 @@ fn read_back(list: &crate::host::HostList, dst: &CopyLocation, at: [u32; 3], src let (Some(title), Some((buffer, data))) = (buffer_range(dst.resource, dst.footprint.offset, len), list.readback(host, len)) else { return; }; - if crate::texture::title_written(texture) { - crate::texture::upload(list, src.resource, texture); + if crate::texture::title_written(&texture) { + crate::texture::upload(list, src.resource, &texture); } ensure_state(list, src.resource, COPY_SOURCE); let (mut to, mut from) = (*dst, *src); @@ -770,7 +770,7 @@ extern "system" fn resolve( let format = DXGI_FORMAT(format as i32); if (a.Width, a.Height) == (b.Width, b.Height) { list.list - .ResolveSubresource(to, dst_sub, from, src_sub, format); + .ResolveSubresource(&to, dst_sub, &from, src_sub, format); } else if let Ok(list1) = list.list.cast::() { // The console clips a larger source to the destination. let rect = RECT { @@ -780,11 +780,11 @@ extern "system" fn resolve( bottom: a.Height.min(b.Height) as i32, }; list1.ResolveSubresourceRegion( - to, + &to, dst_sub, 0, 0, - from, + &from, src_sub, Some(&rect), format, @@ -833,13 +833,13 @@ extern "system" fn clear_rtv( unsafe { std::slice::from_raw_parts(rects.cast(), count as usize) } }); const RENDER_TARGET: u32 = 0x4; - let rtv = host.rtv(texture, record.desc().as_ref()); + let rtv = host.rtv(&texture, record.desc().as_ref()); // SAFETY: an open list, a fresh view of a live texture. unsafe { if let Some((_, before)) = list.transition(record.resource, RENDER_TARGET) { use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_STATES as State; list.list.ResourceBarrier(&[crate::host::transition( - texture, + &texture, State(before as i32), State(RENDER_TARGET as i32), )]); @@ -881,7 +881,7 @@ extern "system" fn clear_dsv( }); const DEPTH_WRITE: u32 = 0x10; ensure_state(list, record.resource, DEPTH_WRITE); - let dsv = host.dsv(texture, record.depth_desc().as_ref()); + let dsv = host.dsv(&texture, record.depth_desc().as_ref()); // SAFETY: an open list, a fresh view of a live texture. unsafe { list.list diff --git a/crates/victory-gpu/src/queue.rs b/crates/victory-gpu/src/queue.rs index ba071b7977..e3a76bf05e 100644 --- a/crates/victory-gpu/src/queue.rs +++ b/crates/victory-gpu/src/queue.rs @@ -227,7 +227,6 @@ fn system_timestamp() -> u64 { /// Frames presented so far. static FRAMES: AtomicU64 = AtomicU64::new(0); -#[cfg(feature = "diagnostics")] pub(crate) fn presented() -> u64 { FRAMES.load(Ordering::Relaxed) } @@ -294,7 +293,7 @@ extern "system" fn present( const COPY_SOURCE: u32 = 0x800; let state = crate::resource::host_transition(resource, COPY_SOURCE) .map_or(COPY_SOURCE, |(_, before)| before); - let shown = host.present(texture, state, frame); + let shown = host.present(&texture, state, frame); crate::resource::host_transition(resource, state); #[cfg(feature = "diagnostics")] blinks(frame, resource, state, shown); diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index 640532c9d0..a5022b17e1 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -778,9 +778,10 @@ struct Resource { heap_flags: u32, backing: Backing, /// Textures also live on the host GPU (decision 0007), made on first use - /// ([`Resource::host`]); buffers do not yet. + /// ([`Resource::host`]); buffers do not yet. `None`: not made (yet, or + /// given up by [`evict`]); `Some(None)`: the host refused it. #[cfg(windows)] - host: std::sync::OnceLock>>, + host: std::sync::Mutex>>>, /// The creation's initial state and clear value, for the host texture. #[cfg(windows)] made_with: (u32, Option<[u32; 5]>), @@ -817,6 +818,11 @@ pub(crate) struct HostTexture { used: std::sync::atomic::AtomicBool, /// A shader-visible heap slot viewed it (diagnostics: [`texture_census`]). pub(crate) viewed: std::sync::atomic::AtomicBool, + /// The memory it copies, for title textures fed from it. + key: Option, + /// When the title last used it: presented frame and milliseconds since + /// the first stamp ([`HostTexture::stamp`]). + last: [std::sync::atomic::AtomicU64; 2], } #[cfg(windows)] @@ -843,9 +849,38 @@ impl HostTexture { bytes, used: false.into(), viewed: false.into(), + key: None, + last: [crate::queue::presented().into(), now_ms().into()], } } + /// The title used it now: a list of the title's names it, or a shader + /// read a heap slot viewing it (`crate::descriptor::make_read`). + pub(crate) fn stamp(&self) { + self.stamp_at(crate::queue::presented(), now_ms()); + } + + /// Used at presented frame `frame`, `ms` milliseconds in. + fn stamp_at(&self, frame: u64, ms: u64) { + use std::sync::atomic::Ordering::Relaxed; + self.last[0].store(frame, Relaxed); + self.last[1].store(ms, Relaxed); + } + + /// When the title last used it: presented frame and milliseconds + /// (tests). + #[cfg(test)] + pub(crate) fn last_used(&self) -> (u64, u64) { + use std::sync::atomic::Ordering::Relaxed; + (self.last[0].load(Relaxed), self.last[1].load(Relaxed)) + } + + /// Forgets its uses (tests: a stamp is then seen to happen). + #[cfg(test)] + pub(crate) fn unstamp(&self) { + self.stamp_at(0, 0); + } + /// A list uses it: counted the first time (diagnostics of how much of /// the host textures' memory the GPU ever touches). pub(crate) fn note_used(&self) { @@ -1021,15 +1056,24 @@ pub(crate) fn host_transition(this: This, wanted: u32) -> Option<(*mut c_void, u (before != wanted).then(|| (host.texture.as_raw(), before)) } -/// The host GPU's copy of a title resource, if it has one. +/// The host GPU's copy of a title resource, if it has one (made on first +/// use). Owned: [`evict`] may give the host texture up meanwhile. #[cfg(windows)] -pub(crate) fn host_resource<'a>( - this: This, -) -> Option<&'a windows::Win32::Graphics::Direct3D12::ID3D12Resource> { +pub(crate) fn host_resource(this: This) -> Option { + if this.is_null() { + return None; + } + resource(this).host().map(|h| h.texture.clone()) +} + +/// A title texture's host copy if it is made, without making it: for work +/// that is no use of the title's (uploads of what heap slots view). +#[cfg(windows)] +pub(crate) fn made_copy(this: This) -> Option> { if this.is_null() { return None; } - resource(this).host().map(|h| &h.texture) + resource(this).host.lock().unwrap_or_else(|e| e.into_inner()).clone().flatten() } /// A title texture's host copy, shared, for a list to hold. @@ -1038,7 +1082,7 @@ pub(crate) fn host_copy(this: This) -> Option> { if this.is_null() { return None; } - resource(this).host().cloned() + resource(this).host() } /// The host description of a title texture: the same, without the @@ -1184,8 +1228,11 @@ fn shared_texture( // shortcut: title textures of a replaced host texture keep it (placed // views move to the new one, `texture_at`); copies (`alias_source`) // bridge the two where the shapes allow. - let t = std::sync::Arc::new(make_texture(&d, state, clear)?); + let mut t = make_texture(&d, state, clear)?; + t.key = key; + let t = std::sync::Arc::new(t); if let Some(k) = key { + remade(&k); if live.is_some() { REPLACED.fetch_add(1, std::sync::atomic::Ordering::Relaxed); tracing::debug!(?k, "a texture memory's host texture replaced by one with more uses or another format"); @@ -1216,13 +1263,14 @@ fn takes(t: &HostTexture, d: &ResourceDesc) -> bool { #[cfg(windows)] fn current(this: This) -> bool { let r = resource(this); - let (Some(Some(h)), Some(k)) = (r.host.get(), memory_key(r.data() as u64, &r.desc)) else { + let made = r.host.lock().unwrap_or_else(|e| e.into_inner()).clone(); + let (Some(Some(h)), Some(k)) = (made, memory_key(r.data() as u64, &r.desc)) else { return true; }; let map = MEMORY.lock().unwrap_or_else(|e| e.into_inner()); map.as_ref() .and_then(|m| m.get(&k)?.upgrade()) - .is_none_or(|live| std::sync::Arc::ptr_eq(&live, h)) + .is_none_or(|live| std::sync::Arc::ptr_eq(&live, &h)) } /// A host texture of host description `d` in GPU memory, castable to @@ -1361,14 +1409,17 @@ impl Resource { /// of the title's textures are never used (decision 0007, "Host /// textures made on first use"). #[cfg(windows)] - fn host(&self) -> Option<&std::sync::Arc> { - self.host - .get_or_init(|| { - let (state, clear) = self.made_with; - let clear = clear.as_ref().map_or(std::ptr::null(), |c| std::ptr::from_ref(c).cast()); - shared_texture(self.data() as u64, &self.desc, state, clear) - }) - .as_ref() + fn host(&self) -> Option> { + if let Some(made) = self.host.lock().unwrap_or_else(|e| e.into_inner()).clone() { + return made; + } + // Made without the lock held (`shared_texture` takes the memory + // maps, which `evict` holds while it takes this lock). + let (state, clear) = self.made_with; + let clear = clear.as_ref().map_or(std::ptr::null(), |c| std::ptr::from_ref(c).cast()); + let made = shared_texture(self.data() as u64, &self.desc, state, clear); + // A texture made meanwhile by another thread is the memory's too. + self.host.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert(made).clone() } fn data(&self) -> *mut u8 { @@ -1392,6 +1443,221 @@ fn resource<'a>(this: This) -> &'a Resource { unsafe { &*this.cast::() } } +/// A title texture's host texture if it is made. +#[cfg(windows)] +fn made(r: &Resource) -> Option> { + r.host.lock().unwrap_or_else(|e| e.into_inner()).clone().flatten() +} + +/// Milliseconds since the first call: host textures' use stamps. +#[cfg(windows)] +fn now_ms() -> u64 { + static START: std::sync::OnceLock = std::sync::OnceLock::new(); + START.get_or_init(std::time::Instant::now).elapsed().as_millis() as u64 +} + +/// A host texture fed from title memory that the title has not used for +/// this long (and this many presented frames) is given up ([`evict`]). +/// Two minutes: of the textures given up after 20 s, nine in ten were +/// read again within a minute (run evict4). +#[cfg(windows)] +pub(crate) const IDLE_MS: u64 = 120_000; +/// Frames as well as time: in slow runs (seconds a frame) 20 s alone cycled +/// the textures of a cutscene's alternating shots (run evict2), and 30 +/// frames gave up what the menus and loading made (at 30 fps) before the +/// world read it (run evict3). At 30 fps the idle time decides; slower, the +/// card's budget does. +#[cfg(windows)] +pub(crate) const IDLE_FRAMES: u64 = 300; +/// Past this share of the card's memory budget, host textures fed from +/// title memory are given up least recently used first, until the card's +/// use is back under [`BUDGET_LOW`]. +#[cfg(windows)] +const BUDGET_HIGH: f64 = 0.90; +#[cfg(windows)] +const BUDGET_LOW: f64 = 0.85; +/// A texture made again within this many frames of being given up counts +/// as remade soon ([`EVICTIONS`]): too eager an [`IDLE_MS`]. +#[cfg(windows)] +const SOON_FRAMES: u64 = 10; + +/// Host textures given up, their bytes, those made again since, and those +/// made again within [`SOON_FRAMES`]. +#[cfg(windows)] +pub(crate) static EVICTIONS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// Memories whose host texture was given up, with the frame it was. +#[cfg(windows)] +static GIVEN_UP: std::sync::Mutex>> = std::sync::Mutex::new(None); + +/// A host texture is made for memory `k`: counted if it had been given up. +#[cfg(windows)] +fn remade(k: &MemoryKey) { + use std::sync::atomic::Ordering::Relaxed; + let mut given = GIVEN_UP.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(at) = given.as_mut().and_then(|g| g.remove(k)) { + EVICTIONS[2].fetch_add(1, Relaxed); + if crate::queue::presented().saturating_sub(at) <= SOON_FRAMES { + EVICTIONS[3].fetch_add(1, Relaxed); + } + } +} + +/// Whether host texture `t` may be given up: its contents come from title +/// memory alone (no render target, depth or unordered access, no host copy +/// or resolve wrote it), so a texture made again has them back. +#[cfg(windows)] +fn evictable(t: &HostTexture) -> bool { + t.key.is_some() && crate::texture::title_written(&t.texture) && !t.host_written.load(std::sync::atomic::Ordering::Relaxed) +} + +/// Once per presented frame, before a submission (`Host::execute`, one at a +/// time, the last one has run): gives up host textures fed from title memory +/// that the title has not used for [`IDLE_MS`], and past [`BUDGET_HIGH`] of +/// the card's budget the least recently used ones until [`BUDGET_LOW`]. +#[cfg(windows)] +pub(crate) fn evict_unused() { + use std::sync::atomic::Ordering::Relaxed; + static LAST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(u64::MAX); + let frame = crate::queue::presented(); + if LAST.swap(frame, Relaxed) == frame { + return; + } + let over = crate::host::video_memory().map_or(0, |[(used, budget), _]| { + if used > BUDGET_HIGH * budget { ((used - BUDGET_LOW * budget) * 1e6) as u64 } else { 0 } + }); + evict(frame, now_ms(), over); +} + +/// A host texture and the title textures (resource objects) holding it. +#[cfg(windows)] +pub(crate) type Owned = (std::sync::Arc, Vec); + +/// Gives up the host textures fed from title memory that the title has +/// not used for [`IDLE_MS`] and [`IDLE_FRAMES`] at (`frame`, `now` ms), +/// then least recently used ones until `over` bytes are gone +/// ([`give_up`]). Returns how many and their bytes. +#[cfg(windows)] +fn evict(frame: u64, now: u64, over: u64) -> (u64, u64) { + // Read through the heap since the last pass: used (a slot's read mark is + // reported as new only once, so its first read alone stamped it; run + // evict1 gave up and made again hundreds of textures a frame). + let read = crate::descriptor::read_textures(&crate::shadow::reads_since()); + evict_among(&candidates(), &read, frame, now, over) +} + +/// [`evict`] among `candidates`, with `read` (raw pointers) the host +/// textures shaders read through the heap since the last pass. +#[cfg(windows)] +pub(crate) fn evict_among( + candidates: &[Owned], + read: &std::collections::HashSet, + frame: u64, + now: u64, + over: u64, +) -> (u64, u64) { + use std::sync::atomic::Ordering::Relaxed; + for (t, _) in candidates { + if read.contains(&(windows::core::Interface::as_raw(&t.texture) as usize)) { + t.stamp_at(frame, now); + } + } + let uses: Vec<(u64, u64, u64)> = + candidates.iter().map(|(t, _)| (t.last[0].load(Relaxed), t.last[1].load(Relaxed), t.bytes)).collect(); + let chosen = choose(&uses, frame, now, over); + let gone: Vec = chosen.into_iter().map(|i| candidates[i].clone()).collect(); + give_up(&gone, frame) +} + +/// The host textures that may be given up ([`evictable`]), each with the +/// title textures holding it. +#[cfg(windows)] +fn candidates() -> Vec { + let at = TEXTURES_AT.lock().unwrap_or_else(|e| e.into_inner()); + let mut by: std::collections::HashMap = std::collections::HashMap::new(); + for &r in at.values().flatten() { + if let Some(t) = made(resource(r as This)).filter(|t| evictable(t)) { + by.entry(std::sync::Arc::as_ptr(&t) as usize).or_insert_with(|| (t, Vec::new())).1.push(r); + } + } + by.into_values().collect() +} + +/// Of textures last used at (frame, ms) taking (bytes) each, those to give +/// up at (`frame`, `now`): every one idle for [`IDLE_FRAMES`] and +/// [`IDLE_MS`], then the least recently used others until `over` bytes are +/// gone (indices). +fn choose(uses: &[(u64, u64, u64)], frame: u64, now: u64, over: u64) -> Vec { + let idle = |&(f, ms, _): &(u64, u64, u64)| frame.saturating_sub(f) >= IDLE_FRAMES && now.saturating_sub(ms) >= IDLE_MS; + let (mut gone, mut rest): (Vec, Vec) = (0..uses.len()).partition(|&i| idle(&uses[i])); + let mut over = over.saturating_sub(gone.iter().map(|&i| uses[i].2).sum()); + rest.sort_by_key(|&i| uses[i].1); + for i in rest { + if over == 0 { + break; + } + over = over.saturating_sub(uses[i].2); + gone.push(i); + } + gone +} + +/// Gives up host textures `gone` at `frame`: first every heap slot viewing +/// one gets a null view (made again when a draw or a shader reads it), then +/// the title textures let go of it. Lists recorded before hold it until +/// they are reset, so no GPU work reads it freed; the next use makes it +/// again from title memory. +/// shortcut: a use racing this (a title thread recording) may view the +/// texture made again in a list that moved the one given up; the pass +/// gives up only textures unused for a while, or the least recently used. +#[cfg(windows)] +fn give_up(gone: &[Owned], frame: u64) -> (u64, u64) { + use std::sync::atomic::Ordering::Relaxed; + if gone.is_empty() { + return (0, 0); + } + { + use windows::core::Interface; + let raws = gone.iter().map(|(t, _)| t.texture.as_raw() as usize).collect(); + crate::descriptor::evict(&raws); + } + let at = TEXTURES_AT.lock().unwrap_or_else(|e| e.into_inner()); + let live: std::collections::HashSet = at.values().flatten().copied().collect(); + let mut given = GIVEN_UP.lock().unwrap_or_else(|e| e.into_inner()); + let given = given.get_or_insert_with(Default::default); + given.retain(|_, &mut f| frame.saturating_sub(f) <= SOON_FRAMES); + let bytes = gone.iter().map(|(t, _)| t.bytes).sum(); + for (t, owners) in gone { + for &r in owners.iter().filter(|r| live.contains(r)) { + let mut h = resource(r as This).host.lock().unwrap_or_else(|e| e.into_inner()); + if matches!(&*h, Some(Some(x)) if std::sync::Arc::ptr_eq(x, t)) { + *h = None; + } + } + if let Some(k) = t.key { + given.insert(k, frame); + } + } + EVICTIONS[0].fetch_add(gone.len() as u64, Relaxed); + EVICTIONS[1].fetch_add(bytes, Relaxed); + (gone.len() as u64, bytes) +} + +/// Gives up `this`'s host texture as [`evict`] would (tests); false if it +/// has none or may not be given up. +#[cfg(all(windows, test))] +pub(crate) fn give_up_now(this: This) -> bool { + owned(this).is_some_and(|o| give_up(&[o], crate::queue::presented()).0 == 1) +} + +/// `this`'s host texture with the title textures holding it, if it may be +/// given up (tests: [`evict_among`] over textures of their own). +#[cfg(all(windows, test))] +pub(crate) fn owned(this: This) -> Option { + let t = made(resource(this))?; + candidates().into_iter().find(|(c, _)| std::sync::Arc::ptr_eq(c, &t)) +} + // The creation methods' own arguments, passed on. #[allow(clippy::too_many_arguments)] fn hand_out_resource( @@ -1413,7 +1679,7 @@ fn hand_out_resource( heap_flags, backing, #[cfg(windows)] - host: std::sync::OnceLock::new(), + host: std::sync::Mutex::new(None), // The clear value names the format too: format, then color or // depth and stencil (5 words), kept for when the texture is made. #[cfg(windows)] @@ -1469,7 +1735,7 @@ pub(crate) fn alias_source(placed: This) -> Option { let a = resource(r); a.desc.flags & WRITTEN != 0 && bytes(&a.desc) == Some(want) - && matches!((a.host.get(), b.host.get()), (Some(Some(x)), Some(Some(y))) if !std::sync::Arc::ptr_eq(x, y)) + && matches!((made(a), made(b)), (Some(x), Some(y)) if !std::sync::Arc::ptr_eq(&x, &y)) }) } @@ -1477,11 +1743,7 @@ pub(crate) fn alias_source(placed: This) -> Option { impl Drop for Resource { fn drop(&mut self) { #[cfg(feature = "diagnostics")] - if self - .host - .get() - .and_then(Option::as_ref) - .is_some_and(|h| std::sync::Arc::strong_count(h) > 1) + if made(self).is_some_and(|h| std::sync::Arc::strong_count(&h) > 2) { // Before lists held their textures, this freed a texture that // lists not yet run still named (a GPU page fault). @@ -1496,7 +1758,7 @@ impl Drop for Resource { } } #[cfg(feature = "diagnostics")] - if let Some(Some(h)) = self.host.get() { + if let Some(h) = made(self) { use windows::core::Interface; life::note(h.texture.as_raw() as usize, life::RELEASED, 0, life::holders(&h.texture)); } @@ -2053,7 +2315,7 @@ mod tests { }; let read = place(&texture(64, 64, 28, 1)); let written = place(&ResourceDesc { flags: UNORDERED, ..texture(64, 64, 28, 1) }); - assert!(resource(read).host.get().is_none() && resource(written).host.get().is_none(), "made at creation"); + assert!(made(resource(read)).is_none() && made(resource(written)).is_none(), "made at creation"); let first = host_copy(read).expect("a host texture"); // SAFETY: a live resource. assert_ne!(unsafe { first.texture.GetDesc() }.Flags.0 as u32 & UNORDERED, 0, "the memory's uses"); @@ -2064,6 +2326,62 @@ mod tests { assert_eq!(slot::(h, 0x10)(h), 0); } + /// Host textures the GPU writes (render target, depth, unordered access) + /// are never given up, and the title releasing its texture frees its + /// host texture (nothing else holds it); one fed from title memory is + /// given up and made again on its next use. + #[cfg(windows)] + #[test] + fn only_textures_fed_from_title_memory_are_given_up() { + if crate::host::host().is_none() { + return; // no host GPU here + } + let null = std::ptr::null(); + let h = heap(1 << 20); + let place = |offset: u64, desc: &ResourceDesc| { + let mut out = null; + assert_eq!(create_placed(null, h, offset, desc, 0, null.cast(), &RESOURCE_IIDS[0], &mut out), S_OK); + out + }; + let read = place(0, &texture(64, 64, 28, 1)); + let target = place(1 << 18, &ResourceDesc { flags: 1, ..texture(64, 64, 28, 1) }); + let (r, t) = (host_copy(read).unwrap(), host_copy(target).unwrap()); + let listed = candidates(); + assert!(listed.iter().any(|(c, _)| std::sync::Arc::ptr_eq(c, &r)), "fed from title memory"); + assert!(!listed.iter().any(|(c, _)| std::sync::Arc::ptr_eq(c, &t)), "the GPU writes it"); + let (weak_r, weak_t) = (std::sync::Arc::downgrade(&r), std::sync::Arc::downgrade(&t)); + drop((listed, r, t)); + let (r, t) = (weak_r, weak_t); + assert!(!give_up_now(target), "never given up"); + assert!(give_up_now(read)); + // (Not checked freed: a pass in another test may hold it a moment.) + assert!(made(resource(read)).is_none(), "given up"); + drop(r); + assert!(host_copy(read).is_some(), "made again on its next use"); + assert_eq!(slot::(target, 0x10)(target), 0); + assert!(t.upgrade().is_none(), "freed with its title texture"); + assert_eq!(slot::(read, 0x10)(read), 0); + assert_eq!(slot::(h, 0x10)(h), 0); + } + + /// Textures idle for the idle time and frames are given up; past the + /// budget the least recently used others follow until the excess is + /// gone. + #[test] + fn idle_textures_go_and_past_the_budget_the_least_recently_used() { + let (frame, now) = (1_000, 1_000_000); + let recent = (frame, now - 1_000, 10); + let idle = (frame - IDLE_FRAMES, now - IDLE_MS, 10); + let older = (frame, now - 5_000, 30); + let uses = [recent, idle, older]; + assert_eq!(choose(&uses, frame, now, 0), vec![1], "idle only"); + assert_eq!(choose(&uses, frame, now, 10), vec![1], "the idle one covers the excess"); + assert_eq!(choose(&uses, frame, now, 11), vec![1, 2], "then the least recently used"); + assert_eq!(choose(&uses, frame, now, 1 << 20), vec![1, 2, 0], "all of them if need be"); + let early = (frame - 1, now - IDLE_MS, 10); + assert!(choose(&[early], frame, now, 0).is_empty(), "too few frames ago"); + } + /// Title textures of one memory share a key in any format of the same /// element; another address, shape, element size or a depth texture is /// another memory. The library's own layout pick resolves as spelled. @@ -2488,7 +2806,7 @@ mod tests { // SAFETY: an open list, live resources, locations in the host layout. unsafe { back.list.ResourceBarrier(&[crate::host::transition( - host_image, + &host_image, D3D12_RESOURCE_STATES(before as i32), D3D12_RESOURCE_STATE_COPY_SOURCE, )]); diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 795e4a499c..eb862afe74 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -812,6 +812,31 @@ pub(crate) fn take_reads() -> Vec { new } +/// The heap slots shaders read texture views at since the last call (both +/// bitmaps), whose marks are cleared: what the title used (eviction stamps, +/// `crate::resource::evict`). Between submissions, after [`take_reads`] +/// has seen every mark: its own record of slots seen keeps a slot read +/// again from being reported as new. +pub(crate) fn reads_since() -> Vec { + let words = (victory_shader::emit::HEAP_VIEWS / 32) as usize; + let first = (victory_shader::emit::VIEW_READS / 32) as usize; + let mut slots = Vec::new(); + for b in [false, true].into_iter().filter_map(bitmap) { + // SAFETY: the mapped bitmap's read marks; no submission runs. + let bits = unsafe { std::slice::from_raw_parts_mut((b.data as *mut u32).add(first), words) }; + for (w, word) in bits.iter_mut().enumerate() { + let mut x = std::mem::take(word); + while x != 0 { + slots.push(w as u32 * 32 + x.trailing_zeros()); + x &= x - 1; + } + } + } + slots.sort_unstable(); + slots.dedup(); + slots +} + /// Heap slot `slot` now holds a texture view left null: its next read is /// marked again. pub(crate) fn forget_read(slot: u32) { diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index ba41fb4e62..c32e746060 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -257,7 +257,7 @@ pub(crate) fn alias_copy(list: &HostList, from: This, to: This) { // SAFETY: an open list; live resources in the states named. unsafe { for i in 0..n { - l.CopyTextureRegion(&place(&buffer, fa[i as usize]), 0, 0, 0, &sub(a, i), None); + l.CopyTextureRegion(&place(&buffer, fa[i as usize]), 0, 0, 0, &sub(&a, i), None); } l.ResourceBarrier(&[crate::host::transition( &buffer, @@ -265,7 +265,7 @@ pub(crate) fn alias_copy(list: &HostList, from: This, to: This) { D3D12_RESOURCE_STATE_COPY_SOURCE, )]); for i in 0..n { - l.CopyTextureRegion(&sub(b, i), 0, 0, 0, &place(&buffer, fb[i as usize]), None); + l.CopyTextureRegion(&sub(&b, i), 0, 0, 0, &place(&buffer, fb[i as usize]), None); } } ALIAS_COPIES.fetch_add(1, std::sync::atomic::Ordering::Relaxed); From 4959d3498d6f69189ff41355b79e815f16ce52ce Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 09:38:19 +0100 Subject: [PATCH 58/83] GPU: textures the heaps view are brought up to date only when shaders read them lately What was wrong: at every submission (about 30 a frame), every texture any heap slot of a heap-indexing list viewed was brought up to date: its staging refreshed and, where its pages had changed, detiled and uploaded, read or not. With placed textures made when read (4-8k textures, 5-8 GB viewed by the heaps) that re-uploaded about 4 GB in 30-46 world frames and took 0.3-3.7 s a frame (runs evict2, noevict1; main 5-25 ms). What changed: a heap-viewed texture is brought up only if the title used it in this presented frame or the last (made then, named by one of its lists, or read through the heap as the eviction pass's stamps found). Textures lists read through tables keep their own rule (the list names them). Uploads of heap-viewed textures are counted with the others. shortcut: a texture read again after a gap is brought up after the submission that read it, which can see bytes one refresh old. Evidence: test `host::tests::heap_textures_unread_lately_are_not_brought_up` (a viewed texture whose pages changed is not uploaded while not read lately; stamped as read, it is); the crate's tests twice with 8 threads. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/bindless.rs | 11 +++++++++++ crates/victory-gpu/src/host.rs | 31 +++++++++++++++++++++++++++++- crates/victory-gpu/src/resource.rs | 13 ++++++++++++- crates/victory-gpu/src/texture.rs | 2 ++ 4 files changed, 55 insertions(+), 2 deletions(-) diff --git a/crates/victory-gpu/src/bindless.rs b/crates/victory-gpu/src/bindless.rs index 864f25219b..b7a708a1fe 100644 --- a/crates/victory-gpu/src/bindless.rs +++ b/crates/victory-gpu/src/bindless.rs @@ -239,6 +239,17 @@ pub(crate) fn uploads( let Some(texture) = crate::resource::made_copy(r as This) else { continue; }; + // Only what shaders read lately (the eviction pass's stamps): + // the heaps view thousands of textures a frame never reads, and + // bringing each up whenever its pages change re-uploaded about + // 4 GB in 30-46 world frames (runs evict2, noevict1). + // shortcut: a texture read again after a gap is brought up after + // the submission that read it, which can see bytes one refresh + // old (a slot the title rewrites is made fresh anyway); upload on + // the mark itself if that shows. + if !texture.used_recently() { + continue; + } if crate::texture::upload_changed(list, r as This, &texture.texture) { crate::list::ensure_state(list, r as This, SHADER_RESOURCE); recorded = true; diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 74e4967845..f64a2a4663 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -509,10 +509,39 @@ mod tests { list.set_ours(); } let _ = list.transition(textures[0], 0x40); - assert_eq!(copy.last_used() != (0, 0), stamped, "ours: {ours}"); + assert_eq!(copy.last_used().0 != u64::MAX, stamped, "ours: {ours}"); } } + /// Textures the heaps view are brought up to date only if the title used + /// them lately: one whose pages changed but that no shader read is not + /// uploaded; read in the last pass, it is. + #[test] + fn heap_textures_unread_lately_are_not_brought_up() { + let Some(host) = host() else { return }; + let address = crate::watch::tests::pool(1) as u64; + let words: [u32; 14] = [3, 0, 0, 0, 64, 0, 64, 1 | 1 << 16, 28, 1, 0, 0x100, 0, 0]; + let iid = crate::object::guid(0x696442be, 0xa72e, 0x4059, [0xbc, 0x79, 0x5b, 0x5c, 0x98, 0x04, 0x0f, 0xad]); + let mut object = std::ptr::null(); + let null = std::ptr::null(); + assert_eq!(crate::resource::create_at_address(null, address, words.as_ptr().cast(), 0, std::ptr::null(), &iid, &mut object), 0); + let copy = crate::resource::host_copy(object).expect("a host texture"); + let mut desc = [0u32; 10]; + desc[..6].copy_from_slice(&[28, 4, 0x1688, 0, 0, 1]); + let viewed = std::sync::Arc::new(crate::bindless::Viewed::default()); + viewed.set(0, Some(&crate::descriptor::View::Shader(object as usize, Some(desc))), true); + // No submission uploads meanwhile. + let _one = host.submitted.lock().unwrap_or_else(|e| e.into_inner()); + // SAFETY: the texture's memory, 256-byte rows of 64 texels. + unsafe { std::ptr::write_bytes(address as *mut u8, 0x40, 64 * 64 * 4) }; + copy.unstamp(); + let _ = crate::bindless::uploads(std::slice::from_ref(&viewed), &[]); + assert_eq!(crate::texture::uploads(object), 0, "not read lately: not brought up"); + copy.stamp(); + let _ = crate::bindless::uploads(std::slice::from_ref(&viewed), &[]); + assert_eq!(crate::texture::uploads(object), 1, "read in the last pass: brought up"); + } + #[test] fn list_scratch_grows_to_fit_and_reuses_fenced_chunks() { let Some(host) = host() else { return }; diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index a5022b17e1..3ba05ce03b 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -878,7 +878,15 @@ impl HostTexture { /// Forgets its uses (tests: a stamp is then seen to happen). #[cfg(test)] pub(crate) fn unstamp(&self) { - self.stamp_at(0, 0); + self.stamp_at(NEVER, 0); + } + + /// Whether the title used it in this presented frame or the last one + /// (made then, named by a list of its own, or read through the heap as + /// the last pass found). + pub(crate) fn used_recently(&self) -> bool { + let frame = self.last[0].load(std::sync::atomic::Ordering::Relaxed); + frame != NEVER && frame.saturating_add(1) >= crate::queue::presented() } /// A list uses it: counted the first time (diagnostics of how much of @@ -1469,6 +1477,9 @@ pub(crate) const IDLE_MS: u64 = 120_000; /// card's budget does. #[cfg(windows)] pub(crate) const IDLE_FRAMES: u64 = 300; +/// A use stamp's frame for "never" (tests). +#[cfg(windows)] +const NEVER: u64 = u64::MAX; /// Past this share of the card's memory budget, host textures fed from /// title memory are given up least recently used first, until the card's /// use is back under [`BUDGET_LOW`]. diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index c32e746060..48bd6886b7 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -372,6 +372,8 @@ pub(crate) fn upload_changed(list: &HostList, resource: This, texture: &ID3D12Re crate::list::ensure_state(list, resource, COPY_DEST); copies(list, texture, &staging, &buffer, &subresources, || format!("{resource:?}")); list.keep(&buffer); + staging.uploads.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + staging.copied.fetch_add(subresources.len() as u64, std::sync::atomic::Ordering::Relaxed); true } From cea278c8973ca7fd853757be3554314ac21469f1 Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 09:38:20 +0100 Subject: [PATCH 59/83] GPU: textures for heap slots shaders read are made outside the heaps' lock What was wrong: after each submission, the views of heap slots shaders read for the first time (read marks) were made under `SHADER_HEAPS`, which every title thread writing a view takes: making a placed texture (its resource and host texture) took up to milliseconds each, and title threads waited 1-6 s a frame to write views (runs evict2, noevict1; main 0.2-0.3 s). What changed: the slots are looked up under the lock, the placed textures they view are made without it (they are never released, so they outlive it), and the lock is taken again only to make the views. Evidence: test `descriptor::host::tests::views_written_while_read_slots_get_their_textures_do_not_wait` (another thread writes a view while a read slot's texture is being made and finishes within a bounded wait); the crate's tests twice with 8 threads. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor.rs | 40 ++++++++++++++++- crates/victory-gpu/src/descriptor/host.rs | 54 +++++++++++++++++++++++ 2 files changed, 93 insertions(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 871522e5fa..778901daf4 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -202,6 +202,27 @@ pub(crate) fn sync_heaps() { /// they view as used (`crate::resource::evict`). #[cfg(windows)] pub(crate) fn make_read(slots: &[u32]) { + // The placed textures those slots view are made first, without the + // heaps' lock, which every title thread writing a view waits on (making + // a texture takes up to milliseconds; title threads waited 1-6 s a frame, + // runs evict2, noevict1). They are never released, so they outlive it; + // the lock is held only to look the slots up and to make the views. + let placed: Vec = { + let heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner()); + heaps + .iter() + // SAFETY: registered heaps are live (removed when dropped). + .map(|&(_, _, at)| unsafe { &*(at as *const Heap) }) + .filter(|heap| heap.desc.kind == VIEWS_KIND) + .filter_map(|heap| heap.host.get()?.as_ref().map(|host| (heap, host))) + .flat_map(|(heap, host)| slots.iter().filter(|&&i| i < heap.desc.count).filter_map(|&i| host.unmade_placed(i))) + .collect() + }; + #[cfg(test)] + tests::while_making(slots); + for view in &placed { + let _ = host::placed_texture(view); + } let heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner()); for &(start, _, at) in heaps.iter() { // SAFETY: registered heaps are live (removed when dropped). @@ -788,7 +809,24 @@ static FUNCTIONS: Table<24> = { }; #[cfg(test)] -mod tests { +pub(crate) mod tests { + /// Work to run while `make_read` makes the textures of a read slot (the + /// slot), outside the heaps' lock. + pub(crate) static WHILE_MAKING: std::sync::Mutex> = std::sync::Mutex::new(None); + + /// The work [`WHILE_MAKING`] runs. + pub(crate) type Work = Box; + + pub(crate) fn while_making(slots: &[u32]) { + let mut hook = WHILE_MAKING.lock().unwrap_or_else(|e| e.into_inner()); + if hook.as_ref().is_some_and(|(slot, _)| slots.contains(slot)) + && let Some((_, work)) = hook.take() + { + drop(hook); + work(); + } + } + use super::*; use crate::object::{S_OK, slot}; diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index f2092e722f..cec52992a1 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -810,6 +810,15 @@ impl HostHeap { .collect() } + /// The view of slot `index` if it is a placed texture's left without a + /// host view (made when read). + pub(crate) fn unmade_placed(&self, index: u32) -> Option { + let key = *self.made.lock().unwrap_or_else(|e| e.into_inner()).get(index as usize)?; + let view = (key != 0).then(|| view_at(key as u32, (key >> 32) as u32)).flatten()?; + let kept = self.kept.lock().unwrap_or_else(|e| e.into_inner()).get(index as usize).is_some_and(Option::is_some); + (is_placed_texture(&view) && !kept).then_some(view) + } + /// A shader read slot `index` through the heap: the texture it views /// was used now. pub(crate) fn stamp_read(&self, index: u32) { @@ -1760,6 +1769,51 @@ mod tests { assert!(crate::resource::made_copy(texture).is_some(), "with a host texture again"); } + /// The textures of slots shaders read are made without the heaps' lock: + /// a title thread writing a view meanwhile is not held up by the make. + #[test] + fn views_written_while_read_slots_get_their_textures_do_not_wait() { + if host().is_none() { + return; // no host GPU here + } + let null = std::ptr::null(); + let heap_desc: [u32; 8] = [0, 1024, 1, 0, 0, 0, 0, 0]; + let mut heap = null; + let iid = crate::object::guid(0x8efb471d, 0x616c, 0x4f49, [0x90, 0xf7, 0x12, 0x7b, 0xb7, 0x63, 0xfa, 0x51]); + assert_eq!(crate::descriptor::create_heap(null, heap_desc.as_ptr().cast(), &iid, &mut heap), 0); + let title_heap = crate::descriptor::heap(heap); + let (read, written) = (900u32, 901u32); + // A 4x1 RGBA8 texture, linear, in memory of its own, and a 2D view. + let memory = vec![0u8; 1 << 16]; + let address = memory.as_ptr() as u64; + let words: [u32; 14] = [3, 0, 0, 0, 4, 0, 1, 1 | 1 << 16, 28, 1, 0, 0x100, 0, 0]; + let mut view = [0u32; 16]; + view[..6].copy_from_slice(&[28, 4, 0x1688, 0, 0, 1]); + (view[10], view[11]) = (address as u32, (address >> 32) as u32); + let slot = |i: u32| title_heap.start + u64::from(i) * 32; + crate::descriptor::create_placed_srv(null, &words, &view, slot(read)); + let host = title_heap.host().expect("a host view heap"); + assert!(!host.kept(read), "left null until read"); + let (done, waited) = std::sync::mpsc::channel(); + let at = slot(written); + *crate::descriptor::tests::WHILE_MAKING.lock().unwrap() = Some(( + read, + Box::new(move || { + std::thread::spawn(move || { + crate::descriptor::create_placed_srv(std::ptr::null(), &words, &view, at); + done.send(()).unwrap(); + }); + assert!( + waited.recv_timeout(std::time::Duration::from_secs(5)).is_ok(), + "a view written while a read slot's texture is made waits" + ); + }), + )); + crate::descriptor::make_read(&[read]); + assert!(crate::descriptor::tests::WHILE_MAKING.lock().unwrap().is_none(), "the make ran"); + assert!(host.kept(read), "made for the read"); + } + /// A heap sync makes the slots whose records the title changed as bytes /// (a copy of another slot's record, a record cleared) and passes the /// others by. From ed25c0e24ed5cc80d7db596ba3f6987989a73928 Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 09:54:28 +0100 Subject: [PATCH 60/83] GPU: a slot the title rewrites keeps no per-texture list of slots What was wrong: every slot the title rewrote updated a map from each host texture to the slots viewing it (for giving textures up), searching the texture's whole list to take the slot out. A texture viewed in thousands of slots made each rewrite cost ~25 us; the title rewrites ~62,000 slots a frame (it copies per-draw descriptor tables into its heap), so heap syncs took 0.6-2.9 s a frame and held the heaps' lock that title threads writing views wait on (run evict3: 62,208 stale slots a frame at 25.7 us each, 16 us rising to 34 us as the lists grew). What changed: no map; giving textures up walks the heap's slots once per pass that gives any up. Evidence: tests `descriptor::host::tests::a_slot_viewing_a_texture_given_up_is_made_again_when_read` and the eviction tests; the crate's tests twice with 8 threads. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor/host.rs | 36 ++++++++--------------- 1 file changed, 13 insertions(+), 23 deletions(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index cec52992a1..6eb00422ea 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -31,9 +31,6 @@ pub(crate) struct HostHeap { /// read there is a GPU page fault (the console reads stale memory). /// With it the view's own copy of title memory, if it has one. kept: Mutex>, - /// The slots each kept texture is viewed in (by its raw pointer), for - /// textures given up ([`HostHeap::evict`]). - by_texture: Mutex>>, /// Where the search for free dynamic slots starts, and which are taken /// (by lists not yet reset). next: Mutex<(u32, Vec)>, @@ -197,7 +194,6 @@ impl HostHeap { sampler, made: Mutex::new(vec![0; count as usize]), kept: Mutex::new(vec![None; (count + extra) as usize]), - by_texture: Mutex::default(), next: Mutex::new((0, vec![false; extra as usize])), pairs: Mutex::new((count + extra, Vec::new())), pairs_end: match victory_shader::emit::NULL_BUFFER_VIEW { @@ -521,23 +517,6 @@ impl HostHeap { let mut kept = self.kept.lock().unwrap_or_else(|e| e.into_inner()); if let Some(slot) = kept.get_mut(index as usize) { let old = std::mem::replace(slot, resource); - // Textures (views without a copy of title memory) by slot. - let raw = |k: &Kept| k.as_ref().filter(|k| k.1.is_none()).map(|k| windows::core::Interface::as_raw(&k.0) as usize); - let (was, now) = (raw(&old), raw(slot)); - if was != now { - let mut by = self.by_texture.lock().unwrap_or_else(|e| e.into_inner()); - if let Some(was) = was - && let Some(slots) = by.get_mut(&was) - { - slots.retain(|&i| i != index); - if slots.is_empty() { - by.remove(&was); - } - } - if let Some(now) = now { - by.entry(now).or_default().push(index); - } - } #[cfg(feature = "diagnostics")] if let Some((old, _)) = &old && !self.sampler @@ -779,10 +758,21 @@ impl HostHeap { /// record stays noted so heap syncs leave it, and the next draw reading /// it through a table or shader reading it through the heap (its read /// mark, cleared) makes it again. + /// The slots are found by a walk of the heap, once per pass that gives + /// textures up: a map of each texture's slots, kept at every slot the + /// title rewrote, cost ~25 us a slot (a texture viewed in thousands of + /// slots had its list searched each time; 62,000 slots a frame, run + /// evict3). pub(crate) fn evict(&self, textures: &std::collections::HashSet) { let slots: Vec = { - let by = self.by_texture.lock().unwrap_or_else(|e| e.into_inner()); - textures.iter().filter_map(|t| by.get(t)).flatten().copied().collect() + let kept = self.kept.lock().unwrap_or_else(|e| e.into_inner()); + (0..kept.len() as u32) + .filter(|&i| { + kept[i as usize] + .as_ref() + .is_some_and(|k| k.1.is_none() && textures.contains(&(windows::core::Interface::as_raw(&k.0) as usize))) + }) + .collect() }; let made = self.made.lock().unwrap_or_else(|e| e.into_inner()); for index in slots { From c6e95001b05c54e0befb2bc058f6324786ae3b72 Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 09:54:28 +0100 Subject: [PATCH 61/83] GPU: a texture's refresh asks its tracker's clean bit before taking its pages What was wrong: textures the heaps view are refreshed at every submission where the title used them lately: 123,000 refreshes a frame (run evict3), each taking its tracker's lock to find, almost always, nothing changed. What changed: a refresh of a tracked texture first reads the tracker's dense clean bit, which needs no lock, and stops there if it is clean. Evidence: the upload tests (`draw::tests::a_texture_is_uploaded_once_per_submission_and_only_when_written`, `a_texture_owning_its_pages_is_uploaded_on_any_write`, `a_write_into_one_mip_uploads_that_mip_alone`); the crate's tests twice with 8 threads. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/texture.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 48bd6886b7..6ea712a4a9 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -464,6 +464,11 @@ impl Staging { let mut last = self.last.lock().unwrap_or_else(|e| e.into_inner()); let last = &mut *last; if let Some(t) = &self.tracked { + // Most refreshes find nothing: the tracker's dense bit says so + // without its lock (123,000 refreshes a frame, run evict3). + if t.clean() { + return (0, None); + } let ranges = t.take(start, start + size); if ranges.is_empty() { return (0, None); From 42ea09f769b40d5ca887a8dfebd2a73f46ae096c Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 10:17:37 +0100 Subject: [PATCH 62/83] GPU: what a view needs is made before its slot's lock is taken What was wrong: making a heap slot's view held the heap's slot lock throughout, including making the texture it views (on first use) or the host copy of the buffer memory it views: title threads binding views for draws and writing views waited on that lock (119 of 307 samples of title threads in our code, run evict5). What changed: a slot whose view is unchanged is answered under the lock as before. One to make again releases the lock, makes what the view needs without it, takes it again and, if the slot still holds the record it prepared for, makes the view (cheap now); if the title wrote another record there meanwhile, that record is made instead. Evidence: tests `descriptor::host::tests::views_bound_while_another_slot_gets_its_texture_do_not_wait` (a thread binds a view while another slot's texture is made, bounded wait) and `a_slot_rewritten_while_its_view_is_prepared_views_the_new_record` (the title writes another record into the slot during the prepare; the slot views the new record's texture); the crate's tests three times with 8 threads. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor/host.rs | 153 ++++++++++++++++++++-- 1 file changed, 145 insertions(+), 8 deletions(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 6eb00422ea..15249f4164 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -699,16 +699,37 @@ impl HostHeap { && is_texture(&view) && self.kept.lock().unwrap_or_else(|e| e.into_inner())[index as usize].is_none() }; - if made[index as usize] != key || lazy() { + if made[index as usize] == key && !lazy() { + return Some(view); + } + // Shaders index the heap itself (`crate::bindless`): buffer views + // are made when written. + // shortcut: views of textures the title placed itself are made + // when a draw reads them through a table: a host texture (and a + // staging copy) for each of the ~20,000 the title has views of + // ran the host out of memory (run b2). + let later = !for_draw && is_placed_texture(&view); + if !later { + // What the view needs (the texture it views, the copy of the + // memory) is made without the slot lock, which title threads + // binding and writing views wait on (run evict5). + drop(made); + prepare(&view); + made = self.made.lock().unwrap_or_else(|e| e.into_inner()); + // The title may have written another record there meanwhile (and + // another thread made it): that one is the slot's. + // SAFETY: as above. + if unsafe { (handle as *const [u32; 3]).read_unaligned() } != [tag, i, generation] { + drop(made); + return self.mirror(index, handle, for_draw); + } + if made[index as usize] == key && !lazy() { + return Some(view); + } + } + { self.set_stride(index, Some(&view)); self.note_address(index, Some(&view)); - // Shaders index the heap itself (`crate::bindless`): buffer views - // are made when written. - // shortcut: views of textures the title placed itself are made - // when a draw reads them through a table: a host texture (and a - // staging copy) for each of the ~20,000 the title has views of - // ran the host out of memory (run b2). - let later = !for_draw && is_placed_texture(&view); if later { // Made once a shader reads it (`crate::shadow::take_reads`). crate::shadow::forget_read(index); @@ -1479,6 +1500,25 @@ fn is_placed_texture(view: &View) -> bool { matches!(view, View::Placed(_, resource, _) if resource[0] != 1) } +/// Makes what a host view of `view` needs, if it is not made yet: the +/// texture it views (made on first use) or the host copy of the buffer +/// memory it views. The slot's view is then quick to make. +fn prepare(view: &View) { + #[cfg(test)] + tests::while_preparing(); + match view { + View::Placed(..) if is_placed_texture(view) => { + let _ = placed_texture(view); + } + View::Shader(r, _) | View::Unordered(r, _, _) if crate::resource::texture_memory(*r as crate::object::This).is_some() => { + let _ = crate::resource::host_resource(*r as crate::object::This); + } + _ => { + let _ = view_copy(view); + } + } +} + /// Whether `view` is a shader view of a texture (one placed in memory, or a /// resource object's): such a slot left null is made when read. fn is_texture(view: &View) -> bool { @@ -1759,6 +1799,103 @@ mod tests { assert!(crate::resource::made_copy(texture).is_some(), "with a host texture again"); } + /// Work to run while a view's texture is prepared, once (tests). + pub(crate) static WHILE_PREPARING: std::sync::Mutex> = std::sync::Mutex::new(None); + + pub(crate) fn while_preparing() { + let work = WHILE_PREPARING.lock().unwrap_or_else(|e| e.into_inner()).take(); + if let Some(work) = work { + work(); + } + } + + /// A record the title writes into a slot while another thread prepares + /// the slot's old record is the one the slot ends up viewing. + #[test] + fn a_slot_rewritten_while_its_view_is_prepared_views_the_new_record() { + if host().is_none() { + return; // no host GPU here + } + let null = std::ptr::null(); + let heap_desc: [u32; 8] = [0, 1024, 1, 0, 0, 0, 0, 0]; + let mut heap = null; + let iid = crate::object::guid(0x8efb471d, 0x616c, 0x4f49, [0x90, 0xf7, 0x12, 0x7b, 0xb7, 0x63, 0xfa, 0x51]); + assert_eq!(crate::descriptor::create_heap(null, heap_desc.as_ptr().cast(), &iid, &mut heap), 0); + let title_heap = crate::descriptor::heap(heap); + let s = 960u32; + let at = title_heap.start + u64::from(s) * 32; + let memory = vec![0u8; 1 << 17]; + let words: [u32; 14] = [3, 0, 0, 0, 4, 0, 1, 1 | 1 << 16, 28, 1, 0, 0x100, 0, 0]; + let view_of = |address: u64| { + let mut view = [0u32; 16]; + view[..6].copy_from_slice(&[28, 4, 0x1688, 0, 0, 1]); + (view[10], view[11]) = (address as u32, (address >> 32) as u32); + view + }; + let (first, second) = (memory.as_ptr() as u64, memory.as_ptr() as u64 + (1 << 16)); + crate::descriptor::create_placed_srv(null, &words, &view_of(first), at); + let host = title_heap.host().expect("a host view heap"); + let (done, waited) = std::sync::mpsc::channel(); + let second_view = view_of(second); + *WHILE_PREPARING.lock().unwrap() = Some(Box::new(move || { + // The title writes the other record into the slot meanwhile. + std::thread::spawn(move || { + crate::descriptor::create_placed_srv(std::ptr::null(), &words, &second_view, at); + done.send(()).unwrap(); + }); + assert!(waited.recv_timeout(std::time::Duration::from_secs(5)).is_ok(), "the write waits"); + })); + // A draw reads the slot: its first record is prepared. + assert!(host.mirror(s, at, true).is_some()); + let second_texture = crate::resource::texture_at(second, &words).expect("its resource"); + let raw = windows::core::Interface::as_raw(&crate::resource::made_copy(second_texture).expect("made").texture) as usize; + assert_eq!(host.textures_at(&[s]), [raw], "the slot views the record written last"); + } + + /// What a view needs is made without the slot lock: another thread + /// binding a view of the same heap meanwhile is not held up. + #[test] + fn views_bound_while_another_slot_gets_its_texture_do_not_wait() { + if host().is_none() { + return; // no host GPU here + } + let null = std::ptr::null(); + let heap_desc: [u32; 8] = [0, 1024, 1, 0, 0, 0, 0, 0]; + let mut heap = null; + let iid = crate::object::guid(0x8efb471d, 0x616c, 0x4f49, [0x90, 0xf7, 0x12, 0x7b, 0xb7, 0x63, 0xfa, 0x51]); + assert_eq!(crate::descriptor::create_heap(null, heap_desc.as_ptr().cast(), &iid, &mut heap), 0); + let title_heap = crate::descriptor::heap(heap); + let (first, second) = (950u32, 951u32); + let memory = vec![0u8; 1 << 17]; + let words: [u32; 14] = [3, 0, 0, 0, 4, 0, 1, 1 | 1 << 16, 28, 1, 0, 0x100, 0, 0]; + let slot = |i: u32| title_heap.start + u64::from(i) * 32; + for (i, at) in [(first, 0u64), (second, 1 << 16)] { + let address = memory.as_ptr() as u64 + at; + let mut view = [0u32; 16]; + view[..6].copy_from_slice(&[28, 4, 0x1688, 0, 0, 1]); + (view[10], view[11]) = (address as u32, (address >> 32) as u32); + crate::descriptor::create_placed_srv(null, &words, &view, slot(i)); + } + let host = title_heap.host().expect("a host view heap"); + let heap_at = title_heap.start; + let heap = heap as usize; + let (done, waited) = std::sync::mpsc::channel(); + *WHILE_PREPARING.lock().unwrap() = Some(Box::new(move || { + std::thread::spawn(move || { + let h = crate::descriptor::heap(heap as crate::object::This); + h.host().unwrap().mirror(second, heap_at + u64::from(second) * 32, true); + done.send(()).unwrap(); + }); + assert!( + waited.recv_timeout(std::time::Duration::from_secs(5)).is_ok(), + "a view bound while another slot's texture is made waits" + ); + })); + assert!(host.mirror(first, slot(first), true).is_some()); + assert!(WHILE_PREPARING.lock().unwrap().is_none(), "the prepare ran"); + assert!(host.kept(first) && host.kept(second), "both made"); + } + /// The textures of slots shaders read are made without the heaps' lock: /// a title thread writing a view meanwhile is not held up by the make. #[test] From 56f75f8583061826fd7594e4e06f442bc0718f48 Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 10:17:37 +0100 Subject: [PATCH 63/83] GPU: textures are brought up outside the heaps' locks, several at a time What was wrong: at each submission the textures to bring up were read from title memory, detiled into staging buffers and copied one after the other on the submitting thread, while the heaps' view registry stayed locked: in a new shot that was about a third of the submitting thread (reading memory 19 %, making staging buffers 10 %, detiling 6 %, run evict5), frames grew 6-10 ms per MB uploaded, and title threads setting views waited on the lock throughout. What changed: what to bring up is collected under the heaps' locks, then refreshed without them on up to four threads (a quarter of the CPUs), those whose trackers are clean skipped, then recorded. Staging buffers come in powers of two (at least 64 KiB), so a buffer serves other sizes, and are made without the pool's lock. The tracker still decides the bytes: its pages are taken (and guarded) before they are read, so a title write during the read or detile marks them again and the next refresh brings them up (`watch::tests::writes_mark_every_tracker_of_their_page`). Evidence: tests `host::tests::heap_textures_brought_up_together_each_get_their_upload` (six textures refreshed side by side, each uploaded once, none again when unchanged) and the upload tests; the crate's tests three times with 8 threads. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/bindless.rs | 42 ++++++++----- crates/victory-gpu/src/host.rs | 36 +++++++++++ crates/victory-gpu/src/texture.rs | 97 +++++++++++++++++++----------- 3 files changed, 125 insertions(+), 50 deletions(-) diff --git a/crates/victory-gpu/src/bindless.rs b/crates/victory-gpu/src/bindless.rs index b7a708a1fe..046f0b1879 100644 --- a/crates/victory-gpu/src/bindless.rs +++ b/crates/victory-gpu/src/bindless.rs @@ -200,7 +200,6 @@ pub(crate) fn uploads( textures: &[(Arc, Arc)], ) -> Option { static LIST: Mutex = Mutex::new(Holder(None)); - const SHADER_RESOURCE: u32 = 0x40 | 0x80; let mut guard = LIST.lock().unwrap_or_else(|e| e.into_inner()); crate::texture::recycle(); match &guard.0 { @@ -214,22 +213,21 @@ pub(crate) fn uploads( } } let list = guard.0.as_ref()?; - let mut recorded = false; + // What to bring up: the textures lists read through tables, and those + // the heaps view that shaders read lately. Collected under the heaps' + // locks and brought up without them, several at a time: reading title + // memory, detiling and making staging buffers took half the submitting + // thread in a new shot, and title threads setting views waited on the + // lock meanwhile (run evict5). + let mut work: Vec<(Arc, Arc)> = Vec::new(); let mut staged = std::collections::HashSet::new(); for (staging, copy) in textures { - if staged.insert(Arc::as_ptr(staging)) - && let Some(upload) = staging.refresh() - { - crate::texture::record_upload(list, copy, staging, &upload); - recorded = true; - #[cfg(feature = "diagnostics")] - UPLOADED.fetch_add(1, Relaxed); + if staged.insert(Arc::as_ptr(staging)) { + work.push((staging.clone(), copy.clone())); } } let mut done = std::collections::HashSet::new(); for viewed in heaps { - // Held while uploading: the title releasing a texture (and its - // memory) waits in `forget`. let inner = viewed.inner.lock().unwrap_or_else(|e| e.into_inner()); for &r in inner.textures.keys() { if !done.insert(r) { @@ -250,14 +248,26 @@ pub(crate) fn uploads( if !texture.used_recently() { continue; } - if crate::texture::upload_changed(list, r as This, &texture.texture) { - crate::list::ensure_state(list, r as This, SHADER_RESOURCE); - recorded = true; - #[cfg(feature = "diagnostics")] - UPLOADED.fetch_add(1, Relaxed); + // Its contents are the host's since a host copy wrote it. + if texture.host_written.load(Relaxed) { + continue; + } + if let Some(staging) = crate::texture::staging(r as This, &texture.texture) + && staged.insert(Arc::as_ptr(&staging)) + { + work.push((staging, texture)); } } } + let mut recorded = false; + for ((staging, copy), upload) in work.iter().zip(crate::texture::refresh_all(&work)) { + if let Some(upload) = upload { + crate::texture::record_upload(list, copy, staging, &upload); + recorded = true; + #[cfg(feature = "diagnostics")] + UPLOADED.fetch_add(1, Relaxed); + } + } list.close(); // A list recording nothing is not run (its reset next time is fine). recorded.then_some(Uploads(guard)) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index f64a2a4663..50021d1c32 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -542,6 +542,42 @@ mod tests { assert_eq!(crate::texture::uploads(object), 1, "read in the last pass: brought up"); } + /// Heap textures brought up in one submission are refreshed side by + /// side, each into its own staging and its own upload. + #[test] + fn heap_textures_brought_up_together_each_get_their_upload() { + let Some(host) = host() else { return }; + let iid = crate::object::guid(0x696442be, 0xa72e, 0x4059, [0xbc, 0x79, 0x5b, 0x5c, 0x98, 0x04, 0x0f, 0xad]); + let pool = crate::watch::tests::pool(6); + let viewed = std::sync::Arc::new(crate::bindless::Viewed::default()); + let objects: Vec = (0..6u32) + .map(|k| { + // RGBA8 128x128 (one page each), linear, each its own bytes. + let address = (pool + k as usize * crate::watch::PAGE) as u64; + // SAFETY: the texture's own page of the pool. + unsafe { std::ptr::write_bytes(address as *mut u8, 0x10 * k as u8, crate::watch::PAGE) }; + let words: [u32; 14] = [3, 0, 0, 0, 128, 0, 128, 1 | 1 << 16, 28, 1, 0, 0x100, 0, 0]; + let mut object = std::ptr::null(); + assert_eq!(crate::resource::create_at_address(std::ptr::null(), address, words.as_ptr().cast(), 0, std::ptr::null(), &iid, &mut object), 0); + crate::resource::host_copy(object).expect("a host texture").stamp(); + let mut desc = [0u32; 10]; + desc[..6].copy_from_slice(&[28, 4, 0x1688, 0, 0, 1]); + viewed.set(k, Some(&crate::descriptor::View::Shader(object as usize, Some(desc))), true); + object + }) + .collect(); + // No submission uploads meanwhile. + let _one = host.submitted.lock().unwrap_or_else(|e| e.into_inner()); + let _ = crate::bindless::uploads(std::slice::from_ref(&viewed), &[]); + for &object in &objects { + assert_eq!(crate::texture::uploads(object), 1, "each brought up once"); + } + let _ = crate::bindless::uploads(std::slice::from_ref(&viewed), &[]); + for &object in &objects { + assert_eq!(crate::texture::uploads(object), 1, "unchanged: not again"); + } + } + #[test] fn list_scratch_grows_to_fit_and_reuses_fenced_chunks() { let Some(host) = host() else { return }; diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 6ea712a4a9..1f35306832 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -132,22 +132,27 @@ pub(crate) fn recycle() { } /// A free staging buffer of `size` bytes, or a new one. +/// Sizes are taken in powers of two (at least 64 KiB), so a buffer serves +/// textures of other sizes too: a new shot's textures came in new sizes and +/// made buffers 10 % of the submitting thread (run evict5). fn staging_buffer(size: u64) -> Option<(ID3D12Resource, *mut u8)> { - let mut b = BUFFERS.lock().unwrap_or_else(|e| e.into_inner()); - let e = match b.free.iter().position(|e| e.0 == size) { - Some(i) => { - let e = b.free.remove(i)?; - b.free_bytes -= size; - e - } + let class = size.max(1 << 16).next_power_of_two(); + let taken = { + let mut b = BUFFERS.lock().unwrap_or_else(|e| e.into_inner()); + let i = b.free.iter().position(|e| e.0 == class); + i.and_then(|i| b.free.remove(i)).inspect(|_| b.free_bytes -= class) + }; + // Made without the pool's lock (refreshes run on several threads). + let e = match taken { + Some(e) => e, None => { - let (buffer, data) = host()?.upload_buffer(size)?; + let (buffer, data) = host()?.upload_buffer(class)?; crate::host::name(&buffer, || "texture staging".into()); - (size, buffer, data as usize) + (class, buffer, data as usize) } }; let made = (e.1.clone(), e.2 as *mut u8); - b.used.push(e); + BUFFERS.lock().unwrap_or_else(|e| e.into_inner()).used.push(e); Some(made) } @@ -353,29 +358,6 @@ pub(crate) fn copied(resource: This) -> u64 { staging.map_or(0, |s| s.copied.load(std::sync::atomic::Ordering::Relaxed)) } -/// For textures shaders reach through the heap itself, at submission -/// (`crate::bindless::uploads`): brings the staging buffer up to date and -/// records its copy into `list` only if the memory changed since (or was -/// never uploaded). True if it recorded; the texture is then in the copy -/// destination state. -pub(crate) fn upload_changed(list: &HostList, resource: This, texture: &ID3D12Resource) -> bool { - if is_host_written(resource) { - return false; - } - let Some(staging) = staging(resource, texture) else { - return false; - }; - let Some((buffer, subresources)) = staging.refresh() else { - return false; - }; - const COPY_DEST: u32 = 0x400; - crate::list::ensure_state(list, resource, COPY_DEST); - copies(list, texture, &staging, &buffer, &subresources, || format!("{resource:?}")); - list.keep(&buffer); - staging.uploads.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - staging.copied.fetch_add(subresources.len() as u64, std::sync::atomic::Ordering::Relaxed); - true -} /// Records the copy of `subresources` of `buffer` (laid out as `staging` /// says) into `texture` (in the copy destination state); `name` names it @@ -441,7 +423,54 @@ fn copies( } } +/// What a refresh gives: a staging buffer and the subresources detiled +/// into it. +pub(crate) type Upload = (ID3D12Resource, Vec); + +/// [`Staging::refresh`] of each of `work`, those whose memory may have +/// changed on several threads at once (reading title memory and detiling +/// cost ~6 ms of frame a MB on one thread in a new shot, run evict5). +pub(crate) fn refresh_all(work: &[(Arc, Arc)]) -> Vec> { + use std::sync::atomic::{AtomicUsize, Ordering::Relaxed}; + let mut out: Vec> = vec![None; work.len()]; + // Most find nothing changed (their trackers' clean bits say so): those + // are not handed to threads. + let changed: Vec = (0..work.len()).filter(|&i| work[i].0.maybe_changed()).collect(); + // A quarter of the CPUs at most, four at most: the title's own threads + // need the rest. + let threads = std::thread::available_parallelism().map_or(4, |n| n.get() / 4).clamp(1, 4).min(changed.len()); + if threads < 2 { + for &i in &changed { + out[i] = work[i].0.refresh(); + } + return out; + } + let next = AtomicUsize::new(0); + let results: Vec>> = changed.iter().map(|_| Mutex::new(None)).collect(); + std::thread::scope(|scope| { + for _ in 0..threads { + scope.spawn(|| { + loop { + let k = next.fetch_add(1, Relaxed); + let Some(&i) = changed.get(k) else { break }; + *results[k].lock().unwrap_or_else(|e| e.into_inner()) = work[i].0.refresh(); + } + }); + } + }); + for (k, r) in results.into_iter().enumerate() { + out[changed[k]] = r.into_inner().unwrap_or_else(|e| e.into_inner()); + } + out +} + impl Staging { + /// Whether its memory may have changed since it was last detiled (an + /// untracked texture always may). + pub(crate) fn maybe_changed(&self) -> bool { + self.tracked.as_ref().is_none_or(|t| !t.clean()) + } + /// A staging buffer with the texture memory detiled into it if it /// changed since the last time (and is mapped at all), and the /// subresources that changed (only those are detiled and to be copied). @@ -637,7 +666,7 @@ pub(crate) fn committed(at: *const u8, len: usize) -> bool { /// The staging state of a title texture's host texture, made on first use /// (one for all title textures of its memory). -fn staging(resource: This, texture: &ID3D12Resource) -> Option> { +pub(crate) fn staging(resource: This, texture: &ID3D12Resource) -> Option> { let copy = crate::resource::host_copy(resource)?; let mut held = copy.staging.lock().unwrap_or_else(|e| e.into_inner()); if let Some(s) = held.as_ref() { From ec9e750eb75b43f5f202d6929321d5cc7c5dc87c Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 10:31:15 +0100 Subject: [PATCH 64/83] GPU: what a submission that missed title memory withheld leaves the copies at once What lists using title memory write while the frame withholds stays in the host copies until the frame's end: through the page table, through root views (byte for byte) and through marked views. When a list of the submission read or wrote memory with no copy, those results are garbage computed from zeros (BVH builder nodes: +-inf bounds, 0xffffffff, rising u16 pairs), and later submissions of the same frame read them from the copies: in run shards20 the meshlet culling read such bytes in its per-batch meshlet buffers (stale copies with no title-side event after their take; 95.59 % of the batches walked equal to title memory). Now what such a submission withheld counts as changed in every buffer copy holding it right after it completes (`drop_withheld`, which takes the place of `drop_at_frame_end`), so the next submission's refresh takes it from title memory again. What submissions that missed nothing withheld keeps the frame-end retake. Run shards21 (29210929 + the page-table part alone + branch-only diagnostics, same listing as shards20): one list per world frame wrote through the page table, every one missed and was retaken at once (34-19,446 pages); stale copies written through the page table are gone, 98.12 % of 13,509 batches walked equal title memory. Every sampled stale batch left was last written through a declared, unmarked view with no retake after it (the builder's root UAVs, which the page-table path leaves to the byte-for-byte path), hence the root and marked views here too. Test: memory::tests::a_submission_that_missed_leaves_the_copies_at_once (a write through the page table beside a miss; fails before the change: the next submission reads the write instead of title memory's bytes). Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/host.rs | 6 +- crates/victory-gpu/src/memory.rs | 153 ++++++++++++++++++++++++++++--- crates/victory-gpu/src/shadow.rs | 6 +- 3 files changed, 146 insertions(+), 19 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 50021d1c32..01297898e5 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -1273,9 +1273,7 @@ impl Host { .iter() .map(|list| list.deferred().missed.iter().any(|check| check())) .collect(); - if missed.contains(&true) { - crate::memory::note_missed(); - } + crate::memory::note_submission(missed.contains(&true)); let withholding = crate::memory::withholding(); for (list, &missed) in runs.iter().zip(&missed) { let deferred = list.deferred(); @@ -1314,7 +1312,7 @@ impl Host { } else { shadow.keep_writes(address, len); crate::memory::note_withheld(len as u64); - crate::memory::drop_at_frame_end(address, len); + crate::memory::drop_withheld(address, len); } } for list in runs { diff --git a/crates/victory-gpu/src/memory.rs b/crates/victory-gpu/src/memory.rs index 47fcaa148f..c2ad88da9f 100644 --- a/crates/victory-gpu/src/memory.rs +++ b/crates/victory-gpu/src/memory.rs @@ -169,10 +169,18 @@ static FRAMES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new( static MISSED_IN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(MISS_NEVER); const MISS_NEVER: u64 = u64::MAX; -/// A list using title memory read or wrote memory with no copy. -pub(crate) fn note_missed() { +/// Whether a list using title memory in the submission being completed +/// read or wrote memory with no copy (completions run one at a time). +static SUBMISSION_MISSED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// A submission's lists ran: whether one using title memory read or wrote +/// memory with no copy. +pub(crate) fn note_submission(missed: bool) { use std::sync::atomic::Ordering::Relaxed; - MISSED_IN.store(FRAMES.load(Relaxed), Relaxed); + SUBMISSION_MISSED.store(missed, Relaxed); + if missed { + MISSED_IN.store(FRAMES.load(Relaxed), Relaxed); + } } /// Whether what lists using title memory wrote stays out of title memory @@ -197,10 +205,17 @@ fn withheld_in(frame: u64, missed: u64) -> bool { static DROPPED: Mutex> = Mutex::new(Vec::new()); /// Shaders wrote `[address, address + len)` of title memory in host copies -/// and the frame withheld it: at the frame's end the copies take title -/// memory's bytes again ([`retake_dropped`]). -pub(crate) fn drop_at_frame_end(address: usize, len: usize) { - DROPPED.lock().unwrap_or_else(|e| e.into_inner()).push((address, len)); +/// and the submission withheld it: the copies take title memory's bytes +/// again at their next refresh, from right after the submission if a list +/// of it missed (its results would feed the frame's later submissions: +/// garbage BVH nodes over meshlet buffers, run shards20), else from the +/// frame's end ([`retake_dropped`]). +pub(crate) fn drop_withheld(address: usize, len: usize) { + if SUBMISSION_MISSED.load(std::sync::atomic::Ordering::Relaxed) { + crate::watch::retake(address, len); + } else { + DROPPED.lock().unwrap_or_else(|e| e.into_inner()).push((address, len)); + } } /// At a frame's end: what the frame withheld leaves the host copies, so @@ -500,7 +515,7 @@ pub(crate) fn bind(list: &HostList, key: usize) -> Option { let withheld = if pages + regions > 0 || withholding() { writes.len() as u64 } else { 0 }; if withheld > 0 { for &(_, at) in &writes { - drop_at_frame_end(at as usize, 1 << 16); + drop_withheld(at as usize, 1 << 16); } } let mut written = 0; @@ -620,7 +635,7 @@ void main(uint3 id : SV_DispatchThreadID) { } "#; - fn pipeline() -> ( + fn pipeline(source: &str) -> ( windows::Win32::Graphics::Direct3D12::ID3D12RootSignature, windows::Win32::Graphics::Direct3D12::ID3D12PipelineState, ) { @@ -633,8 +648,8 @@ void main(uint3 id : SV_DispatchThreadID) { // SAFETY: the source and names outlive the call; the errors are text. unsafe { let made = D3DCompile( - SOURCE.as_ptr().cast(), - SOURCE.len(), + source.as_ptr().cast(), + source.len(), s!("memory"), None, None, @@ -688,7 +703,7 @@ void main(uint3 id : SV_DispatchThreadID) { let (Some(host), Some(views)) = (crate::host::host(), heap()) else { return; // no host GPU here }; - let (root, pso) = pipeline(); + let (root, pso) = pipeline(SOURCE); let (out, at) = host.shared_buffer(256).unwrap(); // SAFETY: a live buffer. let out_gpu = unsafe { out.GetGPUVirtualAddress() }; @@ -767,4 +782,118 @@ void main(uint3 id : SV_DispatchThreadID) { drop(copy); } } + + /// Writes `value` at (`lo`, `hi`) through the page table, marking its + /// page as translated shaders do, and with `missing_hi` non-zero reads + /// (`missing_lo`, `missing_hi`), marking it if no copy holds it. + const WRITE: &str = r#" +#define RS "DescriptorTable(UAV(u0, numDescriptors=unbounded)), SRV(t0, space=2), UAV(u0, space=2), RootConstants(num32BitConstants=5, b0)" +RWByteAddressBuffer views[] : register(u0); +ByteAddressBuffer table : register(t0, space2); +RWByteAddressBuffer dirty : register(u0, space2); +cbuffer c : register(b0) { uint lo; uint hi; uint value; uint missing_lo; uint missing_hi; } +void access(uint a, uint h, bool write) { + bool inside = h < 256; + uint l1 = inside ? (h << 4 | a >> 28) : 0; + uint block = inside ? table.Load(l1 * 4) : 0; + uint entry = block << 12 | (a >> 16 & 0xFFF); + uint2 e = table.Load2((4096 + 2 * entry) * 4); + bool miss = e.x == table.Load(4096 * 4); + uint n = miss && block == 0 ? l1 : entry; + if (write || miss) { + dirty.InterlockedOr(n >> 5 << 2, 1u << (n & 31)); + } + if (write && !miss) { + views[NonUniformResourceIndex(e.x + 1)].Store(a - e.y, value); + } +} +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void main() { + access(lo, hi, true); + if (missing_hi != 0) { + access(missing_lo, missing_hi, false); + } +} +"#; + + /// What a submission that missed memory wrote through the page table + /// leaves the host copies right after it, so the next submission reads + /// title memory's bytes (run shards20: garbage BVH nodes over meshlet + /// buffers until the frame's end); one that missed nothing leaves its + /// writes in the copies. + #[test] + fn a_submission_that_missed_leaves_the_copies_at_once() { + use crate::watch::PAGE; + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc}; + let (Some(host), Some(views)) = (crate::host::host(), heap()) else { + return; // no host GPU here + }; + let ((write_root, writer), (read_root, reader)) = (pipeline(WRITE), pipeline(SOURCE)); + let (out, out_cpu) = host.shared_buffer(256).unwrap(); + // SAFETY: a live buffer. + let out_gpu = unsafe { out.GetGPUVirtualAddress() }; + // A page of title memory below 2^40, write-watched as the pools. + let p = (0..256u64) + .map(|k| 0x50_0000_0000 + (k << 28)) + // SAFETY: a fresh allocation where nothing is mapped, or none. + .map(|hint| unsafe { VirtualAlloc(hint as *const _, PAGE, MEM_RESERVE | MEM_COMMIT | crate::watch::tests::MEM_WRITE_WATCH, PAGE_READWRITE) } as usize) + .find(|&p| p != 0) + .expect("memory below 2^40"); + let at = p + 16; + // SAFETY: our pool, not guarded yet. + unsafe { (at as *mut u32).write_volatile(0x11) }; + crate::shadow::register(p, p as u64, PAGE as u64); + let copy = crate::shadow::find(p as u64, PAGE as u64).unwrap(); + let list = host.new_list().unwrap(); + // One submission of one dispatch; the list is open again after it. + let submit = |root: &windows::Win32::Graphics::Direct3D12::ID3D12RootSignature, + pso: &windows::Win32::Graphics::Direct3D12::ID3D12PipelineState, + uav: Option, + constants: &[u32]| { + let map = bind(&list, OURS).expect("a page table"); + // SAFETY: an open list, live objects of ours. + unsafe { + list.list.SetDescriptorHeaps(&[Some(views.heap.clone())]); + list.list.SetComputeRootSignature(root); + list.list.SetComputeRootDescriptorTable(0, views.gpu(0)); + list.list.SetComputeRootShaderResourceView(1, map.table); + list.list.SetComputeRootUnorderedAccessView(2, uav.unwrap_or(map.dirty)); + list.list.SetComputeRoot32BitConstants(3, constants.len() as u32, constants.as_ptr().cast(), 0); + list.list.SetPipelineState(pso); + list.list.Dispatch(1, 1, 1); + } + list.close(); + host.execute(&[&list]); + list.reset(); + }; + let write = |value: u32, miss: bool| { + // Memory no copy holds, in a 256 MiB region with no block. + let missing: u64 = if miss { 0xff_f000_0000 } else { 0 }; + let constants = [at as u32, (at >> 32) as u32, value, missing as u32, (missing >> 32) as u32]; + submit(&write_root, &writer, None, &constants); + }; + let read = || -> u32 { + submit(&read_root, &reader, Some(out_gpu), &[at as u32, (at >> 32) as u32, 0]); + // SAFETY: the mapped output, the GPU done with it. + unsafe { out_cpu.cast::().read_volatile() } + }; + // SAFETY: our pool. + let title = || unsafe { (at as *const u32).read_volatile() }; + write(0x33, true); + // Another test's submission may have refreshed the copy already. + let held = copy.read_host(at as u64, 1)[0]; + assert!(!copy.clean() || held == 0x11, "the written page counts as changed at once"); + assert_eq!(title(), 0x11, "nothing went back"); + assert_eq!(read(), 0x11, "the next submission reads title memory's bytes"); + // Unless another test ends a frame meanwhile (its retake is right). + let frame = FRAMES.load(std::sync::atomic::Ordering::Relaxed); + write(0x44, false); + let kept = read(); + if FRAMES.load(std::sync::atomic::Ordering::Relaxed) == frame { + assert_eq!(kept, 0x44, "a submission that missed nothing keeps its writes"); + } + crate::shadow::unregister(p, p as u64); + drop(copy); + } } diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index eb862afe74..8d57a2864f 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -887,11 +887,11 @@ pub(crate) fn copy_back_marks(withheld: &[(Arc, usize, usize)], memory_w (copy, page) }) }; - // Held back: dropped from the copies at the frame's end. + // Held back: dropped from the copies (`crate::memory::drop_withheld`). if !held.is_empty() { let m = marks(); for (_, page) in held.into_iter().filter_map(|n| page_of(&m, n)) { - crate::memory::drop_at_frame_end(page, PAGE); + crate::memory::drop_withheld(page, PAGE); } } if marked.is_empty() { @@ -1541,7 +1541,7 @@ pub(crate) mod tests { c.write_host(p as u64 + 16, &[0x22]); c.keep_writes(start as usize, n as usize); } - crate::memory::drop_at_frame_end(p + 16, 4); + crate::memory::drop_withheld(p + 16, 4); assert_eq!((byte(&outer), byte(&inner)), (0x22, 0x22), "frame N: the GPU's copies keep it"); crate::memory::log_frame(); for c in [&outer, &inner] { From 8ff791351662a2ba8675a899700b3d0193d3c775 Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 11:04:03 +0100 Subject: [PATCH 65/83] Shader: rectangles complete opposite their right angle, wherever it is A console rectangle list gives three corners per rectangle and the hardware adds the fourth opposite the right angle. The geometry shader that completes them on the host (and the CPU expansion used without it) took the right angle to be at v1, as the blits give it (top left, bottom left, bottom right). The tiled lighting's vertex shader (VS_TiledLighting, 3 vertices per tile: corner c = vertex % 3 at x + bit 1, y + bit 0) gives top left, bottom left, top right, the right angle at v0, so every lighting tile drew its upper-left half and the lower-right half of the tile above: tiles whose neighbour below was in another list lost their lower-right half and lit the one above, the right-triangle wedges along silhouettes and kerbs of runs shards22 (frames 1603, 1615, 1627; their depth is clean there). Now the right angle is the corner opposite the longest side (`emit::right_angle`, ties and NaN keep v1), the fourth corner is va + vb - vc and the second triangle (va, vb, v3), turning as the first for any three points; the CPU expansion takes the same rule from the first float element of two or more components. Tests: emit::rect::rule_tests::right_angles_are_found_in_any_order; emit::rect::tests::rectangles_get_their_fourth_corner draws the three orders (and three points on a line, which draw nothing) on hardware and WARP, and fails with the old rule; primitive::tests:: rectangles_complete_opposite_their_right_angle. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/primitive.rs | 58 ++++++-- crates/victory-shader/src/emit/mod.rs | 5 +- crates/victory-shader/src/emit/rect.rs | 179 ++++++++++++++++++------- 3 files changed, 179 insertions(+), 63 deletions(-) diff --git a/crates/victory-gpu/src/primitive.rs b/crates/victory-gpu/src/primitive.rs index fe1895cab1..a30b48a99e 100644 --- a/crates/victory-gpu/src/primitive.rs +++ b/crates/victory-gpu/src/primitive.rs @@ -1,9 +1,8 @@ //! Console primitive types the host lacks. A rectangle list gives three -//! corners per rectangle, the second the one between the other two, and -//! the hardware adds the fourth at `v0 + v2 - v1` (Grand Theft Auto VI's -//! full-screen rectangles come as top left, bottom left, bottom right); on -//! the host each rectangle becomes two triangles, with the fourth vertex -//! made from the other three on the CPU. +//! corners per rectangle, in any order, and the hardware adds the fourth +//! opposite the right angle (`victory_shader::emit::right_angle`); on the +//! host each rectangle becomes two triangles, with the fourth vertex made +//! from the other three on the CPU when no geometry shader does it. //! //! shortcut: the fourth vertex is computed from vertex inputs, not from //! vertex shader outputs as the hardware does; that is the same for vertex @@ -13,8 +12,11 @@ //! next one, which the layout allows). /// Expands `rects` rectangles of `stride`-byte vertices from `src` into six -/// vertices each in `dst`: `(v0, v1, v2)` and `(v0, v2, v3)`, so both -/// triangles turn the same way. `elements` are (byte offset, format). +/// vertices each in `dst`: `(v0, v1, v2)` and `(va, vb, v3)`, so both +/// triangles turn the same way, with the right angle `vc` picked from the +/// first float element of two or more components (taken as the position; +/// none: at `v1`), `va` before it, `vb` after it and `v3 = va + vb - vc`. +/// `elements` are (byte offset, format). pub(crate) fn expand_rects(src: &[u8], dst: &mut [u8], stride: usize, elements: &[(u32, u32)]) { if stride == 0 { return; @@ -27,11 +29,23 @@ pub(crate) fn expand_rects(src: &[u8], dst: &mut [u8], stride: usize, elements: .zip(dst.chunks_exact_mut(out_rect)) { let v = |i: usize| &rect[i * stride..(i + 1) * stride]; - for (slot, i) in [0, 1, 2, 0, 2].into_iter().enumerate() { + let right = elements + .iter() + .find_map(|&(offset, format)| { + let at = offset as usize; + let (n, kind) = components(format)?; + let float = matches!(kind, Kind::F32 | Kind::F16); + (float && n >= 2 && stride.saturating_sub(at) / kind.bytes() >= 2).then(|| { + victory_shader::emit::right_angle([0, 1, 2].map(|i| [0, 1].map(|k| kind.read(&v(i)[at..], k)))) + }) + }) + .unwrap_or(1); + let (a, b) = ((right + 2) % 3, (right + 1) % 3); + for (slot, i) in [0, 1, 2, a, b].into_iter().enumerate() { out[slot * stride..(slot + 1) * stride].copy_from_slice(v(i)); } let fourth = &mut out[5 * stride..]; - fourth.copy_from_slice(v(0)); + fourth.copy_from_slice(v(a)); for &(offset, format) in elements { let at = offset as usize; let Some((n, kind)) = components(format) else { @@ -42,7 +56,7 @@ pub(crate) fn expand_rects(src: &[u8], dst: &mut [u8], stride: usize, elements: let inside = stride.saturating_sub(at) / kind.bytes(); for c in 0..n.min(inside) { let get = |i: usize| kind.read(&v(i)[at..], c); - let value = get(0) + get(2) - get(1); + let value = get(a) + get(b) - get(right); kind.write(&mut fourth[at..], c, value); } } @@ -203,6 +217,30 @@ mod tests { assert_eq!(half_to_f32(0xc000), -2.0); } + /// The tiled lighting's order (top left, bottom left, top right: the + /// right angle first) completes at the bottom right, the second + /// triangle (v2, v1, v3); a triangle that is no rectangle's keeps its + /// winding in both halves. + #[test] + fn rectangles_complete_opposite_their_right_angle() { + let vertex = |x: f32, y: f32| [x.to_le_bytes(), y.to_le_bytes()].concat(); + let src = [vertex(0.0, 0.0), vertex(0.0, 1.0), vertex(1.0, 0.0)].concat(); + let mut dst = vec![0u8; 6 * 8]; + expand_rects(&src, &mut dst, 8, &[(0, 16)]); + assert_eq!(dst[24..], [&src[16..24], &src[8..16], &vertex(1.0, 1.0)[..]].concat()[..]); + let read = |d: &[u8], i: usize| { + let f = |k: usize| f32::from_le_bytes(d[i * 8 + k * 4..i * 8 + k * 4 + 4].try_into().unwrap()); + [f(0), f(1)] + }; + let turn = |d: &[u8], i: usize| { + let [a, b, c] = [i, i + 1, i + 2].map(|k| read(d, k)); + (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]) + }; + let src = [vertex(0.0, 0.0), vertex(3.0, 1.0), vertex(1.0, 0.0)].concat(); + expand_rects(&src, &mut dst, 8, &[(0, 16)]); + assert!(turn(&dst, 0) * turn(&dst, 3) > 0.0, "same winding"); + } + /// A rounding that carries out of the mantissa raises the exponent /// (the carry used to be or-ed into an odd exponent, halving the value). #[test] diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 429389529d..786b13c08f 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -81,7 +81,8 @@ //! loads and per-lane rows), so tables are never copied per draw. //! * **Rectangle lists** ([`rectangle_gs`]): a geometry shader made from a //! vertex shader's outputs completes each rectangle with its fourth -//! corner `v0 + v2 - v1`, as the console's hardware does. +//! corner opposite the right angle ([`right_angle`]), as the console's +//! hardware does. //! * **Heap indices** (added 2026-11-24) are clamped to [`HEAP_VIEWS`] − 1 //! (samplers [`HEAP_SAMPLERS`] − 1): the host's heaps have at least that //! many slots, those past its own null, so an index past the heap (data @@ -206,7 +207,7 @@ mod flow_tests; pub mod host; mod lower; mod rect; -pub use rect::rectangle_gs; +pub use rect::{rectangle_gs, right_angle}; #[cfg(all(test, windows))] mod memory_tests; mod sampler; diff --git a/crates/victory-shader/src/emit/rect.rs b/crates/victory-shader/src/emit/rect.rs index 1eb5f9a1a4..7de61bf5e7 100644 --- a/crates/victory-shader/src/emit/rect.rs +++ b/crates/victory-shader/src/emit/rect.rs @@ -1,16 +1,37 @@ //! The console's rectangle lists on the host. A rectangle comes as three -//! corners, the second between the other two, and the hardware adds the -//! fourth at `v0 + v2 - v1`, for the position and every attribute. The host -//! has no such primitive; a geometry shader made for the vertex shader that -//! feeds it takes each triangle `(v0, v1, v2)` and emits it with its -//! completion `(v0, v2, v3)`, both turning the same way. Integer outputs -//! (which can only be flat) keep `v0`'s value at the fourth corner. +//! corners in any order (the blits put the right angle at `v1`, the tiled +//! lighting at `v0`), and the hardware adds the fourth opposite the right +//! angle `vc`, at `va + vb - vc`, for the position and every attribute. The +//! host has no such primitive; a geometry shader made for the vertex shader +//! that feeds it takes each triangle `(v0, v1, v2)`, finds the right angle +//! opposite its longest side, and emits the triangle with its completion +//! `(va, vb, v3)` (`va` before `vc`, `vb` after it), both turning the same +//! way. Integer outputs (which can only be flat) keep `va`'s value at the +//! fourth corner. -use super::bitcode::{Attr, Bin, Term}; +use super::bitcode::{Attr, Bin, Term, V, pred}; use super::shader::Shader; use crate::ShaderError; use crate::dxbc::{Container, FourCC}; +/// Which of a rectangle's three corners (x and y of each) holds the right +/// angle: the one opposite the longest side, else (ties, NaN) `1`. The +/// geometry shader of [`rectangle_gs`] makes the same choice on the GPU. +pub fn right_angle(xy: [[f32; 2]; 3]) -> usize { + let side = |i: usize, j: usize| { + let (dx, dy) = (xy[i][0] - xy[j][0], xy[i][1] - xy[j][1]); + dx * dx + dy * dy + }; + let (d12, d20, d01) = (side(1, 2), side(2, 0), side(0, 1)); + if d12 > d20 && d12 > d01 { + 0 + } else if d01 > d12 && d01 > d20 { + 2 + } else { + 1 + } +} + /// The geometry shader that completes the rectangles of the vertex shader /// container `vs` (its output signature is the shader's input and output). pub fn rectangle_gs(vs: &[u8]) -> Result, ShaderError> { @@ -45,25 +66,59 @@ pub fn rectangle_gs(vs: &[u8]) -> Result, ShaderError> { } corners.push(values); } - let fourth: Vec> = elements + // The right angle, as [`right_angle`] picks it from the position. + let position = elements .iter() - .enumerate() - .map(|(id, e)| { - (0..usize::from(e.cols)) - .map(|col| { - let [v0, v1, v2] = [0, 1, 2].map(|k| corners[k][id][col]); - if e.comp == 9 { - let sum = s.m.bin(b, Bin::Add, v0, v2); - s.m.bin(b, Bin::Sub, sum, v1) - } else { - v0 - } - }) - .collect() - }) - .collect(); - corners.push(fourth); - for triangle in [[0, 1, 2], [0, 2, 3]] { + .position(|e| e.kind == 3 && e.cols >= 2 && e.comp == 9) + .ok_or(ShaderError::Malformed("a rectangle list without a position"))?; + let side = |s: &mut Shader, i: usize, j: usize| { + let mut sum = None; + for (&p, &q) in corners[i][position].iter().zip(&corners[j][position]).take(2) { + let d = s.m.bin(b, Bin::Sub, p, q); + let sq = s.m.bin(b, Bin::Mul, d, d); + sum = Some(match sum { + Some(x) => s.m.bin(b, Bin::Add, x, sq), + None => sq, + }); + } + sum.expect("two columns") + }; + let (d12, d20, d01) = (side(&mut s, 1, 2), side(&mut s, 2, 0), side(&mut s, 0, 1)); + let longest = |s: &mut Shader, d: V, others: [V; 2]| { + let [x, y] = others.map(|o| s.m.cmp(b, pred::OGT, d, o)); + s.m.bin(b, Bin::And, x, y) + }; + let (at0, at2) = (longest(&mut s, d12, [d20, d01]), longest(&mut s, d01, [d12, d20])); + // `x0` if the right angle is at v0, `x2` if at v2, else `x1`. + let pick = |s: &mut Shader, [x0, x1, x2]: [V; 3]| { + let x = s.m.select(b, at2, x2, x1); + s.m.select(b, at0, x0, x) + }; + // The completing triangle (va, vb, v3), element by element. + let mut second: [Vec>; 3] = Default::default(); + for (id, e) in elements.iter().enumerate() { + let mut cols: [Vec; 3] = Default::default(); + let [c0, c1, c2] = [0, 1, 2].map(|k| &corners[k][id]); + for ((&v0, &v1), &v2) in c0.iter().zip(c1).zip(c2) { + let va = pick(&mut s, [v2, v0, v1]); + let vb = pick(&mut s, [v1, v2, v0]); + let v3 = if e.comp == 9 { + let vc = pick(&mut s, [v0, v1, v2]); + let sum = s.m.bin(b, Bin::Add, va, vb); + s.m.bin(b, Bin::Sub, sum, vc) + } else { + va + }; + for (k, v) in [va, vb, v3].into_iter().enumerate() { + cols[k].push(v); + } + } + for (k, c) in cols.into_iter().enumerate() { + second[k].push(c); + } + } + corners.extend(second); + for triangle in [[0, 1, 2], [3, 4, 5]] { for k in triangle { for (id, e) in elements.iter().enumerate() { let suffix = if e.comp == 9 { ".f32" } else { ".i32" }; @@ -85,6 +140,25 @@ pub fn rectangle_gs(vs: &[u8]) -> Result, ShaderError> { Ok(s.finish()) } +#[cfg(test)] +mod rule_tests { + use super::right_angle; + + /// The right angle is found wherever it is; triangles that are no + /// rectangle's take the corner opposite their longest side (their + /// widest angle), and ties and NaN keep the blits' corner, `v1`. + #[test] + fn right_angles_are_found_in_any_order() { + let (tl, bl, br, tr) = ([0.0, 0.0], [0.0, 1.0], [1.0, 1.0], [1.0, 0.0]); + assert_eq!(right_angle([tl, bl, br]), 1); + assert_eq!(right_angle([tl, bl, tr]), 0); + assert_eq!(right_angle([bl, tr, tl]), 2); + assert_eq!(right_angle([[0.0, 0.0], [3.0, 1.0], [1.0, 0.0]]), 2, "obtuse at v2"); + assert_eq!(right_angle([tl, tl, tl]), 1, "a point"); + assert_eq!(right_angle([tl, [f32::NAN, 0.0], br]), 1); + } +} + #[cfg(all(test, windows))] mod tests { use super::super::bitcode::{Attr, Term}; @@ -150,9 +224,12 @@ mod tests { s.finish() } - /// One rectangle (top left, bottom left, bottom right) with a - /// coordinate attribute: every pixel of the square is drawn, the - /// attribute interpolated over it, the top-right half included. + /// One rectangle with a coordinate attribute, its right angle at each of + /// the three corners in turn (the blits' top left, bottom left, bottom + /// right; the tiled lighting's top left, bottom left, top right; and + /// one with it last): every pixel of the square is drawn, the attribute + /// interpolated over it, the missing half included. Three corners on one + /// line draw nothing. #[test] fn rectangles_get_their_fourth_corner() { let (vs, ps) = (shader(false), shader(true)); @@ -164,33 +241,33 @@ mod tests { v.validate(&mut c.clone()).unwrap(); } } - #[rustfmt::skip] - let vertices = [ - -0.5, 0.5, 0.5, 1.0, -0.5, 0.5, - -0.5, -0.5, 0.5, 1.0, -0.5, -0.5, - 0.5, -0.5, 0.5, 1.0, 0.5, -0.5, - ]; + let corner = |x: f32, y: f32| [x, y, 0.5, 1.0, x, y]; + let (tl, bl, br, tr) = (corner(-0.5, 0.5), corner(-0.5, -0.5), corner(0.5, -0.5), corner(0.5, 0.5)); + let orders = [[tl, bl, br], [tl, bl, tr], [bl, tr, tl], [tl, corner(0.0, 0.0), br]]; for warp in [false, true] { let Ok(host) = Host::new(warp) else { continue }; let root = host.root_signature_for(&[]).unwrap(); let pso = host.pipeline_gs(&root, &vs, &gs, &ps).unwrap(); - let draw = Draw { - roots: Vec::new(), - textures: &[], - samplers: &[], - vertices: &vertices, - stride: 24, - size: (32, 32), - mesh_groups: 0, - }; - let texels = host.draw(&root, &pso, &draw).unwrap(); - for (i, t) in texels.iter().enumerate() { - let (x, y) = ((i % 32) as f32, (i / 32) as f32); - let (u, v) = ((x + 0.5) / 16.0 - 1.0, 1.0 - (y + 0.5) / 16.0); - let inside = u.abs() < 0.5 && v.abs() < 0.5; - let want = if inside { [u, v, 1.0, 1.0] } else { [0.0; 4] }; - let near = t.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-4); - assert!(near, "warp {warp} pixel ({x}, {y}): {t:?}, want {want:?}"); + for (n, order) in orders.iter().enumerate() { + let vertices = order.concat(); + let draw = Draw { + roots: Vec::new(), + textures: &[], + samplers: &[], + vertices: &vertices, + stride: 24, + size: (32, 32), + mesh_groups: 0, + }; + let texels = host.draw(&root, &pso, &draw).unwrap(); + for (i, t) in texels.iter().enumerate() { + let (x, y) = ((i % 32) as f32, (i / 32) as f32); + let (u, v) = ((x + 0.5) / 16.0 - 1.0, 1.0 - (y + 0.5) / 16.0); + let inside = n < 3 && u.abs() < 0.5 && v.abs() < 0.5; + let want = if inside { [u, v, 1.0, 1.0] } else { [0.0; 4] }; + let near = t.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-4); + assert!(near, "warp {warp} order {n} pixel ({x}, {y}): {t:?}, want {want:?}"); + } } } } From 8a3d975940b3817c8722c4a792cfdb2d3b5cf87f Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 12:27:23 +0100 Subject: [PATCH 66/83] GPU: textures' staging space is carved from large upload buffers What was wrong: each texture brought up took a staging buffer of its own size class from a pool, and the pool's free buffers rarely fit a new shot's sizes: making upload buffers was 10 % of the submitting thread in a new shot (run evict5), one committed resource per texture. What changed: staging space up to 32 MiB is carved, front to back, from 32 MiB upload buffers, 512-byte aligned as texture copies need; the copies read their footprints at that offset. The chunks are rewound at each submission (the last one has run, as for the pool) and 16 are kept. Larger textures keep a buffer of their own from the pool. Evidence: test `draw::tests::textures_uploaded_together_each_read_their_own_bytes` (two textures brought up in one submission, the second at an offset in the same chunk, each read back with its own bytes) and the upload tests; the crate's tests twice with 8 threads (a timing test of frame waits, `frame::tests::waits_end_on_ticks_and_count_frames`, failed once while a title run loaded the machine, and passed in the other run). Measured together with the upload barrier batch (next commits' run shots2, 240 s of the intro cutscene, quiet): world frame median 964 ms (mean 1,038) against 1,169 ms with only the parallel creation (run shots1) and 1,206 ms before (run evict6); preparing 497 ms against 706; texture refreshes 264 ms for 135 MB a frame against 745 ms for 154 MB. The two were not measured apart. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/draw.rs | 40 +++++++++++++++ crates/victory-gpu/src/texture.rs | 81 +++++++++++++++++++++++++------ 2 files changed, 107 insertions(+), 14 deletions(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index ba35ed921d..e0eb7a6b8a 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -2441,6 +2441,46 @@ void main(uint3 id : SV_DispatchThreadID) { assert_eq!(crate::texture::uploads(object), 1, "uploaded into the new one"); } + /// Textures brought up in one submission share staging space (parts + /// of one upload buffer): each reads its own bytes. + #[test] + fn textures_uploaded_together_each_read_their_own_bytes() { + let Some(host) = crate::host::host() else { + return; // no host GPU here + }; + let slots = Slots::new(2); + let read = compile_cs(READ); + let outs: Vec<_> = (0..2).map(|_| host.shared_buffer(64 * 64 * 16).unwrap()).collect(); + let pool = crate::watch::tests::pool(2); + let views: Vec = (0..2usize) + .map(|k| { + let address = (pool + k * crate::watch::PAGE) as u64; + // SAFETY: the texture's memory in our pool, 256-byte rows of 64 texels. + unsafe { std::ptr::write_bytes(address as *mut u8, 0x40 * (k as u8 + 1), 64 * 64 * 4) }; + let object = texture_at_address(address, &texture_words(64, 64, 28, 0x100, 0)); + let mut desc = [0u32; 10]; + desc[..6].copy_from_slice(&[28, 4, 0x1688, 0, 0, 1]); + View::Shader(object as usize, Some(desc)) + }) + .collect(); + let lists: Vec<_> = (0..2usize) + .map(|k| { + slots.make(k as u32, &views[k]); + let list = host.new_list().unwrap(); + readable(&list, &used(ResourceType::Srv), &views[k], false); + run(&list, &slots, &read, k as u32, Some(&outs[k].0), (8, 8)); + list.close(); + list + }) + .collect(); + host.execute(&[&lists[0], &lists[1]]); + for (k, (_, data)) in outs.iter().enumerate() { + // SAFETY: inside the mapped output. + let texel = unsafe { (*data as *const [f32; 4]).read() }; + assert!((texel[0] - (0x40 * (k + 1)) as f32 / 255.0).abs() < 1e-6, "texture {k}: {}", texel[0]); + } + } + /// A texture written in a page that holds only its own bytes is uploaded /// without hashing them (a movie frame rewritten every frame), so even /// the same bytes again are uploaded. diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 1f35306832..f59b08cd73 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -118,6 +118,11 @@ const KEPT_BYTES: u64 = 64 << 20; /// Called before a submission's uploads: the buffers of the last one are /// free again (the oldest dropped past `KEPT_BYTES`). pub(crate) fn recycle() { + { + let mut c = CHUNKS.lock().unwrap_or_else(|e| e.into_inner()); + (c.current, c.used) = (0, 0); + c.all.truncate(CHUNKS_KEPT); + } let mut b = BUFFERS.lock().unwrap_or_else(|e| e.into_inner()); let b = &mut *b; for e in b.used.drain(..) { @@ -156,6 +161,52 @@ fn staging_buffer(size: u64) -> Option<(ID3D12Resource, *mut u8)> { Some(made) } +/// Staging space carved from large upload buffers, front to back: most +/// textures take a part of one instead of a buffer of their own (making +/// upload buffers was 10 % of the submitting thread in a new shot, run +/// evict5). Rewound at each submission ([`recycle`]): the last one has run. +struct Chunks { + /// (buffer, mapping), [`CHUNK`] bytes each. + all: Vec<(ID3D12Resource, usize)>, + /// The chunk being carved and the bytes taken from it. + current: usize, + used: u64, +} + +// SAFETY: the mappings are persistent mappings of the upload buffers. +unsafe impl Send for Chunks {} + +static CHUNKS: Mutex = Mutex::new(Chunks { all: Vec::new(), current: 0, used: 0 }); + +const CHUNK: u64 = 32 << 20; +/// Chunks kept between submissions (more are made while one needs them). +const CHUNKS_KEPT: usize = 16; + +/// `size` bytes of staging space: a buffer, the offset of the space in it +/// (a multiple of 512, as texture copies need) and its mapping there. +/// Space larger than a chunk is a buffer of its own ([`staging_buffer`]). +fn staging_space(size: u64) -> Option<(ID3D12Resource, u64, *mut u8)> { + if size > CHUNK { + return staging_buffer(size).map(|(b, data)| (b, 0, data)); + } + let mut c = CHUNKS.lock().unwrap_or_else(|e| e.into_inner()); + loop { + if let Some((buffer, data)) = c.all.get(c.current) { + let at = c.used.next_multiple_of(512); + if at + size <= CHUNK { + let made = (buffer.clone(), at, (*data + at as usize) as *mut u8); + c.used = at + size; + return Some(made); + } + (c.current, c.used) = (c.current + 1, 0); + continue; + } + let (buffer, data) = host()?.upload_buffer(CHUNK)?; + crate::host::name(&buffer, || "texture staging chunk".into()); + c.all.push((buffer, data as usize)); + } +} + // SAFETY: the title memory is only read, under `last`'s lock. unsafe impl Send for Staging {} // SAFETY: as above. @@ -324,7 +375,7 @@ pub(crate) fn record_upload( list: &HostList, copy: &Arc, staging: &Staging, - (buffer, subresources): &(ID3D12Resource, Vec), + (buffer, at, subresources): &Upload, ) { const COPY_DEST: u32 = 0x400; const SHADER_RESOURCE: u32 = 0x40 | 0x80; @@ -335,7 +386,7 @@ pub(crate) fn record_upload( } }; move_to(COPY_DEST); - copies(list, ©.texture, staging, buffer, subresources, String::new); + copies(list, ©.texture, staging, (buffer, *at), subresources, String::new); move_to(SHADER_RESOURCE); list.keep(buffer); staging.uploads.fetch_add(1, std::sync::atomic::Ordering::Relaxed); @@ -367,13 +418,15 @@ fn copies( list: &HostList, texture: &ID3D12Resource, staging: &Staging, - buffer: &ID3D12Resource, + (buffer, at): (&ID3D12Resource, u64), subresources: &[u32], name: impl Fn() -> String, ) { for &i in subresources { let i = i as usize; - let footprint = &staging.footprints[i]; + let mut footprint = staging.footprints[i]; + footprint.Offset += at; + let footprint = &footprint; #[cfg(feature = "diagnostics")] { let f = footprint.Footprint; @@ -423,9 +476,9 @@ fn copies( } } -/// What a refresh gives: a staging buffer and the subresources detiled -/// into it. -pub(crate) type Upload = (ID3D12Resource, Vec); +/// What a refresh gives: a staging buffer, where its space starts in it, +/// and the subresources detiled into it. +pub(crate) type Upload = (ID3D12Resource, u64, Vec); /// [`Staging::refresh`] of each of `work`, those whose memory may have /// changed on several threads at once (reading title memory and detiling @@ -474,7 +527,7 @@ impl Staging { /// A staging buffer with the texture memory detiled into it if it /// changed since the last time (and is mapped at all), and the /// subresources that changed (only those are detiled and to be copied). - pub(crate) fn refresh(&self) -> Option<(ID3D12Resource, Vec)> { + pub(crate) fn refresh(&self) -> Option { use std::sync::atomic::Ordering::Relaxed; let started = std::time::Instant::now(); let (read, buffer) = self.refresh_now(); @@ -486,7 +539,7 @@ impl Staging { /// Returns the bytes of title memory read, and the buffer it detiled /// into with the subresources detiled. - fn refresh_now(&self) -> (usize, Option<(ID3D12Resource, Vec)>) { + fn refresh_now(&self) -> (usize, Option) { let all = || (0..self.footprints.len() as u32).collect::>(); let size = self.layout.size as usize; let start = self.memory as usize; @@ -558,7 +611,7 @@ impl Staging { } #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexWatched, bytes as u64); - return (bytes, buffer.map(|b| (b, fresh))); + return (bytes, buffer.map(|(b, at)| (b, at, fresh))); } if !committed(self.memory, size) { #[cfg(feature = "diagnostics")] @@ -583,14 +636,14 @@ impl Staging { last.hash = buffer.is_some().then_some(hash); #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexChanged, size as u64); - (size, buffer.map(|b| (b, every))) + (size, buffer.map(|(b, at)| (b, at, every))) } /// Detiles `subresources` of `tiled` (the texture's memory) into a /// staging buffer (`None` if none could be had or a subresource could /// not be read). - fn detile(&self, tiled: &[u8], subresources: &[u32]) -> Option { - let (buffer, data) = staging_buffer(self.size)?; + fn detile(&self, tiled: &[u8], subresources: &[u32]) -> Option<(ID3D12Resource, u64)> { + let (buffer, at, data) = staging_space(self.size)?; #[cfg(feature = "diagnostics")] if tiled.iter().all(|&b| b == 0) { tracing::debug!( @@ -619,7 +672,7 @@ impl Staging { return None; } } - Some(buffer) + Some((buffer, at)) } } From ab2e2b24a0a6545b70ff5a02c4987d5627a1c40c Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 12:27:24 +0100 Subject: [PATCH 67/83] GPU: the textures of slots shaders read are made several at a time What was wrong: after a submission, the placed textures of heap slots its shaders read for the first time were made one after the other on the submitting thread, and `texture_at` held its map's lock while making each host texture: in a new shot, hundreds of committed textures, 7 % of the submitting thread (run evict5). What changed: `texture_at` makes the host texture after letting go of its map's lock, and the read slots' placed textures are made on up to four threads (a quarter of the CPUs), with the helper the texture refreshes use. Evidence: test `resource::tests::placed_textures_made_side_by_side_are_one_each` (four threads asking for four memories: one resource and one host texture each) and `descriptor::host::tests::views_written_while_read_slots_get_their_textures_do_not_wait`; the crate's tests twice with 8 threads. Measured alone (run shots1: main 8ff79135 and this commit, 240 s of the intro cutscene, quiet): world frame median 1,169 ms against 1,206 ms before (run evict6), preparing 706 ms against 709: a small gain; the staging chunks and the barrier batch carry the rest (run shots2). Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor.rs | 8 +++-- crates/victory-gpu/src/resource.rs | 26 ++++++++++++++++ crates/victory-gpu/src/texture.rs | 45 ++++++++++++++++------------ 3 files changed, 57 insertions(+), 22 deletions(-) diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 778901daf4..a48e52a933 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -220,9 +220,11 @@ pub(crate) fn make_read(slots: &[u32]) { }; #[cfg(test)] tests::while_making(slots); - for view in &placed { - let _ = host::placed_texture(view); - } + // Several at a time (each a committed texture; hundreds in a new shot, + // 7 % of the submitting thread when made one by one, run evict5). + crate::texture::in_parallel(placed.len(), |i| { + let _ = host::placed_texture(&placed[i]); + }); let heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner()); for &(start, _, at) in heaps.iter() { // SAFETY: registered heaps are live (removed when dropped). diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index 3ba05ce03b..a622552426 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -2008,6 +2008,9 @@ pub(crate) fn texture_at(address: u64, desc: &[u32; 14]) -> Option { } PLACED_BYTES.fetch_add(placed_size(desc).unwrap_or(0), std::sync::atomic::Ordering::Relaxed); map.insert((address, *desc), out as usize); + // Its host texture is made without the map's lock: the textures of the + // slots a submission's shaders read are made several at a time. + drop(map); resource(out).host().is_some().then_some(out) } @@ -2375,6 +2378,29 @@ mod tests { assert_eq!(slot::(h, 0x10)(h), 0); } + /// Placed textures asked for from several threads at once: one resource + /// and one host texture for each memory, made side by side. + #[cfg(windows)] + #[test] + fn placed_textures_made_side_by_side_are_one_each() { + if crate::host::host().is_none() { + return; // no host GPU here + } + let memory = vec![0u8; 4 << 16]; + let words: [u32; 14] = [3, 0, 0, 0, 4, 0, 1, 1 | 1 << 16, 28, 1, 0, 0x100, 0, 0]; + let base = memory.as_ptr() as u64; + let made: Vec> = std::thread::scope(|s| { + let threads: Vec<_> = (0..4) + .map(|_| s.spawn(move || (0..4u64).map(|k| texture_at(base + (k << 16), &words).unwrap() as usize).collect::>())) + .collect(); + threads.into_iter().map(|t| t.join().unwrap()).collect() + }); + for k in 0..4 { + assert!(made.iter().all(|m| m[k] == made[0][k]), "one resource for memory {k}"); + assert!(made_copy(made[0][k] as This).is_some(), "with a host texture"); + } + } + /// Textures idle for the idle time and frames are given up; past the /// budget the least recently used others follow until the excess is /// gone. diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index f59b08cd73..df7291f95d 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -480,37 +480,44 @@ fn copies( /// and the subresources detiled into it. pub(crate) type Upload = (ID3D12Resource, u64, Vec); -/// [`Staging::refresh`] of each of `work`, those whose memory may have -/// changed on several threads at once (reading title memory and detiling -/// cost ~6 ms of frame a MB on one thread in a new shot, run evict5). -pub(crate) fn refresh_all(work: &[(Arc, Arc)]) -> Vec> { +/// Runs `f(i)` for each `i` below `n` on up to a quarter of the CPUs (four +/// at most: the title's own threads need the rest), here when that is +/// fewer than two. +pub(crate) fn in_parallel(n: usize, f: impl Fn(usize) + Sync) { use std::sync::atomic::{AtomicUsize, Ordering::Relaxed}; - let mut out: Vec> = vec![None; work.len()]; - // Most find nothing changed (their trackers' clean bits say so): those - // are not handed to threads. - let changed: Vec = (0..work.len()).filter(|&i| work[i].0.maybe_changed()).collect(); - // A quarter of the CPUs at most, four at most: the title's own threads - // need the rest. - let threads = std::thread::available_parallelism().map_or(4, |n| n.get() / 4).clamp(1, 4).min(changed.len()); + let threads = std::thread::available_parallelism().map_or(4, |n| n.get() / 4).clamp(1, 4).min(n); if threads < 2 { - for &i in &changed { - out[i] = work[i].0.refresh(); - } - return out; + (0..n).for_each(f); + return; } let next = AtomicUsize::new(0); - let results: Vec>> = changed.iter().map(|_| Mutex::new(None)).collect(); std::thread::scope(|scope| { for _ in 0..threads { scope.spawn(|| { loop { - let k = next.fetch_add(1, Relaxed); - let Some(&i) = changed.get(k) else { break }; - *results[k].lock().unwrap_or_else(|e| e.into_inner()) = work[i].0.refresh(); + let i = next.fetch_add(1, Relaxed); + if i >= n { + break; + } + f(i); } }); } }); +} + +/// [`Staging::refresh`] of each of `work`, those whose memory may have +/// changed on several threads at once (reading title memory and detiling +/// cost ~6 ms of frame a MB on one thread in a new shot, run evict5). +pub(crate) fn refresh_all(work: &[(Arc, Arc)]) -> Vec> { + // Most find nothing changed (their trackers' clean bits say so): those + // are not handed to threads. + let changed: Vec = (0..work.len()).filter(|&i| work[i].0.maybe_changed()).collect(); + let results: Vec>> = changed.iter().map(|_| Mutex::new(None)).collect(); + in_parallel(changed.len(), |k| { + *results[k].lock().unwrap_or_else(|e| e.into_inner()) = work[changed[k]].0.refresh(); + }); + let mut out: Vec> = vec![None; work.len()]; for (k, r) in results.into_iter().enumerate() { out[changed[k]] = r.into_inner().unwrap_or_else(|e| e.into_inner()); } From ea812894eeb031f19feff6c448d93944c91dc72a Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 12:27:24 +0100 Subject: [PATCH 68/83] GPU: a submission's texture uploads become readable in one barrier batch What was wrong: the upload list a submission runs first recorded, for each texture it brought up, the copies and then that texture's barrier back to shader reads, so every barrier sat between one texture's copies and the next one's. In a new shot the list holds hundreds of textures (154 MB a frame in run shots1), and each barrier kept the GPU from overlapping the copies around it. What changed: record_upload returns the barrier instead of recording it, and the upload list records all of them in one call after the last copy. Evidence: textures_uploaded_together_each_read_their_own_bytes (two textures uploaded by one submission each read their own bytes) and the other upload tests pass. Measured together with the staging chunks (run shots2, 240 s of the intro cutscene, quiet): world frame median 964 ms against 1,169 ms without the two (run shots1); GPU 313 ms against 351. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/bindless.rs | 8 +++++++- crates/victory-gpu/src/texture.rs | 21 +++++++++++---------- 2 files changed, 18 insertions(+), 11 deletions(-) diff --git a/crates/victory-gpu/src/bindless.rs b/crates/victory-gpu/src/bindless.rs index 046f0b1879..8304104bca 100644 --- a/crates/victory-gpu/src/bindless.rs +++ b/crates/victory-gpu/src/bindless.rs @@ -260,14 +260,20 @@ pub(crate) fn uploads( } } let mut recorded = false; + // The textures copied into stay alive in `work` until recorded. + let mut readable = Vec::new(); for ((staging, copy), upload) in work.iter().zip(crate::texture::refresh_all(&work)) { if let Some(upload) = upload { - crate::texture::record_upload(list, copy, staging, &upload); + readable.extend(crate::texture::record_upload(list, copy, staging, &upload)); recorded = true; #[cfg(feature = "diagnostics")] UPLOADED.fetch_add(1, Relaxed); } } + if !readable.is_empty() { + // SAFETY: an open list; the barriers name live textures. + unsafe { list.list.ResourceBarrier(&readable) }; + } list.close(); // A list recording nothing is not run (its reset next time is fine). recorded.then_some(Uploads(guard)) diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index df7291f95d..59802b25d4 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -370,27 +370,28 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) } /// Records into `list` the copy of `buffer` (laid out as `staging` says) -/// into host texture `copy`, leaving it readable by shaders. +/// into host texture `copy`. Returns the barrier that leaves it readable by +/// shaders, for the caller to record with the others after every copy: one +/// barrier per texture between the copies kept the GPU from overlapping +/// them (new shots copy hundreds of textures, run evict6). +#[must_use] pub(crate) fn record_upload( list: &HostList, copy: &Arc, staging: &Staging, (buffer, at, subresources): &Upload, -) { +) -> Option { const COPY_DEST: u32 = 0x400; const SHADER_RESOURCE: u32 = 0x40 | 0x80; - let move_to = |wanted| { - if let Some(b) = list.move_texture(copy, wanted) { - // SAFETY: an open list; the barrier names a live texture. - unsafe { list.list.ResourceBarrier(&[b]) }; - } - }; - move_to(COPY_DEST); + if let Some(b) = list.move_texture(copy, COPY_DEST) { + // SAFETY: an open list; the barrier names a live texture. + unsafe { list.list.ResourceBarrier(&[b]) }; + } copies(list, ©.texture, staging, (buffer, *at), subresources, String::new); - move_to(SHADER_RESOURCE); list.keep(buffer); staging.uploads.fetch_add(1, std::sync::atomic::Ordering::Relaxed); staging.copied.fetch_add(subresources.len() as u64, std::sync::atomic::Ordering::Relaxed); + list.move_texture(copy, SHADER_RESOURCE) } /// The uploads [`record_upload`] recorded into `resource`'s host texture From 0a5be3c7c6a217246be8dba36671c0f9a996146f Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 12:08:07 +0100 Subject: [PATCH 69/83] GPU: only what programs using title memory write is withheld when their list misses A list in which a program using title memory read or wrote memory with no copy had every range its shaders declared withheld from title memory (and, since ec9e750e, dropped from the host copies right after the submission), whichever program declared it. The BVH builder's list also holds ordinary programs (run light13, one list: ~1,000 builder dispatches beside billboard_nobump:CS_ComputeImposterTransform x250, CSGenerateHairVB/IB, bvh_skinning, CS_InstanceRotationFixup), so their output never reached title memory and, after the drop, never reached the frame's later draws either. Now each declared range records whether its program uses title memory (the draw or dispatch being bound, `HostList::writer_uses_memory`), and only those ranges are withheld when their list misses. Other programs write through bounded views from their own inputs: their ranges go back as before the withholding. An ordinary range overlapping a withheld range of the same copy is withheld with it, since its copy-back would take the other's bytes along. Test: host::withholding::only_programs_using_title_memory_are_withheld (a missing list with an ordinary write, a title-memory program's write and an overlapping ordinary write; fails with the whole list withheld). Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/draw.rs | 3 + crates/victory-gpu/src/host.rs | 111 ++++++++++++++++++++++++++++++--- 2 files changed, 104 insertions(+), 10 deletions(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index e0eb7a6b8a..e6b7b6b6aa 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -509,6 +509,9 @@ impl State { /// False if the draw or dispatch must not run: a table it reads could /// not be made. fn bind(&mut self, list: &HostList, p: &HostPipeline, compute: bool) -> bool { + // What its shaders write is withheld only if the program uses title + // memory and a list using it misses (`crate::memory::withholding`). + let _writer = list.writer_uses_memory(p.stages.iter().any(|s| s.memory.is_some())); let l = &list.list; // A depth copy of ours (`crate::twin`) since the last one ran a // compute pipeline. diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 01297898e5..67b863118d 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -759,6 +759,9 @@ pub(crate) struct HostList { /// A list of ours (uploads), whose uses are no use of the title's /// (`crate::resource::evict`). ours: std::sync::atomic::AtomicBool, + /// The draw or dispatch being recorded runs a program using title + /// memory ([`HostList::writer_uses_memory`]). + memory_writer: std::sync::atomic::AtomicBool, /// The list that runs those transitions just before this one. prelude: (ID3D12CommandAllocator, ID3D12GraphicsCommandList), /// The pipelines the list binds, for reports of slow submissions. @@ -913,8 +916,10 @@ enum Step { /// Work that writes host memory only. Host(Box), /// Shaders write a range (address, bytes) of a buffer's host copy; - /// whether they mark the pages they write (no snapshot then). - GpuWrite(std::sync::Arc, usize, usize, bool), + /// whether they mark the pages they write (no snapshot then), and + /// whether their program uses title memory (then the range is withheld + /// when such a list misses, `crate::memory::withholding`). + GpuWrite(std::sync::Arc, usize, usize, bool, bool), /// Brings a texture's staging buffer up to date: once per submission, /// whichever lists sample it, until a `Copy` or `Run` intervenes. Texture(std::sync::Arc, std::sync::Arc), @@ -1061,6 +1066,7 @@ impl Host { twins: Mutex::default(), rebind: false.into(), ours: false.into(), + memory_writer: false.into(), prelude: (prelude_allocator, prelude), pipelines: Mutex::default(), id, @@ -1266,9 +1272,13 @@ impl Host { let mut index: std::collections::HashMap<(usize, usize, usize), usize> = std::collections::HashMap::new(); // Shaders that read memory with no copy computed something else than // the console's: it stays out of title memory, where it broke the - // title's own data (runs c1, c4), and so does what every list using - // title memory wrote while any misses (`crate::memory::withholding`). - // Only such lists have checks; all are asked before anything goes back. + // title's own data (runs c1, c4), and so does what every program + // using title memory wrote while any misses + // (`crate::memory::withholding`). Only lists with such programs have + // checks; all are asked before anything goes back. Other programs in + // those lists write through bounded views from their own inputs: + // their ranges go back (the imposter transforms beside the BVH + // builder in one list, run light13). let missed: Vec = runs .iter() .map(|list| list.deferred().missed.iter().any(|check| check())) @@ -1279,18 +1289,32 @@ impl Host { let deferred = list.deferred(); let missed = missed || withholding && !deferred.missed.is_empty(); for step in &deferred.copies { - if let Step::GpuWrite(shadow, address, len, _) = step { + if let Step::GpuWrite(shadow, address, len, _, memory) = step { let key = (std::sync::Arc::as_ptr(shadow) as usize, *address, *len); + // A range both kinds declare is withheld whole. + let goes_back = !(missed && *memory); match index.get(&key) { - Some(&i) => back[i].3 &= !missed, + Some(&i) => back[i].3 &= goes_back, None => { index.insert(key, back.len()); - back.push((shadow.clone(), *address, *len, !missed)); + back.push((shadow.clone(), *address, *len, goes_back)); } } } } } + // A range overlapping a withheld one of the same copy is withheld + // too: its copy-back would take the other's bytes along (pages a + // program using title memory and another both wrote). + let held: Vec<(usize, usize, usize)> = back + .iter() + .filter(|b| !b.3) + .map(|(s, a, n, _)| (std::sync::Arc::as_ptr(s) as usize, *a, *n)) + .collect(); + for b in back.iter_mut().filter(|b| b.3) { + let copy = std::sync::Arc::as_ptr(&b.0) as usize; + b.3 = !held.iter().any(|&(c, a, n)| c == copy && a < b.1 + b.2 && b.1 < a + n); + } // Pages shaders marked first: the copy-backs below end what the // copies keep for them. let withheld: Vec<(std::sync::Arc, usize, usize)> = back @@ -1797,6 +1821,19 @@ impl HostList { self.ours.store(true, Ordering::Relaxed); } + /// What the list's shaders write from now until the guard goes is + /// written by a program using title memory (`uses`) or not. + pub(crate) fn writer_uses_memory(&self, uses: bool) -> impl Drop + '_ { + struct Reset<'a>(&'a std::sync::atomic::AtomicBool); + impl Drop for Reset<'_> { + fn drop(&mut self) { + self.0.store(false, Ordering::Relaxed); + } + } + self.memory_writer.store(uses, Ordering::Relaxed); + Reset(&self.memory_writer) + } + /// A copy of ours replaced the compute root signature and pipeline. pub(crate) fn need_rebind(&self) { self.rebind.store(true, Ordering::Relaxed); @@ -1977,9 +2014,10 @@ impl HostList { len: usize, marked: bool, ) { + let memory = self.memory_writer.load(Ordering::Relaxed); self.deferred() .copies - .push(Step::GpuWrite(shadow.clone(), address, len, marked)); + .push(Step::GpuWrite(shadow.clone(), address, len, marked, memory)); } /// Shaders of the list take views from the heap itself @@ -2197,7 +2235,7 @@ impl HostList { } continue; } - Step::GpuWrite(shadow, address, len, marked) => { + Step::GpuWrite(shadow, address, len, marked, _) => { // The shaders start from the title's data, which a // snapshot must hold (marked ranges keep none). if !marked { @@ -3391,3 +3429,56 @@ mod batch { // `mod tests` is already taken at the top of this file } } + +#[cfg(test)] +mod withholding { + /// A list in which a program using title memory missed memory: what + /// that program wrote is withheld from title memory and leaves the + /// copies at once; what an ordinary program wrote in the same list goes + /// back and stays in its copy (run light13: the imposter transforms in + /// the BVH builder's list); an ordinary range overlapping a withheld one + /// is withheld with it, since its copy-back would take the other's bytes + /// along. + #[test] + fn only_programs_using_title_memory_are_withheld() { + use crate::watch::PAGE; + let Some(host) = super::host() else { + return; // no host GPU here + }; + let pools = [crate::watch::tests::pool(1), crate::watch::tests::pool(1)]; + for &p in &pools { + // SAFETY: our pool, not guarded yet. + unsafe { ((p + 16) as *mut u8).write_volatile(0x11) }; + crate::shadow::register(p, p as u64, PAGE as u64); + } + let copies: Vec<_> = pools.iter().map(|&p| crate::shadow::find(p as u64, PAGE as u64).unwrap()).collect(); + let list = host.new_list().unwrap(); + // (copy, start, bytes, the writer uses title memory, byte written at +0 and +16) + let writes = [(0, 0, 32, false, 0x22), (1, 16, 16, true, 0x33), (1, 0, 32, false, 0x44)]; + for &(k, at, len, memory, value) in &writes { + let _writer = list.writer_uses_memory(memory); + let (copy, address) = (copies[k].clone(), (pools[k] + at) as u64); + copy.refresh(&list, address, len); + copy.gpu_writes(&list, address, len, false); + // The shader's write, after the step that keeps the range's bytes. + list.defer_host(move || copy.write_host(address, &[value])); + } + list.defer_missed(|| true); + list.close(); + host.execute(&[&list]); + // SAFETY: bytes of our pools. + let title = |k: usize, at: usize| unsafe { ((pools[k] + at) as *const u8).read_volatile() }; + let copy = |k: usize, at: usize| { + copies[k].update(pools[k], PAGE); + copies[k].read_host((pools[k] + at) as u64, 1)[0] & 0xff + }; + assert_eq!((title(0, 0), copy(0, 0)), (0x22, 0x22), "an ordinary program's write goes back and stays"); + assert_eq!((title(1, 16), copy(1, 16)), (0x11, 0x11), "withheld, then dropped from the copy"); + assert_eq!((title(1, 0), copy(1, 0)), (0, 0), "overlapping a withheld range: withheld with it"); + for (&p, copy) in pools.iter().zip(copies) { + crate::shadow::unregister(p, p as u64); + drop(copy); + crate::watch::tests::free(p); + } + } +} From f68442ffe04caef6b9a52c67d74ed82a9dc17657 Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 13:45:27 +0100 Subject: [PATCH 70/83] GPU: a texture a host copy writes is the host's from the copy's submission What was wrong: `texture::host_written` marked a texture as written by the host (a copy, copy-region or resolve into it) when the list holding the copy was recorded, and textures read through tables were checked only then, by `texture::upload` at record time. A list recorded before the writer but submitted after it kept its upload due: its submission uploaded title memory over the texels the host copy had written. Submissions need not run in the order their lists were recorded (`light` is changing the order to the title's own waits between queues), so this decision belongs to the submission. What changed: `texture::host_writes(list, resource)` marks the texture from the submission that runs the writing list (a deferred host step), and the submission's upload gathering skips table-read textures so marked, as the heap path already did. A reader submitted before the writer still gets its upload; one submitted after keeps the host's texels. Evidence: test `draw::tests::a_list_run_after_a_host_write_keeps_the_host_texels` (a reader recorded, title memory written, a later-recorded writer submitted first, then the reader: the host's texels stay). Without the submission-time check it fails (the title's new bytes, 0.502, uploaded over 0.251). victory-gpu tests 179 passed; workspace clippy clean. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/bindless.rs | 5 +++ crates/victory-gpu/src/draw.rs | 52 ++++++++++++++++++++++++++++++ crates/victory-gpu/src/list.rs | 6 ++-- crates/victory-gpu/src/texture.rs | 16 ++++++--- 4 files changed, 71 insertions(+), 8 deletions(-) diff --git a/crates/victory-gpu/src/bindless.rs b/crates/victory-gpu/src/bindless.rs index 8304104bca..e2033918db 100644 --- a/crates/victory-gpu/src/bindless.rs +++ b/crates/victory-gpu/src/bindless.rs @@ -222,6 +222,11 @@ pub(crate) fn uploads( let mut work: Vec<(Arc, Arc)> = Vec::new(); let mut staged = std::collections::HashSet::new(); for (staging, copy) in textures { + // A host copy wrote it in a submission made before this one (it + // was not when the list was recorded). + if copy.host_written.load(Relaxed) { + continue; + } if staged.insert(Arc::as_ptr(staging)) { work.push((staging.clone(), copy.clone())); } diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index e6b7b6b6aa..7e2059af42 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -2403,6 +2403,58 @@ void main(uint3 id : SV_DispatchThreadID) { assert_eq!(submit(Some(0x80)).0, 0, "the same bytes in a shared page: not uploaded"); } + /// A list recorded before another whose host copy writes a texture it + /// reads, but run after it, reads the host's texels: whether its upload + /// from title memory is still due is decided when its submission is + /// made, after the writing list's (`texture::host_writes`), not when it + /// was recorded. + #[test] + fn a_list_run_after_a_host_write_keeps_the_host_texels() { + let Some(host) = crate::host::host() else { + return; // no host GPU here + }; + let slots = Slots::new(2); + let read = compile_cs(READ); + let (out, data) = host.shared_buffer(64 * 64 * 16).unwrap(); + // Runtime memory the change journal follows; RGBA8 64x64, linear. + let address = crate::watch::tests::pool(1) as u64; + let object = texture_at_address(address, &texture_words(64, 64, 28, 0x100, 0)); + let mut desc = [0u32; 10]; + desc[..6].copy_from_slice(&[28, 4, 0x1688, 0, 0, 1]); + let view = View::Shader(object as usize, Some(desc)); + slots.make(0, &view); + let reading = || { + let list = host.new_list().unwrap(); + readable(&list, &used(ResourceType::Srv), &view, false); + run(&list, &slots, &read, 0, Some(&out), (8, 8)); + list.close(); + list + }; + // SAFETY: inside the mapped output. + let texel = || unsafe { (data as *const [f32; 4]).read() }[0]; + // SAFETY: the texture's memory, 256-byte rows of 64 texels. + let write = |byte: u8| unsafe { std::ptr::write_bytes(address as *mut u8, byte, 64 * 64 * 4) }; + write(0x40); + host.execute(&[&reading()]); + assert!((texel() - 64.0 / 255.0).abs() < 1e-6, "uploaded: {}", texel()); + // The title writes the memory again and a list reading the texture + // is recorded: its upload is due. + write(0x80); + let late = reading(); + // A list recorded after it, holding a host copy into the texture + // (its mark; what it copies is the host's business), runs first. + let copying = host.new_list().unwrap(); + crate::texture::host_writes(©ing, object); + copying.close(); + host.execute(&[©ing]); + host.execute(&[&late]); + assert!( + (texel() - 64.0 / 255.0).abs() < 1e-6, + "the host's texels kept, not title memory uploaded over them: {}", + texel() + ); + } + /// A texture fed from title memory given up (`resource::evict`) while a /// recorded list names it: the list still reads it, and the next use /// makes it again with its bytes from title memory. diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 9801e0ba54..1f4ee204a7 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -468,7 +468,7 @@ extern "system" fn copy_resource(this: This, dst: This, src: This) { } ensure_state(list, dst, COPY_DEST); ensure_state(list, src, COPY_SOURCE); - crate::texture::host_written(dst); + crate::texture::host_writes(list, dst); #[cfg(feature = "diagnostics")] list.note_op(|| format!("copy resource {src:?} to {dst:?}")); // SAFETY: an open list and live textures. @@ -565,7 +565,7 @@ extern "system" fn copy_texture_region( from.resource = texture.as_raw().cast_const().cast(); } ensure_state(list, dst.resource, COPY_DEST); - crate::texture::host_written(dst.resource); + crate::texture::host_writes(list, dst.resource); let mut to_location = dst; to_location.resource = to.as_raw().cast_const().cast(); let host_box = (!source_box.is_null()).then(|| source_box.cast::()); @@ -761,7 +761,7 @@ extern "system" fn resolve( const RESOLVE_SOURCE: u32 = 0x2000; ensure_state(list, dst, RESOLVE_DEST); ensure_state(list, src, RESOLVE_SOURCE); - crate::texture::host_written(dst); + crate::texture::host_writes(list, dst); #[cfg(feature = "diagnostics")] list.note_op(|| format!("resolve {src:?} to {dst:?} format {format}")); // SAFETY: an open list and live textures; the region is inside both. diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 59802b25d4..803d00f4dc 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -212,11 +212,17 @@ unsafe impl Send for Staging {} // SAFETY: as above. unsafe impl Sync for Staging {} -/// A host copy or resolve writes `resource`: its host texture's contents -/// are the host's, not title memory's, which stays as it was. -pub(crate) fn host_written(resource: This) { +/// A host copy or resolve that `list` records writes `resource`: from the +/// submission that runs `list` on, its host texture's contents are the +/// host's, not title memory's, which stays as it was. Marked when that +/// submission is made, not when `list` is recorded: a list recorded before +/// it but run after it must not upload title memory over the host's texels +/// (submissions run in the order they are made, which need not be the +/// order their lists were recorded in), and one run before it must still +/// get its upload. +pub(crate) fn host_writes(list: &HostList, resource: This) { if let Some(copy) = crate::resource::host_copy(resource) { - copy.host_written.store(true, std::sync::atomic::Ordering::Relaxed); + list.defer_host(move || copy.host_written.store(true, std::sync::atomic::Ordering::Relaxed)); } } @@ -294,7 +300,7 @@ pub(crate) fn alias_copy(list: &HostList, from: This, to: This) { } let Some(buffer) = host.default_buffer(total) else { return }; list.keep(&buffer); - crate::texture::host_written(to); + crate::texture::host_writes(list, to); crate::list::ensure_state(list, from, COPY_SOURCE); crate::list::ensure_state(list, to, COPY_DEST); let place = |r: &ID3D12Resource, f: D3D12_PLACED_SUBRESOURCE_FOOTPRINT| D3D12_TEXTURE_COPY_LOCATION { From 11e9a54448a8efa200c701f2c2e7136cda38b0c2 Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 14:19:21 +0100 Subject: [PATCH 71/83] GPU: textures fed from title memory are placed in heaps made ahead What was wrong: every host texture was a committed resource, made one by one. A new shot brings hundreds of textures at once (the placed textures of slots shaders read for the first time, made after the submission), and making them took most of the copying-back phase: windows that made 337 / 134 / 110 MB of placed textures a frame spent 351 / 926 / 300 ms there (run shots2). Measured on the RX 6700 XT, 300 textures of a new shot's sizes (430 MB): committed 255 ms (not zeroed: 274 ms); one heap 32 ms, then placed 3 ms. What changed: textures without render-target, depth, unordered-access or simultaneous use, up to 16 MiB, are placed in 64 MiB heaps (default heaps for textures that are neither render targets nor depth), first fit, with castable formats through `CreatePlacedResource2` as the committed path uses `CreateCommittedResource3`; others stay committed, and so does a texture whose placement the host refuses. A texture's range is free again only once nothing else holds its resource (views' slots keep it until the running submission has run, lists until they are reset), checked at each placement and eviction pass; empty heaps past two are released. The eviction budget counts free heap space as unused. A texture whose memory is not committed when first read gets zeros, as a committed one starts (a placed one starts with what its range held); every other first refresh already uploads every subresource. The host-textures statistics line gives the heaps held and their used and free bytes. Evidence: tests `placement::tests::ranges_are_taken_first_fit_and_joined_when_given_back` and `a_range_is_reused_only_once_nothing_holds_its_texture`; the texture upload tests, whose textures are now placed, pass (victory-gpu 182 passed, twice). Run placed1 (240 s of the intro cutscene, quiet, on main with the narrower withholding of 0a5be3c7 and the host-write fix): making the read slots' textures 23 ms a frame (median 12; the largest new shots 406 / 568 / 871 slots in 107 / 68 / 43 ms), against up to 926 ms before; copying back 109 ms against 223 (run shots2); world frame median 894 ms against 964. The whole-frame gain shares its main with the withholding change; the read-slot part is placement's alone. No device removal, no stale texels seen. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/host.rs | 4 + crates/victory-gpu/src/lib.rs | 2 + crates/victory-gpu/src/placement.rs | 285 ++++++++++++++++++++++++++++ crates/victory-gpu/src/resource.rs | 95 ++++++++-- crates/victory-gpu/src/texture.rs | 11 +- 5 files changed, 378 insertions(+), 19 deletions(-) create mode 100644 crates/victory-gpu/src/placement.rs diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 67b863118d..99d63d904c 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -2771,12 +2771,16 @@ impl Meter { making = crate::pipeline::making() ); let (textures, bytes, used, shared, saved, replaced) = crate::resource::texture_counts(); + let (heaps, heap_used, heap_free) = crate::placement::stats(); tracing::info!( "host textures: {textures} ({:.0} MB, {:.0} MB of them used by lists), title textures sharing one {shared} (saving {:.0} MB), replacing one {replaced}; \ + heaps of textures {heaps} ({:.0} MB used, {:.0} MB free); \ copies between textures of one memory {:.1}/frame, depth twin copies {:.1}/frame", bytes as f64 / 1e6, used as f64 / 1e6, saved as f64 / 1e6, + heap_used as f64 / 1e6, + heap_free as f64 / 1e6, crate::texture::ALIAS_COPIES.swap(0, Ordering::Relaxed) as f64 / frames, crate::twin::COPIES.swap(0, Ordering::Relaxed) as f64 / frames, ); diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index fc1c958bd0..d4d97cce31 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -42,6 +42,8 @@ mod memory; pub mod object; pub mod pipeline; #[cfg(windows)] +mod placement; +#[cfg(windows)] mod primitive; pub mod query; pub mod queue; diff --git a/crates/victory-gpu/src/placement.rs b/crates/victory-gpu/src/placement.rs new file mode 100644 index 0000000000..7c0afbbc35 --- /dev/null +++ b/crates/victory-gpu/src/placement.rs @@ -0,0 +1,285 @@ +//! Host textures placed in heaps made ahead instead of committed one by +//! one: a new shot brings hundreds of textures, and the host spent most of +//! a frame making them (300 textures, 430 MB on the RX 6700 XT: committed +//! 255 ms; one heap 32 ms, then placed 3 ms). +//! +//! Textures without render-target, depth or unordered-access use, up to a +//! quarter of a heap, go into heaps of [`HEAP`] bytes, first fit. A +//! texture's range is free again once nothing else holds its resource +//! (heap slots keep views' resources until the running submission has run, +//! lists until they are reset), so no view or list sees its memory reused. +//! Empty heaps past [`SPARE`] are released. + +use std::collections::BTreeMap; +use std::sync::Mutex; + +use windows::Win32::Graphics::Direct3D12::*; +use windows::core::Interface; + +/// Bytes of one heap. +const HEAP: u64 = 64 << 20; +/// Empty heaps kept for the next textures. +const SPARE: usize = 2; +/// Placement alignment of textures that are not render targets. +const ALIGN: u64 = 64 << 10; + +/// Where a texture lies: heap, offset and bytes. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct Placement { + heap: u64, + offset: u64, + size: u64, +} + +/// A heap and its free ranges (offset → bytes). +struct Heap { + heap: ID3D12Heap, + id: u64, + free: BTreeMap, +} + +#[derive(Default)] +struct Heaps { + heaps: Vec, + next: u64, + /// Ranges whose texture may still be held elsewhere, with a holder of + /// our own. + pending: Vec<(ID3D12Resource, Placement)>, +} + +// SAFETY: D3D12 heaps and resources are free-threaded; used under the lock. +unsafe impl Send for Heaps {} + +static HEAPS: Mutex> = Mutex::new(None); + +/// The first range of `free` that fits `size` bytes at `align`: its +/// offset, taken out of `free`. +fn take(free: &mut BTreeMap, size: u64, align: u64) -> Option { + let (&start, &len, at) = free.iter().find_map(|(s, l)| { + let at = s.next_multiple_of(align); + (at + size <= s + l).then_some((s, l, at)) + })?; + free.remove(&start); + if at > start { + free.insert(start, at - start); + } + if at + size < start + len { + free.insert(at + size, start + len - at - size); + } + Some(at) +} + +/// Gives `[offset, offset + size)` back to `free`, joined with its +/// neighbours. +fn give(free: &mut BTreeMap, offset: u64, size: u64) { + let (mut start, mut end) = (offset, offset + size); + if let Some((&s, &l)) = free.range(..start).next_back() + && s + l == start + { + free.remove(&s); + start = s; + } + if let Some(&l) = free.get(&end) { + free.remove(&end); + end += l; + } + free.insert(start, end - start); +} + +/// Whether a resource has no holder but the one passed. +fn last_holder(resource: &ID3D12Resource) -> bool { + // SAFETY: a live COM object; one reference taken and given back. + unsafe { + let raw = resource.as_raw(); + let unknown = &*(raw as *const *const windows::core::IUnknown_Vtbl); + ((**unknown).AddRef)(raw); + ((**unknown).Release)(raw) == 1 + } +} + +impl Heaps { + /// Frees the pending ranges nothing else holds now, and releases empty + /// heaps past [`SPARE`]. + fn reap(&mut self) { + let mut i = 0; + while i < self.pending.len() { + if last_holder(&self.pending[i].0) { + let (_, p) = self.pending.swap_remove(i); + if let Some(h) = self.heaps.iter_mut().find(|h| h.id == p.heap) { + give(&mut h.free, p.offset, p.size); + } + } else { + i += 1; + } + } + let empty = |h: &Heap| h.free.get(&0) == Some(&HEAP); + let mut spare = 0; + self.heaps.retain(|h| { + if !empty(h) { + return true; + } + spare += 1; + spare <= SPARE + }); + } + + /// A range of `size` bytes: in a heap with room, else in a new heap. + fn allocate(&mut self, device: &ID3D12Device, size: u64, align: u64) -> Option<(ID3D12Heap, Placement)> { + for h in &mut self.heaps { + if let Some(offset) = take(&mut h.free, size, align) { + return Some((h.heap.clone(), Placement { heap: h.id, offset, size })); + } + } + let desc = D3D12_HEAP_DESC { + SizeInBytes: HEAP, + Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + Alignment: ALIGN, + Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES, + }; + let mut heap: Option = None; + // SAFETY: plain creation, our out pointer. + unsafe { device.CreateHeap(&desc, &mut heap) }.ok()?; + let heap = heap?; + crate::host::name(&heap, || "texture heap".into()); + let id = self.next; + self.next += 1; + let mut free = BTreeMap::new(); + free.insert(0, HEAP); + let offset = take(&mut free, size, align)?; + self.heaps.push(Heap { heap: heap.clone(), id, free }); + Some((heap, Placement { heap: id, offset, size })) + } +} + +/// Whether a texture of `desc` goes into a heap: no render-target, depth or +/// unordered-access use, and at most a quarter of a heap. +pub(crate) fn fits(device: &ID3D12Device, desc: &D3D12_RESOURCE_DESC) -> bool { + const USES: i32 = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET.0 + | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL.0 + | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 + | D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS.0; + if desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER || desc.Flags.0 & USES != 0 || desc.SampleDesc.Count > 1 { + return false; + } + // SAFETY: a plain query. + let info = unsafe { device.GetResourceAllocationInfo(0, &[*desc]) }; + info.SizeInBytes != u64::MAX && info.SizeInBytes <= HEAP / 4 && info.Alignment <= ALIGN +} + +/// Room for a texture of `desc` in a heap ([`fits`] first): the heap and +/// the placement, which the texture gives back with [`free`]. +pub(crate) fn place(device: &ID3D12Device, desc: &D3D12_RESOURCE_DESC) -> Option<(ID3D12Heap, Placement)> { + // SAFETY: a plain query. + let info = unsafe { device.GetResourceAllocationInfo(0, &[*desc]) }; + let size = info.SizeInBytes.next_multiple_of(ALIGN); + let mut heaps = HEAPS.lock().unwrap_or_else(|e| e.into_inner()); + let heaps = heaps.get_or_insert_with(Heaps::default); + heaps.reap(); + heaps.allocate(device, size, info.Alignment.max(ALIGN)) +} + +/// A range [`place`] gave whose texture could not be made there. +pub(crate) fn unplace(p: Placement) { + let mut heaps = HEAPS.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(h) = heaps.as_mut().and_then(|hs| hs.heaps.iter_mut().find(|h| h.id == p.heap)) { + give(&mut h.free, p.offset, p.size); + } +} + +/// The texture at `p` is let go of: its range is free again once nothing +/// else holds `resource` (checked at the next placements and passes). +pub(crate) fn free(resource: ID3D12Resource, p: Placement) { + let mut heaps = HEAPS.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(h) = heaps.as_mut() { + h.pending.push((resource, p)); + h.reap(); + } +} + +/// Bytes of heap space free for textures (after freeing what nothing +/// holds now): the card's memory they take is not in use. +pub(crate) fn free_bytes() -> u64 { + let mut heaps = HEAPS.lock().unwrap_or_else(|e| e.into_inner()); + let Some(h) = heaps.as_mut() else { return 0 }; + h.reap(); + h.heaps.iter().flat_map(|h| h.free.values()).sum() +} + +/// Heaps of textures held, and their used and free bytes (after freeing +/// what nothing holds now), for the statistics line. +pub(crate) fn stats() -> (usize, u64, u64) { + let mut heaps = HEAPS.lock().unwrap_or_else(|e| e.into_inner()); + let Some(h) = heaps.as_mut() else { return (0, 0, 0) }; + h.reap(); + let free: u64 = h.heaps.iter().flat_map(|h| h.free.values()).sum(); + (h.heaps.len(), h.heaps.len() as u64 * HEAP - free, free) +} + +impl Placement { + /// Its offset in its heap. + pub(crate) fn offset(&self) -> u64 { + self.offset + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A texture's range is not handed out again while anything else holds + /// its resource (a view's slot, a list), and is once nothing does. + #[test] + fn a_range_is_reused_only_once_nothing_holds_its_texture() { + use windows::Win32::Graphics::Dxgi::Common::*; + let Some(host) = crate::host::host() else { + return; // no host GPU here + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 256, + Height: 256, + DepthOrArraySize: 1, + MipLevels: 9, + Format: DXGI_FORMAT_BC1_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + assert!(fits(&host.device, &desc)); + let mut heaps = Heaps::default(); + let (heap, a) = heaps.allocate(&host.device, ALIGN, ALIGN).unwrap(); + let mut texture: Option = None; + // SAFETY: a range of the heap, our out pointer. + unsafe { host.device.CreatePlacedResource(&heap, a.offset(), &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut texture) }.unwrap(); + let texture = texture.unwrap(); + let held = texture.clone(); + heaps.pending.push((texture, a)); + heaps.reap(); + let (_, b) = heaps.allocate(&host.device, ALIGN, ALIGN).unwrap(); + assert_ne!(b, a, "still held: not handed out"); + drop(held); + heaps.reap(); + let (_, c) = heaps.allocate(&host.device, ALIGN, ALIGN).unwrap(); + assert_eq!(c, a, "nothing holds it: free again"); + } + + #[test] + fn ranges_are_taken_first_fit_and_joined_when_given_back() { + let k = 64 << 10; + let mut free = BTreeMap::from([(0, 10 * k)]); + let a = take(&mut free, 3 * k, k).unwrap(); + let b = take(&mut free, 2 * k, k).unwrap(); + let c = take(&mut free, 4 * k, k).unwrap(); + assert_eq!((a, b, c), (0, 3 * k, 5 * k)); + assert_eq!(take(&mut free, 2 * k, k), None, "one 64 KiB range left"); + give(&mut free, b, 2 * k); + assert_eq!(take(&mut free, 3 * k, k), None, "two ranges of 2 and 1, not joined"); + give(&mut free, c, 4 * k); + assert_eq!(free, BTreeMap::from([(3 * k, 7 * k)]), "joined with both neighbours"); + give(&mut free, a, 3 * k); + assert_eq!(free, BTreeMap::from([(0, 10 * k)])); + // An aligned range inside a free one keeps the padding before it. + let mut free = BTreeMap::from([(k, 10 * k)]); + assert_eq!(take(&mut free, k, 4 * k), Some(4 * k)); + assert_eq!(free, BTreeMap::from([(k, 3 * k), (5 * k, 6 * k)])); + } +} diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index a622552426..049c339a54 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -820,6 +820,9 @@ pub(crate) struct HostTexture { pub(crate) viewed: std::sync::atomic::AtomicBool, /// The memory it copies, for title textures fed from it. key: Option, + /// Its range in a heap of textures (`crate::placement`), given back + /// when it goes; `None` for a committed texture. + placement: Option, /// When the title last used it: presented frame and milliseconds since /// the first stamp ([`HostTexture::stamp`]). last: [std::sync::atomic::AtomicU64; 2], @@ -850,6 +853,7 @@ impl HostTexture { used: false.into(), viewed: false.into(), key: None, + placement: None, last: [crate::queue::presented().into(), now_ms().into()], } } @@ -949,6 +953,9 @@ pub(crate) fn texture_census() -> [[u64; 3]; 2] { #[cfg(windows)] impl Drop for HostTexture { fn drop(&mut self) { + if let Some(p) = self.placement.take() { + crate::placement::free(self.texture.clone(), p); + } TEXTURES.fetch_sub(1, std::sync::atomic::Ordering::Relaxed); TEXTURE_BYTES.fetch_sub(self.bytes, std::sync::atomic::Ordering::Relaxed); if *self.used.get_mut() { @@ -1306,25 +1313,54 @@ fn make_texture(d: &ResourceDesc, state: u32, clear: *const c_void) -> Option = None; let mut castable_formats = if d.flags & DEPTH == 0 { castable(d.format) } else { Vec::new() }; let mut initial = crate::host::legal_for(d.flags, crate::host::texture_state(state)); - if !castable_formats.is_empty() - && let Ok(device) = host.device.cast::() + // In a heap of textures if it fits there (`crate::placement`). + // SAFETY: the description has the host layout (checked size). + let plain = unsafe { std::ptr::from_ref(d).cast::().read_unaligned() }; + let mut placement = None; + if clear_value.is_none() + && crate::placement::fits(&host.device, &plain) + && let Some((heap, p)) = crate::placement::place(&host.device, &plain) { - // SAFETY: the description has the host layout (checked size). - let p = unsafe { std::ptr::from_ref(d).cast::().read_unaligned() }; - // The plain description plus the sampler feedback region (none). - let desc1 = D3D12_RESOURCE_DESC1 { - Dimension: p.Dimension, - Alignment: p.Alignment, - Width: p.Width, - Height: p.Height, - DepthOrArraySize: p.DepthOrArraySize, - MipLevels: p.MipLevels, - Format: p.Format, - SampleDesc: p.SampleDesc, - Layout: p.Layout, - Flags: p.Flags, - SamplerFeedbackMipRegion: Default::default(), + let formats: Vec = castable_formats.iter().map(|&f| DXGI_FORMAT(f as i32)).collect(); + let made = match host.device.cast::() { + Ok(device) if !formats.is_empty() => { + let desc1 = desc1_of(&plain); + // SAFETY: a range of the heap for this description; the + // list of formats lives through the call. + unsafe { + device.CreatePlacedResource2(&heap, p.offset(), &desc1, D3D12_BARRIER_LAYOUT_COMMON, None, Some(&formats), &mut texture) + } + .map(|()| 0) + } + _ => { + // SAFETY: as above. + unsafe { + host.device.CreatePlacedResource(&heap, p.offset(), &plain, D3D12_RESOURCE_STATES(initial as i32), None, &mut texture) + } + .map(|()| { + castable_formats.clear(); + initial + }) + } }; + match made { + Ok(state) => { + initial = state; + placement = Some(p); + } + Err(e) => { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::warn!(error = %e, desc = ?d, "a texture not placed in a heap: committed")); + crate::placement::unplace(p); + texture = None; + } + } + } + if texture.is_none() + && !castable_formats.is_empty() + && let Ok(device) = host.device.cast::() + { + let desc1 = desc1_of(&plain); let formats: Vec = castable_formats.iter().map(|&f| DXGI_FORMAT(f as i32)).collect(); // SAFETY: a host description and our out pointer; the list and the // clear value live through the call. @@ -1375,7 +1411,27 @@ fn make_texture(d: &ResourceDesc, state: u32, clear: *const c_void) -> Option windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_DESC1 { + windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_DESC1 { + Dimension: p.Dimension, + Alignment: p.Alignment, + Width: p.Width, + Height: p.Height, + DepthOrArraySize: p.DepthOrArraySize, + MipLevels: p.MipLevels, + Format: p.Format, + SampleDesc: p.SampleDesc, + Layout: p.Layout, + Flags: p.Flags, + SamplerFeedbackMipRegion: Default::default(), + } } /// A texture's console memory and description; `None` for buffers. @@ -1535,6 +1591,9 @@ pub(crate) fn evict_unused() { return; } let over = crate::host::video_memory().map_or(0, |[(used, budget), _]| { + // Free space in the heaps of textures takes the card's memory but + // is not in use: new textures go there first. + let used = used - crate::placement::free_bytes() as f64 / 1e6; if used > BUDGET_HIGH * budget { ((used - BUDGET_LOW * budget) * 1e6) as u64 } else { 0 } }); evict(frame, now_ms(), over); diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 803d00f4dc..437b1fbdd5 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -635,7 +635,16 @@ impl Staging { desc = ?self.layout.desc, "a sampled texture's memory is not committed" ); - return (0, None); + // Never uploaded: zeros, as a committed texture starts (one in + // a heap of textures starts with whatever the range held). + if last.hash.is_some() { + return (0, None); + } + let zeros = vec![0u8; size]; + let every = all(); + let buffer = self.detile(&zeros, &every); + last.hash = buffer.is_some().then(|| blake3::hash(&zeros)); + return (0, buffer.map(|(b, at)| (b, at, every))); } // SAFETY: committed memory of the texture's layout size. let tiled = unsafe { std::slice::from_raw_parts(self.memory, size) }; From 9cc37c5f5b2092b06d6e34c6e4a0ff3dec49c145 Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 14:20:56 +0100 Subject: [PATCH 72/83] GPU: lists wait on memory values; queues hold work until its waits hold What was wrong: Wait32/64BitValueX were ignored and every submission ran when the title made it. Grand Theft Auto VI's four compute queues start each list with a wait for the frame's value of a word that a list on another queue writes at its end (Write64BitValueBottomOfPipeX), and some lists wait again after their first commands. Run light17's trace, one world frame (F = the frame counter, all comparisons GREATER_EQUAL): compute lists (kind 2), 22 queue submissions of one list each: wait [0xd0417fe00 + 16k] >= F at the start, write [+8] = F at the end (0xd0417fe00 .. 0xd04180070); the depth-processing list [w fe10][HBO dispatch, barrier][write fe18 at its end][w fe68, fee8]... graphics lists (kind 0) of 32-33-list submissions wait on words the compute lists write (list 1 after 7-8 commands for [0xd0417ff80], lists 3, 5, 7, ... at their start for [..ff90], [..ffa0], [..ffb0]) So CS_DepthProcessingHBO ran before the character G-buffer it reads, and CS_MaterialTilesInitial classified the head and hair as sky: the white-grey hair blob, faces dark or patched, the erased building bodies, the black shards in the sky and part of the skin's leopard patches. What changed: a wait recorded after commands cuts the title list into a new host list (`list::wait`, `State::cut` replays the fixed-function state and lets the next draw rebind the rest); each queue keeps a FIFO of list segments, Signals and fence Waits (`hold.rs`). The pump runs a queue's head once its waits hold, consecutive runnable segments as one host submission (a piece, its own submission for refreshes, marks, withholding and copy-back), and tests every queue again after each piece until none can move. Order within a queue never changes, only the interleaving across queues. A queue Signal behind held work is delivered after it (its fence is kept alive meanwhile); CPU fence Signals, GetCompletedValue and SetEventOnCompletion, PresentX, every submission and a 2 ms timer (values the title writes from the CPU) pump. D3D12 lets a list be reset as soon as it is submitted, which the title does up to 21 times a frame while its work is held: the held part keeps its own host list, its title list's draw state (dynamic descriptor slots, title-memory page table) and 0x4a0 memory, freed after it ran; host lists back from a queue are reused. Counted shortcuts (`shortcut:`): a head held 10 s runs anyway (valve); an unknown comparison holds; CopyPageMappingsBatchX and PresentX do not wait behind held work. The frame line (when work waited or is held): submissions, pieces, segments, cuts, early resets, segments that waited and what released them, the pump's own time, the title's fence-event waits, what is held at the present with the unmet waits. Evidence: run light18 (240 s, survived): per world frame 16-42 title submissions, pieces = submissions + 1, 188-266 segments, 0-11 cuts, 5-10 segments waited (55-1060 ms, every one released by a later submission); held at the present 0, valve 0, unknown comparisons 0, page mappings with work held 0. Hair whole against the sky, buildings whole, sky clean, skin clean, every face present and lit (13 faces in 8 close shots; act3 2700, without this, has a dark patch over the same woman's face). light19 (the debug layer, 240 s; median per world frame 30 submissions, 31 pieces, 236 segments, 9 waited; pump 1.1 ms a frame; no fence event left pending) and light20 (240 s, with the stale-upload fix now in main: 30, 31, 241, 9; pump 1.8 ms) survived; held at the present, valve, unknown comparisons and page mappings with work held 0 in all three. The debug layer's resource-state errors of light19 are on main alone too (light21, same kinds and rate): not from the new order. Tests: hold::tests (comparisons, a wait across queues, a wait that holds defers nothing, chained waits across two queues, order kept, a Signal after held work, a fence wait, work held at the frame's end, unknown comparisons, the valve) and the GPU test resource::tests::a_list_waiting_for_another_queues_write_reads_what_it_wrote (a compute list cut at its wait and reset while held reads back the plain texture the graphics list fills, as that list left it; on the old code it reads zeros). Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/draw.rs | 105 +++++-- crates/victory-gpu/src/fence.rs | 55 +++- crates/victory-gpu/src/hold.rs | 442 +++++++++++++++++++++++++++++ crates/victory-gpu/src/host.rs | 35 +++ crates/victory-gpu/src/lib.rs | 1 + crates/victory-gpu/src/list.rs | 249 +++++++++++++--- crates/victory-gpu/src/object.rs | 6 + crates/victory-gpu/src/queue.rs | 293 +++++++++++++++++-- crates/victory-gpu/src/resource.rs | 100 +++++++ 9 files changed, 1205 insertions(+), 81 deletions(-) create mode 100644 crates/victory-gpu/src/hold.rs diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 7e2059af42..4a3aa3840b 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -89,6 +89,21 @@ pub(crate) struct State { /// slot, end): taken [`ROOT_VIEW_RUN`] at a time, so that single slots /// do not break up the runs fresh tables need. root_run: (usize, u32, u32), + /// What was set straight onto the host list, for the next segment of + /// the list ([`State::cut`]). + fixed: Fixed, +} + +/// Fixed-function state the title set, as it set it. +#[derive(Default)] +struct Fixed { + viewports: Option>, + scissors: Option>, + blend_factor: Option>, + stencil_ref: Option, + /// Render target and depth view handles. + targets: Option<(Vec, u64)>, + topology: bool, } impl Drop for State { @@ -230,6 +245,7 @@ impl State { /// [`crate::primitive`]). pub(crate) fn set_topology(&mut self, list: &HostList, topology: u32) { self.topology = topology; + self.fixed.topology = true; let host = match topology { RECTANGLES => 4, TRIANGLE_FAN | LINE_LOOP | QUADS | QUAD_STRIP => { @@ -249,6 +265,73 @@ impl State { self.pipeline = pipeline as usize; } + /// Fixed-function state, straight onto the host list (and kept for the + /// list's next segment). + pub(crate) fn viewports(&mut self, list: &HostList, viewports: &[D3D12_VIEWPORT]) { + self.fixed.viewports = Some(viewports.to_vec()); + // SAFETY: an open list. + unsafe { list.list.RSSetViewports(viewports) }; + } + + pub(crate) fn scissors(&mut self, list: &HostList, rects: &[RECT]) { + self.fixed.scissors = Some(rects.to_vec()); + // SAFETY: an open list. + unsafe { list.list.RSSetScissorRects(rects) }; + } + + pub(crate) fn blend_factor(&mut self, list: &HostList, factor: Option<&[f32; 4]>) { + self.fixed.blend_factor = Some(factor.copied()); + // SAFETY: an open list. + unsafe { list.list.OMSetBlendFactor(factor) }; + } + + pub(crate) fn stencil_ref(&mut self, list: &HostList, reference: u32) { + self.fixed.stencil_ref = Some(reference); + // SAFETY: an open list. + unsafe { list.list.OMSetStencilRef(reference) }; + } + + /// The title list goes on in a fresh host list (a segment after a wait, + /// `crate::list`): the state it set is given to `list` again. + /// + /// Replayed: topology, viewports, scissors, blend factor, stencil + /// reference, render targets and depth (set at once); heaps, root + /// signatures, pipelines, root arguments, vertex and index buffers are + /// set by the next draw or dispatch from what this state holds (the + /// host caches are cleared). Made again in the new segment, so their + /// submission-time work (refreshes, uploads) runs with it: fresh tables, + /// root views and the title-memory page table. Not replayed, as nothing + /// of it is on the host list: depth bounds and shading rate (ignored), + /// queries (resolved with plain values), the 0x4a0 upload memory (the + /// title list's own), texture states and twins (each segment has its + /// own, made from the real states at its submission). Clears and copies + /// are commands, recorded once in the segment they belong to. + pub(crate) fn cut(&mut self, list: &HostList) { + self.host_state_lost(); + self.fresh_tables.clear(); + self.root_slots.clear(); + self.memory = None; + let fixed = std::mem::take(&mut self.fixed); + if fixed.topology { + self.set_topology(list, self.topology); + } + if let Some(v) = &fixed.viewports { + self.viewports(list, v); + } + if let Some(r) = &fixed.scissors { + self.scissors(list, r); + } + if let Some(f) = fixed.blend_factor { + self.blend_factor(list, f.as_ref()); + } + if let Some(s) = fixed.stencil_ref { + self.stencil_ref(list, s); + } + if let Some((targets, depth)) = &fixed.targets { + self.set_targets(list, targets, *depth); + } + } + /// Others recorded into the host list (`crate::external`): its heaps, /// root signatures and pipeline are set again before the next draw or /// dispatch. @@ -318,6 +401,7 @@ impl State { /// Render targets and depth, set on the host list at once. pub(crate) fn set_targets(&mut self, list: &HostList, handles: &[u64], depth: u64) { + self.fixed.targets = Some((handles.to_vec(), depth)); let Some(host) = crate::host::host() else { return; }; @@ -1868,27 +1952,6 @@ const LINE_LOOP: u32 = 18; const QUADS: u32 = 19; const QUAD_STRIP: u32 = 20; -/// Fixed-function state, straight onto the host list. -pub(crate) fn viewports(list: &HostList, viewports: &[D3D12_VIEWPORT]) { - // SAFETY: an open list. - unsafe { list.list.RSSetViewports(viewports) }; -} - -pub(crate) fn scissors(list: &HostList, rects: &[RECT]) { - // SAFETY: an open list. - unsafe { list.list.RSSetScissorRects(rects) }; -} - -pub(crate) fn blend_factor(list: &HostList, factor: Option<&[f32; 4]>) { - // SAFETY: an open list. - unsafe { list.list.OMSetBlendFactor(factor) }; -} - -pub(crate) fn stencil_ref(list: &HostList, reference: u32) { - // SAFETY: an open list. - unsafe { list.list.OMSetStencilRef(reference) }; -} - #[cfg(test)] mod tests { use super::*; diff --git a/crates/victory-gpu/src/fence.rs b/crates/victory-gpu/src/fence.rs index 64f9de41ee..00325b17f9 100644 --- a/crates/victory-gpu/src/fence.rs +++ b/crates/victory-gpu/src/fence.rs @@ -1,5 +1,5 @@ -//! Fences: a 64-bit value and the events waiting for it. Nothing runs on a -//! GPU yet, so only signals (the title's, later our queues') move one. +//! Fences: a 64-bit value and the events waiting for it, moved by the +//! title's Signals and its queues' (once the work before them has run). #![allow(clippy::not_unsafe_ptr_arg_deref)] use std::ffi::c_void; @@ -35,8 +35,9 @@ struct Fence { /// address. value: AtomicU64, flags: u32, - /// Events to set once the value reaches theirs (handles as integers). - waiters: Mutex>, + /// Events to set once the value reaches theirs (handles as integers), + /// and since when. + waiters: Mutex>, } fn fence<'a>(this: This) -> &'a Fence { @@ -83,9 +84,12 @@ extern "system" fn release(this: This) -> u32 { object::release_boxed::(this) } extern "system" fn completed(this: This) -> u64 { + // A title polling for a value: held work that may run now does first. + crate::queue::pump_held_if_free(crate::queue::Why::Fence); fence(this).value.load(Ordering::Acquire) } extern "system" fn set_event_on_completion(this: This, value: u64, event: *mut c_void) -> HRESULT { + crate::queue::pump_held_if_free(crate::queue::Why::Fence); let fence = fence(this); let mut waiters = fence.waiters.lock().unwrap_or_else(|e| e.into_inner()); if fence.value.load(Ordering::Acquire) >= value { @@ -100,23 +104,60 @@ extern "system" fn set_event_on_completion(this: This, value: u64, event: *mut c tracing::warn!(value, "blocking fence wait not implemented"); return E_NOTIMPL; } - waiters.push((value, event as usize)); + waiters.push((value, event as usize, std::time::Instant::now())); S_OK } -pub(crate) extern "system" fn signal(this: This, value: u64) -> HRESULT { +/// The title's Signal from the CPU: what queues hold behind a Wait for it +/// may run now (`crate::hold`). +extern "system" fn signal(this: This, value: u64) -> HRESULT { + let hr = set(this, value); + crate::queue::pump_held(crate::queue::Why::Fence); + hr +} + +/// Moves a fence to `value` and wakes the events waiting for it (a queue's +/// Signal, when the work before it has run). +pub(crate) fn set(this: This, value: u64) -> HRESULT { let fence = fence(this); let mut waiters = fence.waiters.lock().unwrap_or_else(|e| e.into_inner()); fence.value.store(value, Ordering::Release); - waiters.retain(|&(wanted, event)| { + waiters.retain(|&(wanted, event, since)| { let reached = wanted <= value; if reached { set_event(event); + WAITED.0.fetch_add(1, Ordering::Relaxed); + WAITED.1.fetch_add(since.elapsed().as_micros() as u64, Ordering::Relaxed); } !reached }); S_OK } +/// Events the title waited on for a fence value, and their summed waits in +/// microseconds (the held-work frame line: work held back shows here as the +/// title's own waits). +static WAITED: (AtomicU64, AtomicU64) = (AtomicU64::new(0), AtomicU64::new(0)); + +/// Events set since the last call and how long they waited, summed. +pub(crate) fn take_waited() -> (u64, std::time::Duration) { + let n = WAITED.0.swap(0, Ordering::Relaxed); + (n, std::time::Duration::from_micros(WAITED.1.swap(0, Ordering::Relaxed))) +} + +/// A fence's value. +pub(crate) fn value(this: This) -> u64 { + fence(this).value.load(Ordering::Acquire) +} + +/// Keeps a fence alive while a queue holds a Signal of it, until +/// [`let_go`]. +pub(crate) fn keep(this: This) { + object::add_ref(this); +} +pub(crate) fn let_go(this: This) { + release(this); +} + extern "system" fn creation_flags(this: This) -> u32 { fence(this).flags } diff --git a/crates/victory-gpu/src/hold.rs b/crates/victory-gpu/src/hold.rs new file mode 100644 index 0000000000..efe249c737 --- /dev/null +++ b/crates/victory-gpu/src/hold.rs @@ -0,0 +1,442 @@ +//! Work a queue holds back (decision 0007, "Queues wait on memory values"). +//! +//! The console's lists wait on memory values (`Wait32BitValueX`, +//! `Wait64BitValueX`) that lists on other queues write at their end +//! (`Write32/64BitValueBottomOfPipeX`): Grand Theft Auto VI's four compute +//! queues start each list with a wait for the frame's value of a word that +//! a graphics list writes, and some lists wait again after their first +//! commands. Our submissions run to completion when the title makes them, +//! so a queue here is a FIFO of what the title submitted to it: segments of +//! lists (a list is cut where it waits after commands, `crate::list`), its +//! Signals and its fence Waits, in their order. The head of a queue runs +//! once its waits hold; consecutive heads that may run go to the host GPU +//! together (a piece); after every piece the heads of all queues are tested +//! again until none can move. Order within a queue never changes, only the +//! interleaving across queues. + +use std::collections::VecDeque; +use std::time::{Duration, Instant}; + +/// A wait for a memory value, as a list records it: the value at `address` +/// (`bytes` 4 or 8, the 32-bit form masked) compared with `reference` by a +/// D3D12 comparison function. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct ValueWait { + pub(crate) address: u64, + pub(crate) bytes: u8, + pub(crate) comparison: u32, + pub(crate) reference: u64, + pub(crate) mask: u64, +} + +/// D3D12 comparison functions (`D3D12_COMPARISON_FUNC`). +const NEVER: u32 = 1; +const LESS: u32 = 2; +const EQUAL: u32 = 3; +const LESS_EQUAL: u32 = 4; +const GREATER: u32 = 5; +const NOT_EQUAL: u32 = 6; +const GREATER_EQUAL: u32 = 7; +const ALWAYS: u32 = 8; + +impl ValueWait { + /// Whether it holds with `read` giving the memory's value: `None` for a + /// comparison we do not know (counted by the caller, taken as holding) + /// and for memory that cannot be read (taken as not holding). + pub(crate) fn holds(&self, read: &dyn Fn(u64, u8) -> Option) -> Option { + if !(NEVER..=ALWAYS).contains(&self.comparison) { + return None; + } + let value = read(self.address, self.bytes)? & self.mask; + let reference = self.reference; + Some(match self.comparison { + NEVER => false, + LESS => value < reference, + EQUAL => value == reference, + LESS_EQUAL => value <= reference, + GREATER => value > reference, + NOT_EQUAL => value != reference, + GREATER_EQUAL => value >= reference, + _ => true, + }) + } +} + +/// What a queue holds, in its order. +pub(crate) enum Item { + /// A list segment and the waits at its start. + Segment(S, Vec), + /// A fence Signal: the fence and its value. + Signal(usize, u64), + /// A fence Wait: until the fence reaches the value. + FenceWait(usize, u64), +} + +/// What a pump did, for the frame's accounting. +#[derive(Default, Debug, PartialEq, Eq)] +pub(crate) struct Pumped { + /// Pieces given to the host GPU, and the segments in them. + pub(crate) pieces: u32, + pub(crate) segments: u32, + /// Of those, segments that had waited (not run when submitted): their + /// queue and how long. + pub(crate) waited: Vec<(usize, Duration)>, + /// Waits with a comparison we do not know (taken as holding). + pub(crate) unknown: u32, +} + +/// Every queue's held work. +pub(crate) struct Held { + queues: Vec<(usize, Fifo)>, +} + +/// A queue's items, each with when it was pushed and whether it is fresh +/// (not yet found waiting). +type Fifo = VecDeque<(Item, Instant, bool)>; + +impl Default for Held { + fn default() -> Self { + Self::new() + } +} + +impl Held { + pub(crate) const fn new() -> Self { + Held { queues: Vec::new() } + } +} + +/// What the pump needs from the outside world. +pub(crate) struct World<'a, S> { + /// A memory value (address, bytes). + pub(crate) read: &'a dyn Fn(u64, u8) -> Option, + /// A fence's value. + pub(crate) fence: &'a dyn Fn(usize) -> u64, + /// Runs a piece (a queue, its segments in order) to completion, the + /// bottom-of-pipe writes included. + pub(crate) run: &'a mut dyn FnMut(usize, Vec), + /// Signals a fence. + pub(crate) signal: &'a mut dyn FnMut(usize, u64), +} + +impl Held { + /// Appends `item` to `queue`'s FIFO, marked fresh: whether it waited is + /// decided by its first test. + pub(crate) fn push(&mut self, queue: usize, item: Item) { + let now = Instant::now(); + match self.queues.iter_mut().find(|(q, _)| *q == queue) { + Some((_, items)) => items.push_back((item, now, true)), + None => self.queues.push((queue, VecDeque::from([(item, now, true)]))), + } + } + + /// Runs every queue's heads that may run, until none can. + pub(crate) fn pump(&mut self, w: &mut World) -> Pumped { + let mut done = Pumped::default(); + loop { + let mut moved = false; + for (queue, items) in &mut self.queues { + let mut piece = Vec::new(); + loop { + let ready = match items.front_mut() { + None => false, + Some((Item::Segment(_, waits), since, fresh)) => { + let mut ok = true; + for wait in waits.iter() { + match wait.holds(w.read) { + Some(true) => {} + Some(false) => ok = false, + None => done.unknown += 1, + } + } + if !ok { + *fresh = false; + } else if !*fresh { + done.waited.push((*queue, since.elapsed())); + } + ok + } + // A Signal or Wait keeps its place: the piece before + // it runs first. + Some((Item::Signal(..), ..)) => { + if !piece.is_empty() { + (w.run)(*queue, std::mem::take(&mut piece)); + done.pieces += 1; + } + true + } + Some((Item::FenceWait(fence, value), _, fresh)) => { + let ok = (w.fence)(*fence) >= *value; + if !ok { + *fresh = false; + } + ok + } + }; + if !ready { + break; + } + moved = true; + match items.pop_front().map(|(item, ..)| item) { + Some(Item::Segment(s, _)) => { + piece.push(s); + done.segments += 1; + } + Some(Item::Signal(fence, value)) => (w.signal)(fence, value), + Some(Item::FenceWait(..)) | None => {} + } + } + if !piece.is_empty() { + (w.run)(*queue, piece); + done.pieces += 1; + } + } + if !moved { + break; + } + } + self.queues.retain(|(_, items)| !items.is_empty()); + done + } + + /// The queues still holding work: (queue, items, how long the head + /// waited, the head's waits that do not hold). + pub(crate) fn blocked(&self, read: &dyn Fn(u64, u8) -> Option) -> Vec<(usize, usize, Duration, Vec)> { + self.queues + .iter() + .filter_map(|(q, items)| { + let (head, since, _) = items.front()?; + let unmet = match head { + Item::Segment(_, waits) => waits.iter().filter(|w| w.holds(read) == Some(false)).copied().collect(), + _ => Vec::new(), + }; + Some((*q, items.len(), since.elapsed(), unmet)) + }) + .collect() + } + + /// Whether no queue holds anything. + pub(crate) fn is_empty(&self) -> bool { + self.queues.is_empty() + } + + /// Whether `queue` holds anything. + pub(crate) fn holds_work(&self, queue: usize) -> bool { + self.queues.iter().any(|(q, items)| *q == queue && !items.is_empty()) + } + + /// Releases work held longer than `limit` at the heads of blocked + /// queues, as if its waits held: the count of segments forced. + // shortcut: a safety valve against waits nothing will satisfy (a write + // we do not emulate), which would hold the title's fences back until + // its 30 s watchdog ends the run; remove once runs show it never fires. + pub(crate) fn force_older_than(&mut self, limit: Duration) -> Vec<(usize, Vec)> { + let mut forced = Vec::new(); + for (q, items) in &mut self.queues { + if let Some((Item::Segment(_, waits), since, _)) = items.front_mut() + && since.elapsed() >= limit + { + forced.push((*q, std::mem::take(waits))); + } + } + forced + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::cell::RefCell; + use std::collections::HashMap; + + /// Memory, fences and a log of what ran, for a recording executor. + #[derive(Default)] + struct Fake { + memory: HashMap, + fences: HashMap, + log: Vec, + /// Bottom-of-pipe writes of each segment: (address, value). + writes: HashMap<&'static str, Vec<(u64, u64)>>, + } + + fn ge(address: u64, reference: u64) -> ValueWait { + ValueWait { address, bytes: 8, comparison: GREATER_EQUAL, reference, mask: u64::MAX } + } + + fn pump(held: &mut Held<&'static str>, fake: &RefCell) -> Pumped { + let read = |a: u64, _| Some(*fake.borrow().memory.get(&a).unwrap_or(&0)); + let fence = |f: usize| *fake.borrow().fences.get(&f).unwrap_or(&0); + let mut run = |q: usize, segments: Vec<&'static str>| { + let mut f = fake.borrow_mut(); + for s in &segments { + for (a, v) in f.writes.get(s).cloned().unwrap_or_default() { + f.memory.insert(a, v); + } + } + f.log.push(format!("q{q}: {}", segments.join(" "))); + }; + let mut signal = |fence: usize, value: u64| { + let mut f = fake.borrow_mut(); + f.fences.insert(fence, value); + f.log.push(format!("signal {fence} {value}")); + }; + held.pump(&mut World { read: &read, fence: &fence, run: &mut run, signal: &mut signal }) + } + + #[test] + fn comparisons_test_the_masked_value() { + let read = |_, _| Some(0x1_0000_0005); + let w = |comparison, reference| ValueWait { address: 8, bytes: 4, comparison, reference, mask: 0xffff_ffff }; + let expect = [(NEVER, false), (LESS, false), (EQUAL, true), (LESS_EQUAL, true), (GREATER, false), (NOT_EQUAL, false), (GREATER_EQUAL, true), (ALWAYS, true)]; + for (cmp, holds) in expect { + assert_eq!(w(cmp, 5).holds(&read), Some(holds), "comparison {cmp}"); + } + assert_eq!(w(LESS, 6).holds(&read), Some(true)); + assert_eq!(w(GREATER, 4).holds(&read), Some(true)); + assert_eq!(w(0, 5).holds(&read), None, "unknown comparison"); + assert_eq!(w(9, 5).holds(&read), None); + assert_eq!(w(EQUAL, 5).holds(&|_, _| None), None, "unreadable memory"); + } + + /// The compute queue's list waits for a value the graphics queue's list + /// writes at its end: it runs after it. + #[test] + fn a_list_waits_for_another_queues_write() { + let fake = RefCell::new(Fake::default()); + fake.borrow_mut().writes.insert("draw", vec![(0x100, 7)]); + let mut held = Held::default(); + held.push(2, Item::Segment("depth", vec![ge(0x100, 7)])); + let p = pump(&mut held, &fake); + assert_eq!((p.pieces, p.segments), (0, 0), "held: the value is not there"); + assert!(held.holds_work(2)); + held.push(1, Item::Segment("draw", vec![])); + let p = pump(&mut held, &fake); + assert_eq!(fake.borrow().log, ["q1: draw", "q2: depth"]); + assert_eq!((p.pieces, p.segments, p.waited.len()), (2, 2, 1)); + assert_eq!(p.waited[0].0, 2); + assert!(!held.holds_work(2)); + } + + #[test] + fn a_wait_that_holds_defers_nothing() { + let fake = RefCell::new(Fake::default()); + fake.borrow_mut().memory.insert(0x100, 9); + let mut held = Held::default(); + held.push(2, Item::Segment("a", vec![ge(0x100, 7)])); + held.push(2, Item::Segment("b", vec![])); + let p = pump(&mut held, &fake); + assert_eq!(fake.borrow().log, ["q2: a b"], "one piece"); + assert_eq!((p.pieces, p.waited.len()), (1, 0)); + } + + /// A list's second segment waits for a value the other queue writes + /// after reading what the first segment wrote: the cut is what lets + /// both make progress. + #[test] + fn chained_waits_across_two_queues() { + let fake = RefCell::new(Fake::default()); + { + let mut f = fake.borrow_mut(); + f.writes.insert("c1", vec![(0x10, 1)]); + f.writes.insert("g1", vec![(0x20, 1)]); + f.writes.insert("c2", vec![(0x30, 1)]); + } + let mut held = Held::default(); + // Compute: [wait 0x08][c1, writes 0x10][wait 0x20][c2, writes 0x30]. + held.push(2, Item::Segment("c1", vec![ge(0x08, 1)])); + held.push(2, Item::Segment("c2", vec![ge(0x20, 1)])); + // Graphics: [g0, writes 0x08], [wait 0x10][g1, writes 0x20], [wait 0x30][g2]. + held.push(1, Item::Segment("g0", vec![])); + fake.borrow_mut().writes.insert("g0", vec![(0x08, 1)]); + held.push(1, Item::Segment("g1", vec![ge(0x10, 1)])); + held.push(1, Item::Segment("g2", vec![ge(0x30, 1)])); + pump(&mut held, &fake); + assert_eq!(fake.borrow().log, ["q1: g0", "q2: c1", "q1: g1", "q2: c2", "q1: g2"]); + assert!(held.blocked(&|_, _| Some(0)).is_empty()); + } + + /// Order within a queue never changes: a later segment whose waits hold + /// does not pass a held one. + #[test] + fn a_queue_keeps_its_order() { + let fake = RefCell::new(Fake::default()); + let mut held = Held::default(); + held.push(2, Item::Segment("first", vec![ge(0x100, 1)])); + held.push(2, Item::Segment("second", vec![])); + pump(&mut held, &fake); + assert!(fake.borrow().log.is_empty()); + fake.borrow_mut().memory.insert(0x100, 1); + pump(&mut held, &fake); + assert_eq!(fake.borrow().log, ["q2: first second"]); + } + + /// A Signal behind held work is delivered after it: the title's fence + /// (and its memory) does not move before the work ran. + #[test] + fn a_signal_waits_for_the_work_before_it() { + let fake = RefCell::new(Fake::default()); + let mut held = Held::default(); + held.push(2, Item::Segment("work", vec![ge(0x100, 1)])); + held.push(2, Item::Signal(5, 3)); + held.push(2, Item::Segment("after", vec![])); + pump(&mut held, &fake); + assert_eq!(fake.borrow().fences.get(&5), None, "not signalled yet"); + fake.borrow_mut().memory.insert(0x100, 1); + pump(&mut held, &fake); + assert_eq!(fake.borrow().log, ["q2: work", "signal 5 3", "q2: after"]); + } + + #[test] + fn a_fence_wait_holds_its_queue() { + let fake = RefCell::new(Fake::default()); + let mut held = Held::default(); + held.push(2, Item::FenceWait(5, 2)); + held.push(2, Item::Segment("after", vec![])); + pump(&mut held, &fake); + assert!(fake.borrow().log.is_empty()); + held.push(1, Item::Signal(5, 2)); + pump(&mut held, &fake); + assert_eq!(fake.borrow().log, ["signal 5 2", "q2: after"]); + } + + /// The frame ends with work held: it stays held (and is reported), and + /// the next frame's write releases it. + #[test] + fn work_held_at_the_frames_end_stays_held() { + let fake = RefCell::new(Fake::default()); + let mut held = Held::default(); + held.push(2, Item::Segment("late", vec![ge(0x100, 2)])); + held.push(2, Item::Signal(5, 1)); + pump(&mut held, &fake); + let read = |a: u64, _| Some(*fake.borrow().memory.get(&a).unwrap_or(&0)); + let blocked = held.blocked(&read); + assert_eq!(blocked.len(), 1); + assert_eq!((blocked[0].0, blocked[0].1, blocked[0].3.clone()), (2, 2, vec![ge(0x100, 2)])); + fake.borrow_mut().memory.insert(0x100, 2); + let p = pump(&mut held, &fake); + assert_eq!(p.waited.len(), 1); + assert_eq!(fake.borrow().log, ["q2: late", "signal 5 1"]); + } + + #[test] + fn unknown_comparisons_are_counted_and_do_not_hold_work() { + let fake = RefCell::new(Fake::default()); + let mut held = Held::default(); + let odd = ValueWait { address: 0x100, bytes: 4, comparison: 12, reference: 1, mask: 0xffff_ffff }; + held.push(2, Item::Segment("odd", vec![odd])); + let p = pump(&mut held, &fake); + assert_eq!((p.segments, p.unknown), (1, 1)); + } + + #[test] + fn the_valve_releases_only_old_heads() { + let fake = RefCell::new(Fake::default()); + let mut held = Held::default(); + held.push(2, Item::Segment("stuck", vec![ge(0x100, 1)])); + assert!(held.force_older_than(Duration::from_secs(60)).is_empty()); + let forced = held.force_older_than(Duration::ZERO); + assert_eq!(forced, [(2, vec![ge(0x100, 1)])]); + pump(&mut held, &fake); + assert_eq!(fake.borrow().log, ["q2: stuck"]); + } +} diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 99d63d904c..3e2039e0bf 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -786,6 +786,13 @@ pub(crate) struct HostList { stamps: OnceLock>, } +// SAFETY: D3D12 objects are free-threaded; a host list is recorded by the +// title list's one recording thread, then run by one submission at a time +// (the queues hold it between, `crate::hold`). +unsafe impl Send for HostList {} +// SAFETY: as above. +unsafe impl Sync for HostList {} + /// Timestamps per list (diagnostics); commands past them are not timed. #[cfg(feature = "diagnostics")] const STAMPS: u32 = 4096; @@ -952,6 +959,10 @@ struct Deferred { /// Bottom-of-pipe writes, done once the list has run: address, what, /// bytes. writes: Vec<(usize, crate::queue::Written, usize)>, + /// The memory values the list waits for before it starts (a list the + /// title records with a wait after commands is cut there, + /// `crate::list`). + waits: Vec, /// Whether a step zeroes the indirect-work budget. budget_zeroed: bool, /// Work done once the list has run, before the bottom-of-pipe writes @@ -2054,6 +2065,30 @@ impl HostList { self.deferred().writes.push((dst as usize, what, bytes)); } + /// A memory value the list waits for before it starts. + pub(crate) fn defer_wait(&self, wait: crate::hold::ValueWait) { + self.deferred().waits.push(wait); + } + + /// The memory values the list waits for before it starts. + pub(crate) fn waits(&self) -> Vec { + self.deferred().waits.clone() + } + + /// Whether nothing has been recorded since the list was made or reset + /// that a wait recorded now would have to follow: no work, texture + /// use, bottom-of-pipe write or pipeline (state settings alone carry + /// over). + pub(crate) fn is_empty(&self) -> bool { + let d = self.deferred(); + let deferred_empty = d.copies.is_empty() && d.uploads.is_empty() && d.writes.is_empty() && d.after.is_empty() && d.missed.is_empty(); + drop(d); + deferred_empty + && self.states.lock().unwrap_or_else(|e| e.into_inner()).is_empty() + && self.twins.lock().unwrap_or_else(|e| e.into_inner()).is_empty() + && self.pipelines.lock().unwrap_or_else(|e| e.into_inner()).is_empty() + } + /// A mapped upload buffer of `size` bytes, alive until the list is /// reset. /// diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index d4d97cce31..9e88db5c40 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -32,6 +32,7 @@ pub mod dxgi; pub mod external; pub mod fence; pub mod frame; +mod hold; #[cfg(windows)] mod host; #[cfg(windows)] diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 1f4ee204a7..a16d61ca8e 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -115,8 +115,15 @@ struct List { /// [`allocate_upload`], kept until the list is reset; the host list the /// calls record into (decision 0007), and the draw state the title set. uploads: std::sync::Mutex>, + /// The host lists the calls record into, in order: one, and one more + /// for every wait the title records after commands ([`wait`]). Shared + /// with the queues that hold them until their waits hold + /// (`crate::hold`), so they outlive a list the title releases first. #[cfg(windows)] - host: Option, + hosts: std::sync::Mutex>>, + /// Which of them the calls record into. + #[cfg(windows)] + segment: std::sync::atomic::AtomicUsize, #[cfg(windows)] state: std::sync::Mutex, } @@ -133,14 +140,167 @@ pub(crate) fn with_state(this: This, f: impl FnOnce(&crate::host::HostList, &mut f(list, &mut state.lock().unwrap_or_else(|e| e.into_inner())); } -/// The host list behind a title list, if there is a host GPU. +/// The host list a title list's calls record into (its current segment), +/// if there is a host GPU. #[cfg(windows)] pub(crate) fn host_list<'a>(this: This) -> Option<&'a crate::host::HostList> { if this.is_null() { return None; } // SAFETY: the title passes one of our lists. - unsafe { (*this.cast::()).host.as_ref() } + let list = unsafe { &*this.cast::() }; + let k = list.segment.load(std::sync::atomic::Ordering::Relaxed); + let hosts = list.hosts.lock().unwrap_or_else(|e| e.into_inner()); + let current: *const crate::host::HostList = std::sync::Arc::as_ptr(hosts.get(k)?); + // SAFETY: the list holds this host list until it is reset or released + // (an `Arc` does not move it), and the title records into a list from + // one thread at a time. + Some(unsafe { &*current }) +} + +/// A title list's host lists, in order: what a submission of it runs. +#[cfg(windows)] +pub(crate) fn segments(this: This) -> Vec> { + if this.is_null() { + return Vec::new(); + } + // SAFETY: the title passes one of our lists. + let list = unsafe { &*this.cast::() }; + let k = list.segment.load(std::sync::atomic::Ordering::Relaxed); + let hosts = list.hosts.lock().unwrap_or_else(|e| e.into_inner()); + hosts.iter().take(k + 1).cloned().collect() +} + +/// Waits recorded after commands: the title list goes on in a new host +/// list, which runs once the wait holds. +static CUTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// Lists reset or released while a queue still held some of their host +/// lists: D3D12 lets a list be reset as soon as it is submitted (Grand +/// Theft Auto VI does, 0-21 times a world frame). +static EARLY_RESETS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// Cuts and early resets since the last call (the frame line). +pub(crate) fn take_cuts() -> (u64, u64) { + use std::sync::atomic::Ordering::Relaxed; + (CUTS.swap(0, Relaxed), EARLY_RESETS.swap(0, Relaxed)) +} + +/// `Wait32BitValueX(address, comparison, reference, mask, flags)` and +/// `Wait64BitValueX(address, comparison, reference, flags)`: the GPU waits +/// until the value compares true. Recorded at the start of the current host +/// list, or, after commands, at the start of a new one the rest of the +/// title list records into (the queue runs each once its waits hold, +/// `crate::hold`); bottom-of-pipe writes recorded before it land when the +/// part before it has run. +extern "system" fn wait32(this: This, address: u64, comparison: u32, reference: u32, mask: u32, _flags: u32) { + wait(this, crate::hold::ValueWait { address, bytes: 4, comparison, reference: u64::from(reference), mask: u64::from(mask) }); +} +pub(crate) extern "system" fn wait64(this: This, address: u64, comparison: u32, reference: u64, _flags: u32) { + wait(this, crate::hold::ValueWait { address, bytes: 8, comparison, reference, mask: u64::MAX }); +} + +fn wait(this: This, wait: crate::hold::ValueWait) { + #[cfg(windows)] + { + let Some(current) = host_list(this) else { return }; + if !current.is_empty() { + let Some(next) = next_segment(this) else { return }; + CUTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + current.close(); + // SAFETY: the title passes one of our lists. + let list = unsafe { &*this.cast::() }; + list.state.lock().unwrap_or_else(|e| e.into_inner()).cut(next); + next.defer_wait(wait); + return; + } + current.defer_wait(wait); + } + #[cfg(not(windows))] + let _ = (this, wait); +} + +/// Moves a title list's recording on to its next host list (made, or one +/// it held since an earlier recording, reset then): that host list. +#[cfg(windows)] +fn next_segment<'a>(this: This) -> Option<&'a crate::host::HostList> { + // SAFETY: the title passes one of our lists. + let list = unsafe { &*this.cast::() }; + let k = list.segment.load(std::sync::atomic::Ordering::Relaxed) + 1; + let mut hosts = list.hosts.lock().unwrap_or_else(|e| e.into_inner()); + if hosts.len() <= k { + let made = crate::host::host()?.new_list().ok()?; + hosts.push(std::sync::Arc::new(made)); + } + list.segment.store(k, std::sync::atomic::Ordering::Relaxed); + let next: *const crate::host::HostList = std::sync::Arc::as_ptr(&hosts[k]); + drop(hosts); + // SAFETY: as in `host_list`. + Some(unsafe { &*next }) +} + +/// After the title list's last submission: its host lists start again, +/// and a host list a queue still holds (`crate::hold`) is left to the +/// queue and replaced. The last one left so, which should keep what the +/// title list owned. +#[cfg(windows)] +fn restart(this: This) -> Option> { + // SAFETY: the title passes one of our lists. + let list = unsafe { &*this.cast::() }; + let used = list.segment.swap(0, std::sync::atomic::Ordering::Relaxed); + let mut hosts = list.hosts.lock().unwrap_or_else(|e| e.into_inner()); + let mut left = None; + for (k, h) in hosts.iter_mut().enumerate() { + if std::sync::Arc::strong_count(h) > 1 { + EARLY_RESETS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + tracing::debug!(segment = k, "a list reset while a queue still holds part of it: that part keeps its own host list"); + let spare = SPARE.lock().unwrap_or_else(|e| e.into_inner()).pop(); + match spare.map(Ok).or_else(|| crate::host::host().map(|host| host.new_list())) { + Some(Ok(fresh)) => left = Some(std::mem::replace(h, std::sync::Arc::new(fresh))), + _ => continue, + } + } else if k <= used { + h.reset(); + } + } + left +} + +/// Host lists [`restart`] left to a queue, back once they ran: the next +/// ones it hands out (a host list and its allocators are not free to make; +/// Grand Theft Auto VI resets up to 21 lists a frame while they are held). +#[cfg(windows)] +static SPARE: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + +/// A host list a queue has run: one no title list holds any more is reset +/// and kept for [`restart`]. +#[cfg(windows)] +pub(crate) fn recycle(list: std::sync::Arc) { + const KEPT: usize = 64; + if let Ok(list) = std::sync::Arc::try_unwrap(list) { + list.reset(); + let mut spare = SPARE.lock().unwrap_or_else(|e| e.into_inner()); + if spare.len() < KEPT { + spare.push(list); + } + } +} + +/// What a title list owned that the host list a queue still holds, if any, +/// may read: its upload memory (list 0x4a0) and its draw state's dynamic +/// descriptor slots and title-memory page table. Freed once that host list +/// (the list's last held one, so the last to run) is gone. +#[cfg(windows)] +fn leave(to: Option>, uploads: Vec, state: crate::draw::State) { + struct Kept(#[allow(dead_code)] Vec, #[allow(dead_code)] crate::draw::State); + // SAFETY: only dropped, with the host list, after it has run. + unsafe impl Send for Kept {} + if let Some(held) = to { + let kept = Kept(uploads, state); + held.defer_after(move || { + let _ = &kept; + }); + } } pub(crate) extern "system" fn create_allocator( @@ -222,13 +382,20 @@ fn new_list( newer: [0; 256], uploads: Default::default(), #[cfg(windows)] - host: crate::host::host().and_then(|h| match h.new_list() { - Ok(list) => Some(list), - Err(e) => { - tracing::warn!(error = %e, "no host command list"); - None - } - }), + hosts: std::sync::Mutex::new( + crate::host::host() + .and_then(|h| match h.new_list() { + Ok(list) => Some(std::sync::Arc::new(list)), + Err(e) => { + tracing::warn!(error = %e, "no host command list"); + None + } + }) + .into_iter() + .collect(), + ), + #[cfg(windows)] + segment: Default::default(), #[cfg(windows)] state: { let mut state = crate::draw::State::default(); @@ -259,6 +426,21 @@ extern "system" fn list_query(this: This, iid: *const Iid, out: *mut This) -> HR object::answer(LIST, iid, object::is(iid, &LIST_IIDS).then_some(this), out) } extern "system" fn list_release(this: This) -> u32 { + // A queue may still hold some of its host lists; they are its own, and + // the last of them takes what the list owned. + #[cfg(windows)] + if !this.is_null() && object::refs(this) == 1 { + // SAFETY: the title passes one of our lists. + let list = unsafe { &*this.cast::() }; + let held = list.hosts.lock().unwrap_or_else(|e| e.into_inner()).iter().rfind(|h| std::sync::Arc::strong_count(h) > 1).cloned(); + if held.is_some() { + EARLY_RESETS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + tracing::debug!("a list released while a queue still holds part of it: that part runs on its own"); + let uploads = std::mem::take(&mut *list.uploads.lock().unwrap_or_else(|e| e.into_inner())); + let state = std::mem::take(&mut *list.state.lock().unwrap_or_else(|e| e.into_inner())); + leave(held, uploads, state); + } + } object::release_boxed::(this) } extern "system" fn list_type(this: This) -> u32 { @@ -276,15 +458,22 @@ extern "system" fn reset(this: This, allocator: This, pipeline: This) -> HRESULT if allocator.is_null() { return E_INVALIDARG; } - // Every submission of the list has run (submissions are waited for). + // A queue may still hold what the list recorded (`restart`, `leave`). // SAFETY: the title passes one of our lists. let uploads = unsafe { &(*this.cast::()).uploads }; - uploads.lock().unwrap_or_else(|e| e.into_inner()).clear(); + let uploads = std::mem::take(&mut *uploads.lock().unwrap_or_else(|e| e.into_inner())); #[cfg(windows)] - with_state(this, |host, state| { - host.reset(); + { + let held = restart(this); + // SAFETY: the title passes one of our lists. + let mut state = unsafe { &(*this.cast::()).state }.lock().unwrap_or_else(|e| e.into_inner()); + let old = std::mem::take(&mut *state); state.reset(pipeline); - }); + drop(state); + leave(held, uploads, old); + } + #[cfg(not(windows))] + drop(uploads); crate::pipeline::bound(pipeline); #[cfg(not(windows))] let _ = this; @@ -1138,7 +1327,7 @@ extern "system" fn ignored_state(_: This) {} /// set on the host list at once. Without a host GPU these do nothing. #[cfg(windows)] mod state { - use super::{This, host_list, with_state}; + use super::{This, with_state}; use crate::draw::{IndexView, VertexView}; use windows::Win32::Foundation::RECT; use windows::Win32::Graphics::Direct3D12::D3D12_VIEWPORT; @@ -1160,25 +1349,17 @@ mod state { count: u32, viewports: *const D3D12_VIEWPORT, ) { - if let Some(list) = host_list(this) { - crate::draw::viewports(list, items(viewports, count)); - } + with_state(this, |list, s| s.viewports(list, items(viewports, count))); } pub(super) extern "system" fn scissors(this: This, count: u32, rects: *const RECT) { - if let Some(list) = host_list(this) { - crate::draw::scissors(list, items(rects, count)); - } + with_state(this, |list, s| s.scissors(list, items(rects, count))); } pub(super) extern "system" fn blend_factor(this: This, factor: *const [f32; 4]) { - if let Some(list) = host_list(this) { - // SAFETY: the title passes four floats or null. - crate::draw::blend_factor(list, unsafe { factor.as_ref() }); - } + // SAFETY: the title passes four floats or null. + with_state(this, |list, s| s.blend_factor(list, unsafe { factor.as_ref() })); } pub(super) extern "system" fn stencil_ref(this: This, reference: u32) { - if let Some(list) = host_list(this) { - crate::draw::stencil_ref(list, reference); - } + with_state(this, |list, s| s.stencil_ref(list, reference)); } pub(super) extern "system" fn heaps(this: This, count: u32, heaps: *const This) { with_state(this, |_, s| s.set_heaps(items(heaps, count))); @@ -1485,10 +1666,6 @@ pub(crate) fn take_counts() -> (u64, u64) { (DRAWS.swap(0, Relaxed), DISPATCHES.swap(0, Relaxed)) } -/// A GPU wait for a memory value `(address, comparison, reference, ...)`. -/// Lists run one after another and to completion, so a value another queue -/// or the CPU has to write first cannot be waited for; nothing to do. -extern "system" fn wait_value(_: This, _address: u64, _comparison: u32, _reference: u64) {} /// The enhanced barriers `(group count, groups)`: buffer, texture and /// global barriers with layouts instead of states. Every host use of a @@ -1523,7 +1700,7 @@ extern "system" fn barrier_groups(this: This, count: u32, _groups: *const u8) { extern "system" fn write32(this: This, address: u64, value: u32, _flush: u32, _flags: u32) { defer_write(this, address, Written::Value(u64::from(value)), 4); } -extern "system" fn write64(this: This, address: u64, value: u64, _flush: u32, flags: u32) { +pub(crate) extern "system" fn write64(this: This, address: u64, value: u64, _flush: u32, flags: u32) { const GPU_TIMESTAMP: u32 = 1; const SYSTEM_TIMESTAMP: u32 = 2; let what = match flags { @@ -1598,8 +1775,8 @@ const METHODS: [(usize, *const ()); 52] = [ (68, ignored_state as *const ()), // 0x220 depth bounds (69, write32 as *const ()), // 0x228 (70, write64 as *const ()), // 0x230 - (71, wait_value as *const ()), // 0x238, 32 bits - (72, wait_value as *const ()), // 0x240, 64 bits + (71, wait32 as *const ()), // 0x238 (newer 0x248) + (72, wait64 as *const ()), // 0x240 (newer 0x250) (73, ignored_state as *const ()), // 0x248 pixel shader depth order (83, copy_texture_region_x as *const ()), // 0x298 (84, copy_resource_x as *const ()), // 0x2a0 diff --git a/crates/victory-gpu/src/object.rs b/crates/victory-gpu/src/object.rs index 6671d4b2e4..2df92a7413 100644 --- a/crates/victory-gpu/src/object.rs +++ b/crates/victory-gpu/src/object.rs @@ -71,6 +71,12 @@ pub(crate) extern "system" fn add_ref(this: This) -> u32 { unsafe { &*this }.refs.fetch_add(1, Ordering::Relaxed) + 1 } +/// An object's reference count. +pub(crate) fn refs(this: This) -> u32 { + // SAFETY: `this` is one of our objects. + unsafe { &*this }.refs.load(Ordering::Acquire) +} + pub(crate) extern "system" fn release(this: This) -> u32 { // SAFETY: `this` is one of our objects. let refs = &unsafe { &*this }.refs; diff --git a/crates/victory-gpu/src/queue.rs b/crates/victory-gpu/src/queue.rs index e3a76bf05e..3da261b7be 100644 --- a/crates/victory-gpu/src/queue.rs +++ b/crates/victory-gpu/src/queue.rs @@ -110,20 +110,25 @@ extern "system" fn release(this: This) -> u32 { object::release_boxed::(this) } -/// Runs the lists' host lists and waits for them (decision 0007). -extern "system" fn execute(_: This, count: u32, lists: *const This) { +/// Queues the lists' host lists behind what the queue holds, and runs what +/// may run (`crate::hold`; decision 0007). +extern "system" fn execute(this: This, count: u32, lists: *const This) { if lists.is_null() { return; } #[cfg(windows)] - if let Some(host) = crate::host::host() { + if crate::host::host().is_some() { // SAFETY: the title passes `count` lists. let lists = unsafe { std::slice::from_raw_parts(lists, count as usize) }; - let host_lists: Vec<_> = lists - .iter() - .filter_map(|&l| crate::list::host_list(l)) - .collect(); - host.execute(&host_lists); + let mut held = held(); + for &l in lists { + for segment in crate::list::segments(l) { + let waits = segment.waits(); + held.push(this as usize, Item::Segment(segment, waits)); + } + } + account().submissions += 1; + pump(&mut held, Why::Submission); return; } static ONCE: AtomicBool = AtomicBool::new(false); @@ -132,6 +137,213 @@ extern "system" fn execute(_: This, count: u32, lists: *const This) { } } +/// What ran held work: the title's submission, a queue's Signal or Wait, a +/// CPU fence call, PresentX, or our timer. +#[derive(Clone, Copy, Debug)] +pub(crate) enum Why { + Submission, + Signal, + Wait, + Fence, + Present, + Timer, +} + +#[cfg(windows)] +use crate::hold::Item; + +/// Every queue's held work. +#[cfg(windows)] +type Holding = crate::hold::Held>; + +#[cfg(windows)] +static HELD: std::sync::Mutex = std::sync::Mutex::new(crate::hold::Held::new()); + +#[cfg(windows)] +fn held() -> std::sync::MutexGuard<'static, Holding> { + HELD.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// Runs held work that may run now (`why` for the frame line). +pub(crate) fn pump_held(why: Why) { + #[cfg(windows)] + pump(&mut held(), why); + #[cfg(not(windows))] + let _ = why; +} + +/// The same unless another thread is at it (calls that poll: a fence's +/// value, our timer). +pub(crate) fn pump_held_if_free(why: Why) { + #[cfg(windows)] + if let Ok(mut held) = HELD.try_lock() { + pump(&mut held, why); + } + #[cfg(not(windows))] + let _ = why; +} + +/// How long a queue's head may wait before it runs anyway. +// shortcut: a safety valve against a wait nothing satisfies (a write we do +// not make), which would hold the title's fences until its 30 s watchdog +// ends the run; counted and logged, remove once runs show it never fires. +#[cfg(windows)] +const VALVE: std::time::Duration = std::time::Duration::from_secs(10); + +#[cfg(windows)] +fn pump(held: &mut Holding, why: Why) { + if held.is_empty() { + return; + } + let Some(host) = crate::host::host() else { return }; + let read = read_value; + for (queue, waits) in held.force_older_than(VALVE) { + account().forced += 1; + tracing::warn!(queue = kind(queue), ?waits, "held work runs without its waits after {VALVE:?} (safety valve)"); + } + let fence = |f: usize| crate::fence::value(f as This); + let started = std::time::Instant::now(); + let mut ran = std::time::Duration::ZERO; + let mut run = |_: usize, segments: Vec>| { + let lists: Vec<&crate::host::HostList> = segments.iter().map(|s| &**s).collect(); + let at = std::time::Instant::now(); + host.execute(&lists); + ran += at.elapsed(); + drop(lists); + segments.into_iter().for_each(crate::list::recycle); + }; + let mut signal = |f: usize, value: u64| { + crate::fence::set(f as This, value); + crate::fence::let_go(f as This); + }; + let pumped = held.pump(&mut crate::hold::World { + read: &read, + fence: &fence, + run: &mut run, + signal: &mut signal, + }); + if pumped.segments > 0 || pumped.unknown > 0 { + let mut a = account(); + a.pump += started.elapsed().saturating_sub(ran); + a.pieces += pumped.pieces; + a.segments += pumped.segments; + a.unknown += pumped.unknown; + for (queue, waited) in pumped.waited { + a.released.push((kind(queue), waited, why)); + } + } + // Once work stays held, a timer tests it every 2 ms: memory the title + // writes from the CPU, or the valve, may let it go with no call of ours. + if held.blocked(&read).is_empty() { + return; + } + static TIMER: std::sync::Once = std::sync::Once::new(); + TIMER.call_once(|| { + let _ = std::thread::Builder::new().name("victory held work".into()).spawn(|| loop { + std::thread::sleep(std::time::Duration::from_millis(2)); + pump_held_if_free(Why::Timer); + }); + }); +} + +/// The value a wait tests (4 or 8 bytes), if the memory can be read. +#[cfg(windows)] +fn read_value(address: u64, bytes: u8) -> Option { + let mut value = [0u8; 8]; + crate::host::read_into(address as *const u8, &mut value[..usize::from(bytes.min(8))]).then(|| u64::from_le_bytes(value)) +} + +/// A queue's type, for logs (0 graphics, 2 compute, 3 copy). Titles do not +/// release queues that hold work. +#[cfg(windows)] +fn kind(queue: usize) -> u32 { + self::queue(queue as This).kind +} + +/// What queues did with held work since the last presented frame. +#[cfg(windows)] +#[derive(Default)] +struct Account { + submissions: u32, + pieces: u32, + segments: u32, + /// Segments that waited: queue type, how long, what ran them. + released: Vec<(u32, std::time::Duration, Why)>, + unknown: u32, + forced: u32, + mappings: u32, + /// Time in the pump outside host submissions. + pump: std::time::Duration, +} + +#[cfg(windows)] +fn account() -> std::sync::MutexGuard<'static, Account> { + static ACCOUNT: std::sync::OnceLock> = std::sync::OnceLock::new(); + ACCOUNT.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner()) +} + +/// The frame line of held work: what waited, how long and what released it, +/// and what is still held at the present, with the waits that do not hold. +#[cfg(windows)] +fn account_frame(frame: u64) { + let (cuts, early) = crate::list::take_cuts(); + let (fence_waits, fence_waited) = crate::fence::take_waited(); + let a = std::mem::take(&mut *account()); + let blocked = held().blocked(&read_value); + if a.released.is_empty() && blocked.is_empty() && a.forced == 0 && a.unknown == 0 && a.mappings == 0 { + return; + } + let longest = a.released.iter().map(|r| r.1).max().unwrap_or_default(); + let mut by = [0u32; 6]; + for r in &a.released { + by[r.2 as usize] += 1; + } + tracing::info!( + frame, + submissions = a.submissions, + pieces = a.pieces, + segments = a.segments, + cuts, + early_resets = early, + waited = a.released.len(), + longest_ms = longest.as_secs_f64() * 1e3, + pump_ms = a.pump.as_secs_f64() * 1e3, + fence_waits, + fence_wait_ms = fence_waited.as_secs_f64() * 1e3, + "held work this frame (submissions; host submissions, segments; lists cut at waits; lists reset or released \ + while held, each keeping its own host list; segments that waited, released by \ + submission/signal/wait/fence/present/timer {by:?}; time in the pump outside host submissions; events the title waited on for fence values and their summed waits); held at the present: {}", + blocked.len() + ); + tracing::debug!( + frame, + "held work released this frame (queue type, ms, by): {:?}", + a.released.iter().map(|(k, d, w)| (k, d.as_secs_f64() * 1e3, w)).collect::>() + ); + for (queue, items, waited, unmet) in &blocked { + let level_warn = blocked.len() > 1; + let unmet: Vec = unmet + .iter() + .map(|w| format!("{:#x} cmp {} {:#x} (is {:?})", w.address, w.comparison, w.reference, read_value(w.address, w.bytes))) + .collect(); + if level_warn { + tracing::warn!(frame, queue = kind(*queue), items, waited_ms = waited.as_millis(), ?unmet, "two or more queues hold work at the present"); + } else { + tracing::info!(frame, queue = kind(*queue), items, waited_ms = waited.as_millis(), ?unmet, "a queue holds work at the present"); + } + } + if a.forced > 0 || a.unknown > 0 || a.mappings > 0 { + tracing::warn!( + frame, + forced = a.forced, + unknown = a.unknown, + mappings = a.mappings, + "held work: run without its waits (valve), waits with an unknown comparison (taken as holding), \ + page mappings done ahead of held work" + ); + } +} + /// The start of a present plane: frame token, then the plane's resources. #[repr(C)] pub(crate) struct Plane { @@ -145,7 +357,7 @@ extern "system" fn execute_x(this: This, count: u32, lists: *const This, _token: execute(this, count, lists); } /// Signal with sync settings for the top and bottom of the pipe; our -/// submissions are complete when they return, so it signals at once. +/// submissions are complete when they run, so it signals as Signal does. extern "system" fn signal2_x( this: This, fence: This, @@ -157,15 +369,48 @@ extern "system" fn signal2_x( } /// Markers and events only matter to profilers. extern "system" fn marker(_: This) {} -extern "system" fn signal(_: This, fence: This, value: u64) -> HRESULT { +/// At once, or behind the work the queue holds (its fence, and the memory +/// the title reads it at, move only once that work has run). +extern "system" fn signal(this: This, fence: This, value: u64) -> HRESULT { if fence.is_null() { return E_INVALIDARG; } - crate::fence::signal(fence, value) + #[cfg(windows)] + { + let mut held = held(); + if held.holds_work(this as usize) { + crate::fence::keep(fence); + held.push(this as usize, Item::Signal(fence as usize, value)); + } else { + crate::fence::set(fence, value); + } + // Another queue may wait for this fence. + pump(&mut held, Why::Signal); + } + #[cfg(not(windows))] + { + let _ = this; + crate::fence::set(fence, value); + } + S_OK } -/// Nothing runs on the queue, so waiting for a fence never blocks it. -extern "system" fn wait(_: This, fence: This, _value: u64) -> HRESULT { - if fence.is_null() { E_INVALIDARG } else { S_OK } +/// The queue's later work waits until the fence reaches `value`. +/// +/// shortcut: the fence is not kept alive while the queue waits for it; +/// Grand Theft Auto VI makes no queue wait for a fence. +extern "system" fn wait(this: This, fence: This, value: u64) -> HRESULT { + if fence.is_null() { + return E_INVALIDARG; + } + #[cfg(windows)] + if crate::host::host().is_some() && crate::fence::value(fence) < value { + let mut held = held(); + held.push(this as usize, Item::FenceWait(fence as usize, value)); + pump(&mut held, Why::Wait); + } + #[cfg(not(windows))] + let _ = (this, value); + S_OK } /// Ticks per second of GPU timestamps (see [`Written::GpuTimestamp`]). extern "system" fn timestamp_frequency(_: This, out: *mut u64) -> HRESULT { @@ -241,7 +486,13 @@ extern "system" fn present( plane_parameters: *const Plane, _parameters: *const u8, ) -> HRESULT { + // What may run before the frame is shown does. + // shortcut: PresentX does not wait behind work the queue still holds (it + // shows the frame as far as it ran); the frame line names such work. + pump_held(Why::Present); let frame = FRAMES.fetch_add(1, Ordering::Relaxed) + 1; + #[cfg(windows)] + account_frame(frame); #[cfg(feature = "diagnostics")] crate::frame::presented(); if frame.is_power_of_two() { @@ -363,10 +614,12 @@ const PAGE: u64 = 64 << 10; /// pages of a pool (memory the title mapped physical pages into) at the /// batches' addresses. Grand Theft Auto VI streams textures into pool pages /// and maps them into its tiled heap this way (title+0xf2c470, ranges of -/// one constant page or of unmapped pages). Done at once: every earlier -/// submission has run. +/// one constant page or of unmapped pages). Done at once. +/// +/// shortcut: done ahead of work the queue still holds (counted in the frame +/// line); queue it as an item like Signal if that count is not 0. extern "system" fn copy_page_mappings( - _: This, + this: This, count: u32, batches: *const PageBatch, pool: u64, @@ -379,6 +632,12 @@ extern "system" fn copy_page_mappings( if batches.is_null() && count > 0 { return E_INVALIDARG; } + #[cfg(windows)] + if held().holds_work(this as usize) { + account().mappings += 1; + } + #[cfg(not(windows))] + let _ = this; let batches = (count > 0).then(|| { // SAFETY: the title passes `count` batches. unsafe { std::slice::from_raw_parts(batches, count as usize) } diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index 049c339a54..b6985634a9 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -3008,6 +3008,106 @@ mod tests { assert!(read == want.as_slice(), "the region's rows, and nothing else"); } + /// Two queues, as Grand Theft Auto VI's: a compute list copies a buffer, + /// then waits for a value a graphics list writes at its end, then reads + /// back the texture that graphics list fills. Submitted first, its first + /// part runs at once and the rest waits for the graphics list, then + /// reads what it wrote. + #[cfg(windows)] + #[test] + fn a_list_waiting_for_another_queues_write_reads_what_it_wrote() { + if crate::host::host().is_none() { + return; // no host GPU here + } + let null = std::ptr::null(); + let iid = &RESOURCE_IIDS[0]; + const COPY_DEST: u32 = 0x400; + let (mut image, mut source, mut target, mut early, mut words) = (null, null, null, null, null); + let created = |desc: &ResourceDesc, state, out: &mut This| { + assert_eq!(create_committed(null, &PROPERTIES, 0, desc, state, null.cast(), iid, out), S_OK); + }; + // A plain texture: its contents are the host's from the graphics + // list's submission on (`texture::host_writes`), not from when the + // compute list was recorded. + created(&texture(4, 4, 28, 1), COPY_DEST, &mut image); + created(&buffer(1024), 0, &mut source); + created(&buffer(1024), 0, &mut target); + created(&buffer(1024), 0, &mut early); + created(&buffer(256), 0, &mut words); + let (data, _) = buffer_bytes(source).unwrap(); + // SAFETY: the buffer holds 1024 bytes. + let bytes = unsafe { std::slice::from_raw_parts_mut(data, 1024) }; + for (i, b) in bytes.iter_mut().enumerate() { + *b = (i % 251) as u8; + } + let (out, _) = buffer_bytes(target).unwrap(); + // SAFETY: the buffer holds 1024 bytes. + unsafe { std::ptr::write_bytes(out, 0xEE, 1024) }; + let (flag, _) = buffer_bytes(words).unwrap(); + let flag = flag.cast::(); + + let queue_iid = guid(0x0ec870a6, 0x5d7e, 0x4c22, [0x8c, 0xfc, 0x5b, 0xaa, 0xe0, 0x76, 0x16, 0xed]); + let allocator_iid = guid(0x6102dee4, 0xaf59, 0x4b09, [0xb9, 0x99, 0xb4, 0x4d, 0x73, 0xf0, 0x9b, 0x24]); + let list_iid = guid(0x5b160d0f, 0xac1b, 0x4185, [0x8b, 0xa8, 0xb3, 0xae, 0x42, 0xa5, 0xa4, 0x55]); + let (mut graphics, mut compute, mut allocator, mut drawing, mut computing) = (null, null, null, null, null); + for (kind, queue) in [(0u32, &mut graphics), (2, &mut compute)] { + let desc = [kind, 0, 0, 0]; + assert_eq!(crate::queue::create(null, desc.as_ptr().cast(), &queue_iid, queue), S_OK); + } + assert_eq!(crate::list::create_allocator(null, 0, &allocator_iid, &mut allocator), S_OK); + for (kind, list) in [(0u32, &mut drawing), (2, &mut computing)] { + assert_eq!(crate::list::create_list(null, 0, kind, allocator, null, &list_iid, list), S_OK); + } + #[repr(C)] + struct Location { + resource: This, + kind: u32, + footprint: PlacedFootprint, + } + let rows = PlacedFootprint { offset: 0, format: 28, width: 4, height: 4, depth: 1, row_pitch: 256 }; + let image_at = Location { resource: image, kind: 0, footprint: rows }; + type Copy = extern "system" fn(This, *const Location, u32, u32, u32, *const Location, *const u8); + type CopyBuffer = extern "system" fn(This, This, u64, This, u64, u64); + type Close = extern "system" fn(This) -> HRESULT; + type Execute = extern "system" fn(This, u32, *const This); + const GREATER_EQUAL: u32 = 7; + + // Compute: [copy source → early][wait flag ≥ 1][image → target]. + slot::(computing, 0x78)(computing, early, 0, source, 0, 1024); + crate::list::wait64(computing, flag as u64, GREATER_EQUAL, 1, 0); + let into_target = Location { resource: target, kind: 1, footprint: rows }; + slot::(computing, 0x80)(computing, &into_target, 0, 0, 0, &image_at, null.cast()); + slot::(computing, 0x48)(computing); + // Graphics: [source → image][flag = 1 at its end]. + let from_source = Location { resource: source, kind: 1, footprint: rows }; + slot::(drawing, 0x80)(drawing, &image_at, 0, 0, 0, &from_source, null.cast()); + crate::list::write64(drawing, flag as u64, 1, 0, 0); + slot::(drawing, 0x48)(drawing); + + slot::(compute, 0x50)(compute, 1, &computing); + let (copied, _) = buffer_bytes(early).unwrap(); + // SAFETY: the buffers hold 1024 bytes; nothing runs meanwhile. + let read = |at: *mut u8| unsafe { std::slice::from_raw_parts(at, 1024) }.to_vec(); + assert_eq!(read(copied), bytes, "the part before the wait ran"); + assert!(read(out).iter().all(|&b| b == 0xEE), "the part after it waits"); + // SAFETY: the buffer holds 256 bytes. + assert_eq!(unsafe { flag.read_volatile() }, 0); + // D3D12 lets the title reset a list as soon as it has submitted it: + // the held part keeps its own host list and what it reads. + type Reset = extern "system" fn(This, This, This) -> HRESULT; + assert_eq!(slot::(computing, 0x50)(computing, allocator, null), S_OK); + slot::(computing, 0x48)(computing); + + slot::(graphics, 0x50)(graphics, 1, &drawing); + // SAFETY: as above. + assert_eq!(unsafe { flag.read_volatile() }, 1); + let read = read(out); + for row in 0..4 { + let at = row * 256; + assert_eq!(read[at..at + 16], bytes[at..at + 16], "row {row}: the texture as the graphics list filled it"); + } + } + #[test] fn committed_and_placed_resources_map_at_their_gpu_address() { let null = std::ptr::null(); From 8f2a6f14547586d1f403edc22453ecd1eb6c25d9 Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 14:28:55 +0100 Subject: [PATCH 73/83] GPU: a texture refresh reads title memory into its thread's own buffer What was wrong: each refresh of a tracked texture read the changed title memory into a buffer allocated for it, the texture's whole size (5.6 MB for a BC7 2048), zero-filled and touched page by page: a zero-fill and a page fault per 4 KiB for every texture brought up (129,071 page faults while preparing in one frame of run placed1). The detile itself is not the cost: a BC7 2048 64KB_D texture detiles at 0.04 ms per MB on this machine, as fast as a plain copy of its bytes, against ~2.2 ms per MB for a whole refresh. What changed: the read goes into a buffer the worker thread keeps for its next refresh (up to 32 MiB; larger ones are not kept). Only the touched spans are written, and only they are hashed and detiled, as before. In diagnostics builds, the scan of each texture read for all zeros runs only when its debug message is wanted. Evidence: the texture upload tests, which refresh several textures and single mips on the same threads, pass (victory-gpu 193 passed, twice). Run scratch1 (240 s of the intro cutscene, quiet, on the same main as run placed1): texture refreshes 177 ms of worker time for 98 MB a frame (1.8 ms per MB) against 235 ms for 105 MB (2.2 ms per MB). Its whole frame was slower (median 1,010 ms against 894) through GPU time (mean 450 ms against 318) and after-work, which this change does not touch: one run each, run-to-run variance not separated. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/texture.rs | 58 +++++++++++++++++++++++++------ 1 file changed, 47 insertions(+), 11 deletions(-) diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 437b1fbdd5..4a502c1abd 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -582,8 +582,10 @@ impl Staging { .collect(); // Read through the copy, which stands unmapped pages: memory of // big pools is too slow to ask page by page. Not kept: it would - // double each texture's system memory. - let mut read = vec![0u8; size]; + // double each texture's system memory. Only the touched spans + // are written, and only they are hashed and detiled. + let mut scratch = Scratch::take(size); + let read = &mut scratch.0[..size]; let mut bytes = 0; let mut done: Vec<(usize, usize)> = Vec::new(); for &i in &touched { @@ -617,7 +619,7 @@ impl Staging { if fresh.is_empty() { return (bytes, None); } - let buffer = self.detile(&read, &fresh); + let buffer = self.detile(read, &fresh); if buffer.is_none() { for &i in &fresh { last.hashes[i as usize] = None; @@ -668,14 +670,18 @@ impl Staging { fn detile(&self, tiled: &[u8], subresources: &[u32]) -> Option<(ID3D12Resource, u64)> { let (buffer, at, data) = staging_space(self.size)?; #[cfg(feature = "diagnostics")] - if tiled.iter().all(|&b| b == 0) { - tracing::debug!( - memory = ?self.memory, - desc = ?self.layout.desc, - "a sampled texture's memory is all zero (not streamed yet, or a failed BCPack read)" - ); - } else { - tracing::debug!(memory = ?self.memory, desc = ?self.layout.desc, "a sampled texture detiled"); + // Scanned only when its message is wanted: a pass over every + // texture read, in timing runs too. + if tracing::enabled!(tracing::Level::DEBUG) { + if tiled.iter().all(|&b| b == 0) { + tracing::debug!( + memory = ?self.memory, + desc = ?self.layout.desc, + "a sampled texture's memory is all zero (not streamed yet, or a failed BCPack read)" + ); + } else { + tracing::debug!(memory = ?self.memory, desc = ?self.layout.desc, "a sampled texture detiled"); + } } for &i in subresources { let (footprint, rows) = (&self.footprints[i as usize], self.rows[i as usize]); @@ -699,6 +705,36 @@ impl Staging { } } +/// A buffer for the title memory a refresh reads, kept by the thread for +/// its next refresh: a fresh one for each texture cost a zero-fill and a +/// page fault per 4 KiB (129,000 faults in a frame, run placed1). +struct Scratch(Vec); + +thread_local! { + static SCRATCH: std::cell::Cell> = const { std::cell::Cell::new(Vec::new()) }; +} + +impl Scratch { + /// The thread's buffer, at least `size` bytes. + fn take(size: usize) -> Self { + let mut v = SCRATCH.take(); + if v.len() < size { + v.resize(size, 0); + } + Scratch(v) + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + // The largest textures' buffers are not kept. + const KEEP: usize = 32 << 20; + if self.0.len() <= KEEP { + SCRATCH.set(std::mem::take(&mut self.0)); + } + } +} + /// Bytes available in the staging buffer for a subresource at `offset`. /// D3D12's `GetCopyableFootprints` omits trailing row-pitch padding on the /// final row of the final subresource, so `pitch * rows * depth` can exceed From 286a00e9b69851d1dc0d68d313a01822a251084f Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 13:08:22 +0100 Subject: [PATCH 74/83] Shaders: the DXIL writer leaves out what no edge or reader reaches Lowering leaves much in the DXIL that never runs or counts: branches on constants (lane conditions structurisation already knows, edges no lane takes) and the code only their other edge reaches, empty blocks that only forward to the next, size queries for descriptor words no path reads. The host driver compiles all of it. `indirect_diffuse_lighting:CS_ScreenProbes_ ActivateRays` (with nested descriptor joins, PR #1012) is where it showed: 8,745 of its 10,040 conditional branches were on constants, 10,061 of its 22,384 blocks empty forwarders, about 70 % of its instructions reachable only through constant branches' dead edges, and 556 of the 587 size queries in the rest unread; the AMD driver never finished it (over 6 GB at 64 s). The writer (`Module::plan`, `Module::kept`) now: * takes a branch on a constant as a branch to its one target: blocks only the other edge reaches are not written, and phis lose the entries of edges that are gone (their other entries stay); * folds an empty block with one predecessor into it (the predecessor branches to its target), unless it splits a critical edge (lowering keeps loops' exits and preheaders dedicated, as DXC emits them) or its predecessor would then reach the target twice (one phi entry per predecessor); empty latches fold as before; * writes only instructions with effects (stores, atomics, calls neither read-none nor read-only: barriers, discard, wave operations, the write and read marks) and what they read, transitively (it dropped only unread phis before); * declares only the functions it calls and the constant globals it reads (the validator refuses the others); * and the shader flags of heap handles, wave operations and 64-bit integers follow what is written (`Module::uses`; the validator refuses a flag whose use is gone, "Flags must match usage"). Whole list (shaders.rpf, the exe, XboxBvhBuilder, the upscaler; translate --list --validate, against 8ff79135): 0 programs change outcome (14,254 VS/PS, 2,732 compute, 8,765 mesh emitted; 13,313 / 1,984 / 4,625 validated, as before); DXIL bitcode 1,423,424,800 -> 1,246,729,828 bytes (-12.4 %), blocks 3,624,448 -> 3,554,816 (-1.9 %). ActivateRays itself is still refused here (nested joins); its table is in the commit that lets it through. Tests (`emit::bitcode`): a constant branch drops its other side and that side's phi entry only; a loop whose back edge is never taken; empty blocks before a phi fold only where the entry can move; only values with effects or readers are written (read-none and read-only calls, stores, atomics, barriers); constant globals nothing reads are left out; uses count only what is written. The writer's pinned bytes are pinned anew (its test module's last call became one with effects). Co-Authored-By: Claude Opus 5.5 --- crates/victory-shader/src/emit/bitcode.rs | 564 ++++++++++++++++++---- crates/victory-shader/src/emit/shader.rs | 11 + 2 files changed, 487 insertions(+), 88 deletions(-) diff --git a/crates/victory-shader/src/emit/bitcode.rs b/crates/victory-shader/src/emit/bitcode.rs index 07c87a178d..0a4a44b080 100644 --- a/crates/victory-shader/src/emit/bitcode.rs +++ b/crates/victory-shader/src/emit/bitcode.rs @@ -496,11 +496,49 @@ impl Module { self.named.push((name.into(), nodes)); } - /// The module as bitcode. - /// Which instructions are written: every body instruction, the branch - /// conditions, and whatever they read, transitively (a phi nothing reads - /// is dropped). A worklist visits each instruction once, so a long chain - /// of merges costs one pass, not one pass per merge. + /// Whether body instruction `i` is written even if nothing reads it: it + /// has effects (stores, atomics, calls of operations that are neither + /// read-none nor read-only). + fn rooted(&self, i: u32) -> bool { + match &self.insts[i as usize].op { + Op::Call(f, _) => !matches!(self.funcs[*f as usize].attr, Some(Attr::ReadNone | Attr::ReadOnly)), + Op::Store(..) | Op::AtomicRmw(..) | Op::CmpXchg(..) => true, + _ => false, + } + } + + /// What the instructions [`Module::write`] writes use, of what the + /// shader flags declare (which must match it, or the validator refuses + /// the module: "Flags must match usage"). + pub fn uses(&self) -> Uses { + let plan = self.plan(); + let wide = |t: Ty| self.types[t.0 as usize] == TypeDef::Int(64); + let mut u = Uses::default(); + for b in plan.layout.iter().map(|&b| &self.blocks[b]) { + for &i in b.phis.iter().chain(&b.body).filter(|&&i| plan.live[i as usize]) { + let inst = &self.insts[i as usize]; + u.int64 |= wide(inst.ty); + for_each_operand(&inst.op, |v| u.int64 |= wide(self.type_of(v))); + let Op::Call(f, args) = &inst.op else { continue }; + let name = self.funcs[*f as usize].name.as_str(); + if name.starts_with("dx.op.createHandleFromHeap") { + // Arguments: opcode, index, sampler heap, non-uniform. + let sampler = args.get(2).and_then(|&a| self.int_value(a)).is_some_and(|x| x != 0); + u.heap |= !sampler; + u.sampler_heap |= sampler; + } + u.wave |= name.starts_with("dx.op.wave") || name.starts_with("dx.op.quad"); + } + } + u + } + + /// Which instructions are written: those [`Module::rooted`], the + /// branch conditions, and whatever they read, transitively (a phi or a + /// value nothing reads is dropped: lowering makes size queries for + /// descriptor words no path reads, 556 of ActivateRays' 587). A worklist + /// visits each instruction once, so a long chain of merges costs one + /// pass, not one pass per merge. fn live(&self) -> Vec { let mut live = vec![false; self.insts.len()]; let mut work: Vec = Vec::new(); @@ -513,7 +551,7 @@ impl Module { } }; for b in &self.blocks { - for &i in &b.body { + for &i in b.body.iter().filter(|&&i| self.rooted(i)) { mark(&mut live, &mut work, V::Inst(i)); } if let Some(Term::CondBr(c, ..)) = b.term { @@ -528,7 +566,144 @@ impl Module { live } + /// Block `b`'s terminator, a branch on a constant taking its one edge + /// (lowering leaves many: lane conditions structurisation knows, edges + /// no lane takes). + fn term(&self, b: usize) -> Option { + match self.blocks[b].term { + Some(Term::CondBr(c, t, f)) => match self.int_value(c) { + Some(x) => Some(Term::Br(if x != 0 { t } else { f })), + None => Some(Term::CondBr(c, t, f)), + }, + t => t, + } + } + + /// The globals and functions [`Module::write`] declares, each kept + /// one's new index and their number: functions declared and not called, + /// and constant globals nothing reads, are left out (the validator + /// refuses them). + fn kept(&self, plan: &Plan) -> ((Vec, u32), (Vec, u32)) { + let mut called = vec![false; self.funcs.len()]; + let mut read = vec![false; self.globals.len()]; + for m in &self.mds { + if let MdDef::Value(_, V::Global(g)) = m { + read[*g as usize] = true; + } + } + for b in plan.layout.iter().map(|&b| &self.blocks[b]) { + for &i in b.phis.iter().chain(&b.body).filter(|&&i| plan.live[i as usize]) { + let op = &self.insts[i as usize].op; + if let Op::Call(f, _) = *op { + called[f as usize] = true; + } + for_each_operand(op, |v| { + if let V::Global(g) = v { + read[g as usize] = true; + } + }); + } + } + let number = |keep: &mut dyn Iterator| { + let mut n = 0; + let ids = keep + .map(|k| { + n += u32::from(k); + if k { n - 1 } else { u32::MAX } + }) + .collect(); + (ids, n) + }; + let globals = number(&mut self.globals.iter().zip(&read).map(|(g, &r)| g.init.is_none() || r)); + let funcs = number(&mut self.funcs.iter().zip(&called).map(|(f, &c)| f.body || c)); + (globals, funcs) + } + + /// What [`Module::write`] writes: the instructions ([`Module::live`]), + /// the blocks reached from the entry through terminators as + /// [`Module::term`] gives them, in reverse postorder (every block after + /// its forward predecessors: drivers take a branch to an earlier block + /// for a loop's back edge), and the empty blocks folded away. + /// + /// An empty block (only a branch) with one predecessor is folded into + /// it: the predecessor branches to its target instead. For an empty + /// latch (a branch back to its loop header) this makes the exiting block + /// the latch, as in DXC's loops (the AMD driver hangs on divergent loops + /// otherwise); a forward one goes unless it splits a critical edge + /// (lowering splits them so that loops have dedicated exits and + /// preheaders, as DXC emits them), or its predecessor would reach the + /// target twice (the target's phis have one entry per predecessor). + fn plan(&self) -> Plan { + let live = self.live(); + let succs = |b: usize| successors(self.term(b)); + let mut seen = vec![false; self.blocks.len()]; + let mut post = Vec::new(); + let mut stack = vec![(0usize, 0usize)]; + seen[0] = true; + while let Some(top) = stack.last_mut() { + let (b, k) = *top; + top.1 += 1; + match succs(b).get(k) { + Some(&s) if !seen[s] => { + seen[s] = true; + stack.push((s, 0)); + } + Some(_) => {} + None => { + post.push(b); + stack.pop(); + } + } + } + post.reverse(); + let mut pos = vec![u64::MAX; self.blocks.len()]; + for (n, &b) in post.iter().enumerate() { + pos[b] = n as u64; + } + let mut preds = vec![Vec::new(); self.blocks.len()]; + for &b in &post { + for &s in succs(b).iter() { + preds[s].push(b); + } + } + let mut plan = Plan { + live, + seen, + layout: Vec::new(), + pos: Vec::new(), + fold: vec![None; self.blocks.len()], + }; + for &b in &post { + let blk = &self.blocks[b]; + let empty = b != 0 && blk.phis.iter().chain(&blk.body).all(|&i| !plan.live[i as usize]); + if let (Some(Term::Br(h)), true, [p]) = (self.term(b), empty, &preds[b][..]) + && plan.to(h) != b + { + plan.fold[b] = Some((*p, h)); + let (from, at) = (plan.src(b), plan.to(h)); + let critical = succs(from).len() > 1 && preds[at].len() > 1 && pos[h] > pos[b]; + if critical || succs(from).iter().filter(|&&s| plan.to(s) == at).count() != 1 { + plan.fold[b] = None; + } + } + } + plan.layout = post.into_iter().filter(|&b| plan.fold[b].is_none()).collect(); + plan.pos = vec![u64::MAX; self.blocks.len()]; + for (n, &b) in plan.layout.iter().enumerate() { + plan.pos[b] = n as u64; + } + plan + } + pub fn write(&self) -> Vec { + let plan = self.plan(); + let (live, layout) = (&plan.live, &plan.layout); + let term_of = |b: usize| self.term(b); + let target = |t: usize| plan.pos[plan.to(t)]; + let from = |b: usize| plan.pos[plan.src(b)]; + + let ((kept_globals, g_n), (kept, n)) = self.kept(&plan); + let mut w = Writer::default(); w.bytes(b"BC\xC0\xDE"); w.enter(MODULE_BLOCK, 3); @@ -591,8 +766,8 @@ impl Module { "e-m:e-p:32:32-i1:32-i8:32-i16:32-i32:32-i64:64-f16:32-f32:32-f64:64-n8:16:32:64", ), ); - let first_const = (self.globals.len() + self.funcs.len()) as u64; - for g in &self.globals { + let first_const = u64::from(g_n) + u64::from(n); + for g in self.globals.iter().zip(&kept_globals).filter(|(_, k)| **k != u32::MAX).map(|(g, _)| g) { // [type, address space << 2 | explicit type | constant, init id // + 1, linkage (external 0, internal 3), log2 alignment + 1, // section] @@ -612,7 +787,7 @@ impl Module { ], ); } - for f in &self.funcs { + for f in self.funcs.iter().zip(&kept).filter(|(_, k)| **k != u32::MAX).map(|(f, _)| f) { // [type, cc, isproto, linkage, paramattr, align, section, // visibility, gc, unnamed_addr, prologue, dllstorage, comdat, prefix] let attr = f.attr.map_or(0, |a| a as u64); @@ -638,8 +813,8 @@ impl Module { } // Value ids: globals, functions, constants, instructions. - let globals = self.globals.len() as u32; - let funcs = globals + self.funcs.len() as u32; + let globals = g_n; + let funcs = globals + n; let const_id = |i: u32| u64::from(funcs + i); w.enter(CONSTANTS_BLOCK, 4); let mut current = None; @@ -660,74 +835,12 @@ impl Module { } w.exit(); - // Phis nothing reads are left out (one register per phi makes many). - let live = self.live(); - - // Blocks are laid out in reverse postorder, so every block follows - // its forward predecessors (drivers take a branch to an earlier - // block for a loop's back edge). - let succs = |b: usize| successors(self.blocks[b].term); - let mut seen = vec![false; self.blocks.len()]; - let mut post = Vec::new(); - let mut stack = vec![(0usize, 0usize)]; - seen[0] = true; - while let Some(top) = stack.last_mut() { - let (b, k) = *top; - top.1 += 1; - match succs(b).get(k) { - Some(&s) if !seen[s] => { - seen[s] = true; - stack.push((s, 0)); - } - Some(_) => {} - None => { - post.push(b); - stack.pop(); - } - } - } - post.reverse(); - let mut pos = vec![u64::MAX; self.blocks.len()]; - for (n, &b) in post.iter().enumerate() { - pos[b] = n as u64; - } - // An empty latch (only a branch back to its loop header) is folded - // into its one predecessor, so the exiting block is the latch as in - // DXC's loops; the AMD driver hangs on divergent loops otherwise. - let mut preds = vec![Vec::new(); self.blocks.len()]; - for &b in &post { - for &s in succs(b).iter() { - preds[s].push(b); - } - } - let mut fold = vec![None; self.blocks.len()]; - for &b in &post { - let blk = &self.blocks[b]; - if let (Some(Term::Br(h)), true, [p]) = ( - blk.term, - blk.phis.iter().all(|&i| !live[i as usize]) && blk.body.is_empty(), - &preds[b][..], - ) && pos[h] < pos[b] - && !succs(*p).contains(&h) - { - fold[b] = Some((*p, h)); - } - } - let layout: Vec = post.into_iter().filter(|&b| fold[b].is_none()).collect(); - let mut pos = vec![u64::MAX; self.blocks.len()]; - for (n, &b) in layout.iter().enumerate() { - pos[b] = n as u64; - } - // Branch targets and phi blocks through folded latches. - let target = |t: usize| fold[t].map_or(pos[t], |(_, h)| pos[h]); - let from = |b: usize| fold[b].map_or(pos[b], |(p, _)| pos[p]); - // Instruction value ids, in layout order. let base = funcs + self.consts.len() as u32; let mut ids = vec![u32::MAX; self.insts.len()]; let mut next = base; for b in layout.iter().map(|&b| &self.blocks[b]) { - for &i in b.phis.iter().filter(|&&i| live[i as usize]).chain(&b.body) { + for &i in b.phis.iter().chain(&b.body).filter(|&&i| live[i as usize]) { if !self.is_void(self.insts[i as usize].ty) { ids[i as usize] = next; next += 1; @@ -736,8 +849,8 @@ impl Module { } let abs = |v: V| -> u32 { match v { - V::Global(i) => i, - V::Func(i) => globals + i, + V::Global(i) => kept_globals[i as usize], + V::Func(i) => globals + kept[i as usize], V::Const(i) => funcs + i, V::Inst(i) => { let id = ids[i as usize]; @@ -795,8 +908,9 @@ impl Module { w.exit(); w.enter(VALUE_SYMTAB_BLOCK, 4); - let names = self.globals.iter().map(|g| &g.name); - for (i, name) in names.chain(self.funcs.iter().map(|f| &f.name)).enumerate() { + let names = self.globals.iter().zip(&kept_globals).filter(|(_, k)| **k != u32::MAX).map(|(g, _)| &g.name); + let kept_names = self.funcs.iter().zip(&kept).filter(|(_, k)| **k != u32::MAX).map(|(f, _)| &f.name); + for (i, name) in names.chain(kept_names).enumerate() { let mut r = vec![i as u64]; r.extend(chars(name)); w.record(1, &r); @@ -808,8 +922,9 @@ impl Module { let mut inst_id = base; // The operands of variable-length records, reused across them. let mut r: Vec = Vec::new(); - for b in layout.iter().map(|&b| &self.blocks[b]) { - for &i in b.phis.iter().filter(|&&i| live[i as usize]).chain(&b.body) { + for &x in layout { + let b = &self.blocks[x]; + for &i in b.phis.iter().chain(&b.body).filter(|&&i| live[i as usize]) { let inst = &self.insts[i as usize]; let rel = |v: V| { let a = abs(v); @@ -832,7 +947,7 @@ impl Module { Op::Phi(incoming) => { r.clear(); r.push(u64::from(inst.ty.0)); - for &(v, b) in incoming { + for &(v, b) in incoming.iter().filter(|&&(_, b)| plan.edge(self, b, x)) { r.push(signed(i64::from(inst_id) - i64::from(abs(v)))); r.push(from(b)); } @@ -859,7 +974,7 @@ impl Module { inst_id += 1; } } - match b.term.expect("unterminated block") { + match term_of(x).expect("unterminated block") { Term::Ret => w.record(10, &[]), Term::Br(t) => w.record(11, &[target(t)]), Term::CondBr(c, t, f) => { @@ -884,6 +999,59 @@ const VALUE_SYMTAB_BLOCK: u64 = 14; const METADATA_BLOCK: u64 = 15; const TYPE_BLOCK: u64 = 17; +/// What the written instructions use of the features shader flags declare +/// ([`Module::uses`]). +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] +pub struct Uses { + /// Handles from the resource heap. + pub heap: bool, + /// Handles from the sampler heap. + pub sampler_heap: bool, + /// Wave and quad operations. + pub wave: bool, + /// 64-bit integers. + pub int64: bool, +} + +/// What [`Module::write`] writes ([`Module::plan`]). +struct Plan { + /// Per instruction: written. + live: Vec, + /// Per block: reached from the entry. + seen: Vec, + /// The blocks written, in order. + layout: Vec, + /// Per block: its place in `layout` (`u64::MAX` if not written). + pos: Vec, + /// Per folded block: its one predecessor and its target. + fold: Vec>, +} + +impl Plan { + /// The block a branch to `t` lands in (through folded blocks). + fn to(&self, mut t: usize) -> usize { + while let Some((_, h)) = self.fold[t] { + t = h; + } + t + } + + /// The block an edge from `b` leaves from (through folded blocks). + fn src(&self, mut b: usize) -> usize { + while let Some((p, _)) = self.fold[b] { + b = p; + } + b + } + + /// Whether a phi of block `x` keeps its entry from block `b`: the edge + /// is still there (not a constant branch's other edge, not from a block + /// left out). + fn edge(&self, m: &Module, b: usize, x: usize) -> bool { + self.seen[b] && successors(m.term(b)).iter().any(|&s| self.to(s) == x) + } +} + /// Calls `f` with every value `op` reads, in operand order. fn for_each_operand(op: &Op, mut f: impl FnMut(V)) { match op { @@ -1094,7 +1262,11 @@ mod tests { for &v in &stepped[1..read.max(1)] { acc = m.bin(exit, Bin::Add, acc, v); } - let _ = m.call(exit, f, vec![acc, cur[0]]); + // What the program does with it (a store, say): the rest is live + // because this reads it. + let sink_ty = m.func_ty(void, vec![i32t, i32t]); + let sink = m.function("dx.op.sink", sink_ty, Some(Attr::NoUnwind), false); + let _ = m.call(exit, sink, vec![acc, cur[0]]); m.terminate(exit, Term::Ret); m } @@ -1111,7 +1283,7 @@ mod tests { fn live_by_passes(m: &Module) -> Vec { let mut live = vec![false; m.insts.len()]; for b in &m.blocks { - for &i in &b.body { + for &i in b.body.iter().filter(|&&i| m.rooted(i)) { live[i as usize] = true; } if let Some(Term::CondBr(V::Inst(c), ..)) = b.term { @@ -1163,6 +1335,11 @@ mod tests { m.set_phi(cyc_a, vec![(cyc_b, entry)]); m.set_phi(cyc_b, vec![(cyc_a, entry)]); let sum = m.bin(join, Bin::Add, read, b); + // An unread sum would be dropped too: a store keeps it. + let void = m.void(); + let sink_ty = m.func_ty(void, vec![i32t]); + let sink = m.function("dx.op.sink", sink_ty, Some(Attr::NoUnwind), false); + let _ = m.call(join, sink, vec![sum]); m.terminate(join, Term::Ret); let ids = |v: V| match v { V::Inst(i) => i as usize, @@ -1213,6 +1390,217 @@ mod tests { assert_eq!(build(false), build(true)); } + /// A module with `main`, `n` blocks and a call with effects to keep + /// values alive (what a store does). + fn module(n: usize) -> (Module, Vec, V) { + let mut m = Module::default(); + let (i32t, void) = (m.int(32), m.void()); + let ty = m.func_ty(void, vec![i32t]); + let sink = m.function("dx.op.sink", ty, Some(Attr::NoUnwind), false); + let main_ty = m.func_ty(void, vec![]); + m.function("main", main_ty, None, true); + let blocks = (0..n).map(|_| m.new_block()).collect(); + (m, blocks, sink) + } + + /// A branch on a constant takes its one edge: what only the other side + /// reaches is not written, and a phi loses that side's entry and keeps + /// the others. + #[test] + fn a_constant_branch_drops_its_other_side_and_that_side_s_phi_entry() { + let (mut m, b, sink) = module(6); + let [entry, p, q, a, dead, join] = b[..] else { unreachable!() }; + let i32t = m.int(32); + let (one, two, three) = (m.i32(1), m.i32(2), m.i32(3)); + let x = m.cmp(entry, pred::EQ, one, two); + m.terminate(entry, Term::CondBr(x, p, q)); + let t = m.bool(true); + m.terminate(p, Term::CondBr(t, a, dead)); + m.terminate(q, Term::Br(join)); + let _ = m.call(a, sink, vec![one]); + m.terminate(a, Term::Br(join)); + let _ = m.call(dead, sink, vec![two]); + m.terminate(dead, Term::Br(join)); + let phi = m.phi(join, i32t); + m.set_phi(phi, vec![(one, a), (two, dead), (three, q)]); + let _ = m.call(join, sink, vec![phi]); + m.terminate(join, Term::Ret); + let plan = m.plan(); + assert!(!plan.seen[dead] && !plan.layout.contains(&dead)); + assert!(!plan.edge(&m, dead, join), "the dead side's entry goes"); + assert!(plan.edge(&m, a, join) && plan.edge(&m, q, join), "the others stay"); + // `q` splits a critical edge (entry has two successors, the join + // two predecessors): it stays. + assert_eq!(plan.fold[q], None); + let _ = m.write(); + } + + /// A loop whose back edge is a constant branch's other edge is no loop: + /// the latch is not written and the header's phi keeps the entry's + /// value only. + #[test] + fn a_loop_whose_back_edge_is_never_taken() { + let (mut m, b, sink) = module(4); + let [entry, head, latch, exit] = b[..] else { unreachable!() }; + let i32t = m.int(32); + let (zero, one) = (m.i32(0), m.i32(1)); + m.terminate(entry, Term::Br(head)); + let i = m.phi(head, i32t); + let next = m.bin(head, Bin::Add, i, one); + let f = m.bool(false); + m.terminate(head, Term::CondBr(f, latch, exit)); + m.terminate(latch, Term::Br(head)); + m.set_phi(i, vec![(zero, entry), (next, latch)]); + let _ = m.call(exit, sink, vec![next]); + m.terminate(exit, Term::Ret); + let plan = m.plan(); + assert!(!plan.seen[latch]); + assert!(plan.edge(&m, entry, head) && !plan.edge(&m, latch, head)); + assert_eq!(plan.layout, [entry, head, exit]); + let _ = m.write(); + } + + /// An empty block that is a phi's predecessor: folded only where its + /// predecessor then reaches the phi's block once, the phi's entry then + /// coming from that predecessor. + #[test] + fn empty_blocks_before_a_phi_fold_only_where_the_entry_can_move() { + let (mut m, b, sink) = module(7); + let [entry, f, t, p2, f2, q2, t2] = b[..] else { unreachable!() }; + let i32t = m.int(32); + let (one, two) = (m.i32(1), m.i32(2)); + // entry branches to `t` both directly and through empty `f`, with + // different values: `f` stays. + let x = m.cmp(entry, pred::EQ, one, two); + m.terminate(entry, Term::CondBr(x, f, t)); + m.terminate(f, Term::Br(t)); + let phi = m.phi(t, i32t); + m.set_phi(phi, vec![(one, entry), (two, f)]); + let _ = m.call(t, sink, vec![phi]); + let y = m.cmp(t, pred::EQ, phi, two); + m.terminate(t, Term::CondBr(y, p2, q2)); + // `p2` reaches `t2` only through empty `f2`, which has one + // predecessor and splits no critical edge: folded, its entry now + // `p2`'s. + let _ = m.call(p2, sink, vec![one]); + m.terminate(p2, Term::Br(f2)); + m.terminate(f2, Term::Br(t2)); + let _ = m.call(q2, sink, vec![two]); + m.terminate(q2, Term::Br(t2)); + let phi2 = m.phi(t2, i32t); + m.set_phi(phi2, vec![(one, f2), (two, q2)]); + let _ = m.call(t2, sink, vec![phi2]); + m.terminate(t2, Term::Ret); + let plan = m.plan(); + assert_eq!(plan.fold[f], None); + assert_eq!(plan.fold[f2], Some((p2, t2))); + assert_eq!((plan.src(f2), plan.to(f2)), (p2, t2)); + assert!(plan.edge(&m, f2, t2) && plan.edge(&m, q2, t2)); + assert!(!plan.layout.contains(&f2)); + let _ = m.write(); + } + + /// A value only a dropped value reads is dropped too; operations with + /// effects (calls neither read-none nor read-only: stores, atomics, + /// discard, barriers, marks; stores and atomic instructions) never are. + #[test] + fn only_values_with_effects_or_readers_are_written() { + let (mut m, b, sink) = module(1); + let entry = b[0]; + let (i32t, void) = (m.int(32), m.void()); + let ty = m.func_ty(i32t, vec![i32t]); + let pure = m.function("dx.op.pure", ty, Some(Attr::ReadNone), false); + let reads = m.function("dx.op.reads", ty, Some(Attr::ReadOnly), false); + let barrier_ty = m.func_ty(void, vec![i32t]); + let barrier = m.function("dx.op.barrier", barrier_ty, Some(Attr::NoDuplicate), false); + let (one, two) = (m.i32(1), m.i32(2)); + let x = m.bin(entry, Bin::Add, one, two); + let unread = m.bin(entry, Bin::Mul, x, two); + let p = m.call(entry, pure, vec![one]); + let r = m.call(entry, reads, vec![one]); + let kept = m.bin(entry, Bin::Sub, two, one); + let s = m.call(entry, sink, vec![kept]); + let bar = m.call(entry, barrier, vec![one]); + let cell = m.global("cell", i32t, 3); + m.store(entry, cell, one); + let old = m.atomic(entry, Rmw::Add, cell, two); + m.terminate(entry, Term::Ret); + let live = m.live(); + let at = |v: V| match v { + V::Inst(i) => live[i as usize], + _ => unreachable!(), + }; + assert!(!at(x) && !at(unread) && !at(p) && !at(r), "unread pure values"); + assert!(at(kept) && at(s) && at(bar) && at(old), "effects and what they read"); + // The store has no value of its own: it is the instruction after the + // atomic's operand list, kept as its body entry. + let store = m.blocks[entry].body.iter().any(|&i| matches!(m.insts[i as usize].op, Op::Store(..)) && live[i as usize]); + assert!(store); + let _ = m.write(); + } + + /// A constant global only dropped values read is not declared; one a + /// written load reads is. + #[test] + fn constant_globals_nothing_reads_are_left_out() { + let (mut m, b, sink) = module(1); + let entry = b[0]; + let i32t = m.int(32); + let arr = m.array(2, i32t); + let (one, two) = (m.i32(1), m.i32(2)); + let init = m.aggregate(arr, &[one, two]); + let unread = m.constant_global("unread", init); + let read = m.constant_global("read", init); + let zero = m.i32(0); + let p = m.element(entry, unread, zero); + let _ = m.load(entry, p); + let q = m.element(entry, read, one); + let x = m.load(entry, q); + let _ = m.call(entry, sink, vec![x]); + m.terminate(entry, Term::Ret); + let plan = m.plan(); + let ((globals, n), _) = m.kept(&plan); + let (V::Global(u), V::Global(r)) = (unread, read) else { unreachable!() }; + assert_eq!((globals[u as usize], globals[r as usize], n), (u32::MAX, 0, 1)); + let _ = m.write(); + } + + /// What the shader flags declare is what written instructions use: a + /// heap handle or a 64-bit operation only a dropped value or a never + /// taken edge reaches counts for nothing. + #[test] + fn uses_count_only_what_is_written() { + let (mut m, b, sink) = module(3); + let [entry, live, dead] = b[..] else { unreachable!() }; + let (i32t, i64t, handle_t) = (m.int(32), m.int(64), m.int(8)); + let i1t = m.int(1); + let heap_ty = m.func_ty(handle_t, vec![i32t, i32t, i1t, i1t]); + let heap = m.function("dx.op.createHandleFromHeap", heap_ty, Some(Attr::ReadNone), false); + let (op, zero, no) = (m.i32(218), m.i32(0), m.bool(false)); + let yes = m.bool(true); + // An unread heap handle and 64-bit add where the program goes; a + // read sampler-heap handle behind a constant branch's other edge. + let _ = m.call(entry, heap, vec![op, zero, no, no]); + let five = m.int_const(i64t, 5); + let _ = m.bin(entry, Bin::Add, five, five); + m.terminate(entry, Term::CondBr(yes, live, dead)); + let one = m.i32(1); + let _ = m.call(live, sink, vec![one]); + m.terminate(live, Term::Ret); + let h = m.call(dead, heap, vec![op, zero, yes, no]); + let _ = m.call(dead, sink, vec![one]); + let _ = h; + m.terminate(dead, Term::Ret); + assert_eq!(m.uses(), Uses::default()); + // Read where the program goes: counted. + let h = m.call(live, heap, vec![op, zero, no, no]); + let wide = m.bin(live, Bin::Add, five, five); + let t = m.cast(live, Cast::Trunc, wide, i32t); + let _ = (m.call(live, sink, vec![t]), h); + let u = m.uses(); + assert!(u.int64 && !u.heap && !u.sampler_heap, "{u:?}"); + } + #[test] fn successors_of_each_terminator() { assert!(successors(None).is_empty()); @@ -1221,13 +1609,13 @@ mod tests { assert_eq!(&*successors(Some(Term::CondBr(V::Const(0), 3, 5))), &[3, 5]); } - /// The written bytes are pinned to what the writer produced before the - /// worklist and the reused record buffers. + /// The written bytes are pinned (anew when the writer began to drop + /// unread values: the module's last call became one with effects). #[test] fn written_bytes_unchanged() { for ((regs, stages, read), len, hash) in [ - ((64, 64, 64), 38_916, 0x9586_730c_f953_4a45), - ((128, 256, 32), 295_952, 0x89e5_de2d_64f0_8785), + ((64, 64, 64), 38_956, 0xf0d5_9e83_b39d_a635), + ((128, 256, 32), 252_532, 0x5961_0d0b_12c3_4414), ] { let bytes = synthetic(regs, stages, read).write(); assert_eq!((bytes.len(), fnv(&bytes)), (len, hash), "{regs}x{stages}"); diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index bd42a194e7..a9879adfa4 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -570,6 +570,17 @@ impl Shader { pub fn finish(mut self) -> Vec { let ud_size = (self.user_data * 4).next_multiple_of(16); self.fix_user_data_size(ud_size); + // The flags of what lowering made, as the module writes it: what only + // unread values or never-taken edges used is not written. + let uses = self.m.uses(); + for (flag, used) in [ + (flags::RESOURCE_HEAP, uses.heap), + (flags::SAMPLER_HEAP, uses.sampler_heap), + (flags::WAVE_OPS, uses.wave), + (flags::INT64, uses.int64), + ] { + self.flags = if used { self.flags | flag } else { self.flags & !flag }; + } let mut resources = None; let mut bindings = Vec::new(); let i32c = |s: &mut Self, v: u32| { From 850b66ffd7e06a9c21bc20ccd9168a627f653f3d Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 13:08:23 +0100 Subject: [PATCH 75/83] Shaders: one handle per descriptor at a fixed address, and per join The console compiler reloads a descriptor before each use rather than keep it (`indirect_diffuse_lighting:CS_ScreenProbes_ActivateRays` loads table offset 0x640 2,399 times, once before each of its typed buffer loads), and lowering made a heap handle at each load: index arithmetic, for heap buffers the host-view guard, `createHandleFromHeap`, `annotateHandle`. A descriptor resource tracking finds at a fixed address (a table or heap entry, no dynamic term, not a waterfall loop's per-lane load) now gets one handle for the program, made in the entry block from the root parameter's user data. A descriptor chosen by control flow (a phi of heap indices at a join) gets one handle made in its join block, shared by every access the join dominates, instead of one per access. Read marks still go with each access, at the handle's index. ActivateRays (with nested joins allowed, the commit after this one): 2,608 heap handles before the DXIL writer's folding, 674 after it, 65 with this. Whole list, translate --list --validate: 0 newly failing; DXIL bitcode 1,246,729,828 -> 1,197,299,944 (-4.0 %) bytes. Tests: `descriptors_reloaded_from_a_root_table_share_one_handle` (a descriptor loaded in a branch and again after it: one handle), written heap handles counted from the module (`Module::written_calls`). Co-Authored-By: Claude Opus 5.5 --- crates/victory-shader/src/emit/bitcode.rs | 11 ++ crates/victory-shader/src/emit/lower.rs | 201 ++++++++++++++++++---- 2 files changed, 179 insertions(+), 33 deletions(-) diff --git a/crates/victory-shader/src/emit/bitcode.rs b/crates/victory-shader/src/emit/bitcode.rs index 0a4a44b080..6dcd2826d1 100644 --- a/crates/victory-shader/src/emit/bitcode.rs +++ b/crates/victory-shader/src/emit/bitcode.rs @@ -579,6 +579,17 @@ impl Module { } } + /// Calls of functions named `name` that [`Module::write`] writes. + #[cfg(test)] + pub fn written_calls(&self, name: &str) -> usize { + let plan = self.plan(); + let calls = plan.layout.iter().flat_map(|&b| &self.blocks[b].body); + calls + .filter(|&&i| plan.live[i as usize]) + .filter(|&&i| matches!(self.insts[i as usize].op, Op::Call(f, _) if self.funcs[f as usize].name == name)) + .count() + } + /// The globals and functions [`Module::write`] declares, each kept /// one's new index and their number: functions declared and not called, /// and constant globals nothing reads, are left out (the validator diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index c4b4b381fc..f33bcddfae 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -57,6 +57,9 @@ pub(crate) struct Lowered { /// Heap handles made with a non-uniform index. #[cfg(test)] pub nonuniform_handles: u32, + /// Heap handles written. + #[cfg(test)] + pub heap_handles: u32, /// Whether the program uses wave operations. #[cfg(test)] pub wave_ops: bool, @@ -169,6 +172,10 @@ fn half_shift(width: u32) -> u32 { if width == 16 { 0 } else { 15 - width } } +/// A descriptor load's address given by root parameters alone: root +/// parameter and byte offset. +type EntryAddress = (usize, u32); + struct Lower<'a> { s: Shader, x: &'a Parts<'a>, @@ -202,6 +209,14 @@ struct Lower<'a> { exports: HashMap, interps: HashMap, handles: HashMap<(usize, Site, u8, bool, u32), V>, + /// Handles made in the entry block for descriptors at addresses the + /// root parameters alone give (table and heap loads with no other + /// term), by base value, byte offset, dword, offset register, sampler + /// heap and properties ([`Lower::entry_address`]). + entry_handles: HashMap<(EntryAddress, u8, bool, u32), V>, + /// Handles of descriptors chosen by control flow, made in their join + /// block, by the choice (its `Debug` text), sampler heap and properties. + join_handles: HashMap<(String, bool, u32), V>, /// Blocks splitting the edge from one IR block to another. edges: HashMap<(usize, usize), usize>, /// Per IR block: a `done` export is behind every lane entering it. @@ -643,6 +658,8 @@ impl<'a> Lower<'a> { exports: x.io.exports.iter().map(|e| (e.site, e)).collect(), interps: x.io.interps.iter().map(|(s, i)| (*s, i)).collect(), handles: HashMap::new(), + entry_handles: HashMap::new(), + join_handles: HashMap::new(), edges: HashMap::new(), exported: vec![false; p.blocks.len()], rpo: vec![usize::MAX; p.blocks.len()], @@ -1363,6 +1380,8 @@ impl<'a> Lower<'a> { #[cfg(test)] nonuniform_handles: self.s.nonuniform_handles, #[cfg(test)] + heap_handles: self.s.m.written_calls("dx.op.createHandleFromHeap") as u32, + #[cfg(test)] wave_ops: self.s.flags & flags::WAVE_OPS != 0, #[cfg(test)] rovs: self.s.flags & flags::ROVS != 0, @@ -4948,6 +4967,25 @@ impl<'a> Lower<'a> { self.heap[1] |= props.0 & 0x1000 != 0; } match src { + Source::Loaded { load, first } + if let Some(address) = self.entry_address(*load) => + { + // The same descriptor wherever it is loaded: the console + // compiler reloads one before every use rather than keep it + // (ActivateRays: 2,399 loads of one), and one handle made in + // the entry block serves them all. + let key = (address, *first, sampler, props.0); + if let Some(&h) = self.entry_handles.get(&key) { + return Ok(h); + } + let here = std::mem::replace(&mut self.cur, self.s.entry); + let index = self.entry_heap_index(address, *first, sampler); + let index = self.buffer_guard(src, index, sampler, props); + let h = self.s.heap_handle(self.cur, index, sampler, false, props); + self.cur = here; + self.entry_handles.insert(key, h); + Ok(h) + } Source::Loaded { load, first } => { let key = (self.cur, *load, *first, sampler, props.0); if let Some(&h) = self.handles.get(&key) { @@ -5054,42 +5092,25 @@ impl<'a> Lower<'a> { self.s.sampler_choices.push((ha, hb, phi)); Ok(ha) } - Source::Phi { block, args } => { - // Each predecessor computes its heap index at its end; the - // join picks one with a phi. - // shortcut: an edge that is itself a join (if/else nested in - // another) stays refused: the one program it would let - // through, `indirect_diffuse_lighting:CS_ScreenProbes_ - // ActivateRays` (22k branches, 2.6k heap handles), takes the - // AMD driver over 6 GB and a minute to compile (PR #1012 did - // it; take it once pipelines that costly stay off the title's - // pipeline worker). + Source::Phi { block, .. } => { + // One handle at the join for every access the choice reaches + // (each is in a block the join dominates). let _ = site; - let mut incoming = Vec::new(); - for (&q, arg) in self.x.p.blocks[*block].preds.iter().zip(args) { - if self.block[q].is_none() { - continue; - } - let (Some(tail), Source::Loaded { load, first }) = (self.tail[q], arg) else { - return Err("a descriptor chosen by control flow"); - }; - let at = self.edges.get(&(q, *block)).copied().unwrap_or(tail); - // No lane comes this way (`resource` gave it another - // edge's source): any index will do. - if self.never_taken(q, *block) { - incoming.push((self.s.m.i32(0), at)); - continue; - } - let here = std::mem::replace(&mut self.cur, at); - let index = self.heap_index(*load, *first, sampler); - self.cur = here; - incoming.push((index?, at)); + let key = (format!("{src:?}"), sampler, props.0); + if let Some(&h) = self.join_handles.get(&key) { + return Ok(h); } let join = self.block[*block].ok_or("a descriptor chosen by control flow")?; - let phi = self.s.m.phi(join, self.s.t.i32); - self.s.m.set_phi(phi, incoming); - let index = self.buffer_guard(src, phi, sampler, props); - Ok(self.s.heap_handle(self.cur, index, sampler, false, props)) + let here = std::mem::replace(&mut self.cur, join); + let index = self.uniform_heap_index(src, sampler); + let h = index.map(|index| { + let index = self.buffer_guard(src, index, sampler, props); + self.s.heap_handle(self.cur, index, sampler, false, props) + }); + self.cur = here; + let h = h?; + self.join_handles.insert(key, h); + Ok(h) } Source::Select { scc, args } => { // The heap index of each choice, picked by SCC (uniform). @@ -5165,6 +5186,70 @@ impl<'a> Lower<'a> { }) } + /// The address of the descriptor load at `load` when root parameters + /// alone give it (a table or a heap, at a fixed offset: resource + /// tracking found no other term), and not per lane. + fn entry_address(&self, load: Site) -> Option { + let a = self.scalar.get(&load)?; + let fixed = a.dynamic.is_none() && !self.x.res.waterfall.loads.contains(&load); + let root = self.x.native.layout.get(a.param)?.root; + let heap = matches!(root, RootType::Table | RootType::ResourceHeap | RootType::SamplerHeap); + (fixed && heap).then_some((a.param, a.offset)) + } + + /// [`Lower::heap_index`] of a descriptor at a fixed address + /// ([`Lower::entry_address`]), in the entry block. + fn entry_heap_index(&mut self, (param, offset): EntryAddress, first: u8, sampler: bool) -> V { + let entry = self.s.entry; + let base = match self.x.native.layout[param].root { + RootType::Table => self.user_dword(param, 0), + _ => self.s.m.i32(0), + }; + let k = self.s.m.i32(offset.wrapping_add(4 * u32::from(first))); + let addr = self.s.m.bin(entry, Bin::Add, base, k); + let shift = self.s.m.i32(if sampler { 4 } else { 5 }); + self.s.m.bin(entry, Bin::LShr, addr, shift) + } + + /// The heap index of a descriptor every lane shares, chosen by control + /// flow: a phi at its join of the index each predecessor computes at its + /// end. + // shortcut: an edge that is itself a join (if/else nested in another) + // stays refused: the one program it would let through, `indirect_ + // diffuse_lighting:CS_ScreenProbes_ActivateRays` (22k branches, 2.6k + // heap handles), takes the AMD driver over 6 GB and a minute to compile + // (PR #1012 did it; take it once pipelines that costly stay off the + // title's pipeline worker). + fn uniform_heap_index(&mut self, src: &Source, sampler: bool) -> Result { + let Source::Phi { block, args } = src else { + return Err("a descriptor chosen by control flow"); + }; + let mut incoming = Vec::new(); + for (&q, arg) in self.x.p.blocks[*block].preds.iter().zip(args) { + if self.block[q].is_none() { + continue; + } + let (Some(tail), Source::Loaded { load, first }) = (self.tail[q], arg) else { + return Err("a descriptor chosen by control flow"); + }; + let at = self.edges.get(&(q, *block)).copied().unwrap_or(tail); + // No lane comes this way (`resource` gave it another + // edge's source): any index will do. + if self.never_taken(q, *block) { + incoming.push((self.s.m.i32(0), at)); + continue; + } + let here = std::mem::replace(&mut self.cur, at); + let index = self.heap_index(*load, *first, sampler); + self.cur = here; + incoming.push((index?, at)); + } + let join = self.block[*block].ok_or("a descriptor chosen by control flow")?; + let phi = self.s.m.phi(join, self.s.t.i32); + self.s.m.set_phi(phi, incoming); + Ok(phi) + } + /// The heap index of a descriptor that may differ between lanes, /// computed in the current block (or, chosen by control flow, at the /// join). @@ -10935,6 +11020,56 @@ mod tests { } } + #[test] + fn descriptors_reloaded_from_a_root_table_share_one_handle() { + // The view table at s0 (2D textures at entries 0 and 1, a raw UAV at + // dword 16) and a root constant at s1. Entry 0 is loaded and sampled + // in a branch, then loaded again and sampled after it (the console + // compiler reloads a descriptor before each use rather than keep it). + let words = [ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0A02, + 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 + 0xBE88_03FF, + 0x0000_0092, // s_mov_b32 s8, 0x92 (an immediate sampler) + 0xBE89_0380, // s_mov_b32 s9, 0 + 0xBE8A_0380, // s_mov_b32 s10, 0 + 0xBE8B_0380, // s_mov_b32 s11, 0 + 0x7E04_02F0, // v_mov_b32 v2, 0.5 + 0x7E06_02F0, // v_mov_b32 v3, 0.5 + 0x3420_0082, // v_lshlrev_b32 v16, 2, v0 + 0xBF06_8001, // s_cmp_eq_u32 s1, 0 + 0xBF84_0005, // s_cbranch_scc0 -> the reload + 0xF40C_0302, + 0xFA00_0000, // s_load_dwordx8 s[12:19], s[4:5], 0x0 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xF09C_0F08, + 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xF40C_0302, + 0xFA00_0000, // s_load_dwordx8 s[12:19], s[4:5], 0x0 (again) + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xF09C_0F08, + 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] + 0xE070_1000, + 0x800A_0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen + S_ENDPGM, + ]; + let (_, mut used) = texture_and_uav_tables(); + used.retain(|u| u.user_data == 0); + let layout = vec![root(RootType::Table, 0, 0), root(RootType::Constants, 1, 1)]; + let l = lower_with(&words, layout, used).unwrap(); + // One image handle made in the entry block for both loads, and the + // UAV's. + assert_eq!(l.heap_handles, 2); + if let Ok(mut v) = super::super::validator::Validator::load( + super::super::validator::Validator::default_path().as_deref(), + ) { + v.validate(&mut l.dxil.clone()) + .expect("DXIL validation failed"); + } + } + #[test] fn scalar_bit_tests_lower() { // Each tests one bit of a constant into SCC and branches on it (only From 8681044f025dd6203a2249f4fac71ecbe4400cf0 Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 13:08:35 +0100 Subject: [PATCH 76/83] Shader tests: the differential harness binds the view-stride table Since 4243a96a ("16-bit typed buffer accesses pass bits through integer views") a 16-bit typed buffer access reads its view's format kind from the host's view-stride table, root SRV `t255` (`VIEW_STRIDES`), also for views in tables. The differential harness asserted that a translated program's root views are only the case's own (slots 4 and 5), so the case "16-bit and 64-bit arithmetic" (`RWBuffer` stores through `buffer_store_format_d16`) failed on its root SRV 255 before anything ran, in every run with the console compiler since that commit (eed16700 passes, 4243a96a fails). `host::view_strides` builds the table as `victory_gpu` fills it for the harness's view heap (element sizes, the integer and signed bits of typed views of integer formats), and the harness binds it where a program asks. The case now runs and matches the console compiler's program on the RX 6700 XT. Co-Authored-By: Claude Opus 5.5 --- crates/victory-shader/src/emit/diff_tests.rs | 12 +++++---- crates/victory-shader/src/emit/host.rs | 28 ++++++++++++++++++++ 2 files changed, 35 insertions(+), 5 deletions(-) diff --git a/crates/victory-shader/src/emit/diff_tests.rs b/crates/victory-shader/src/emit/diff_tests.rs index 69fda31a9e..65e61147ea 100644 --- a/crates/victory-shader/src/emit/diff_tests.rs +++ b/crates/victory-shader/src/emit/diff_tests.rs @@ -1483,17 +1483,19 @@ fn translated_compute_matches_pc() { } Err(e) => panic!("{name}: {e}"), }; - // Our root views follow the user data in root parameter order. + // Our root views follow the user data in root parameter order: the + // case's own, then the host's view-stride table (16-bit typed + // accesses read their view's format kind there). let mut roots = vec![(0, Root::Constants(user_data(&cs_c, &k)))]; let mut root_views: Vec<(u8, bool)> = cs_c.root_cbvs.iter().map(|&s| (s, false)).collect(); root_views.extend(cs_c.root_srvs.iter().map(|&s| (s, true))); root_views.sort_unstable(); for (n, (slot, srv)) in root_views.into_iter().enumerate() { - assert_eq!(slot, 4 + u8::from(srv), "{name}: root view"); - let data = if srv { - root_srv.clone() + let data = if srv && slot == super::VIEW_STRIDES { + super::host::view_strides(&views) } else { - root_cbv.clone() + assert_eq!(slot, 4 + u8::from(srv), "{name}: root view"); + if srv { root_srv.clone() } else { root_cbv.clone() } }; roots.push((1 + n as u32, Root::View { srv, data })); } diff --git a/crates/victory-shader/src/emit/host.rs b/crates/victory-shader/src/emit/host.rs index 5ab0a9e65f..856eb87bb2 100644 --- a/crates/victory-shader/src/emit/host.rs +++ b/crates/victory-shader/src/emit/host.rs @@ -1260,6 +1260,34 @@ pub enum View<'a> { NullBuffers, } +/// The host's view-stride table (`t`[`super::VIEW_STRIDES`]) for a view +/// heap of `views`, as `victory_gpu` fills it: per slot the element size of +/// a buffer view (4 for raw ones), with [`super::VIEW_INTEGER`] (and +/// [`super::VIEW_SIGNED`]) for typed views of integer formats; 0 elsewhere. +#[cfg(test)] +pub fn view_strides(views: &[View]) -> Vec { + let kind = |f: DXGI_FORMAT| match f { + DXGI_FORMAT_R32G32B32A32_UINT | DXGI_FORMAT_R16G16B16A16_UINT | DXGI_FORMAT_R32G32_UINT + | DXGI_FORMAT_R10G10B10A2_UINT | DXGI_FORMAT_R8G8B8A8_UINT | DXGI_FORMAT_R16G16_UINT + | DXGI_FORMAT_R32_UINT | DXGI_FORMAT_R8G8_UINT | DXGI_FORMAT_R16_UINT | DXGI_FORMAT_R8_UINT => super::VIEW_INTEGER, + DXGI_FORMAT_R32G32B32A32_SINT | DXGI_FORMAT_R16G16B16A16_SINT | DXGI_FORMAT_R32G32_SINT + | DXGI_FORMAT_R8G8B8A8_SINT | DXGI_FORMAT_R16G16_SINT | DXGI_FORMAT_R32_SINT + | DXGI_FORMAT_R8G8_SINT | DXGI_FORMAT_R16_SINT | DXGI_FORMAT_R8_SINT => super::VIEW_INTEGER | super::VIEW_SIGNED, + _ => 0, + }; + views + .iter() + .map(|v| match *v { + View::Buffer { stride: Stride::Raw, .. } | View::RawUav(_) => 4, + View::Buffer { stride: Stride::Typed, .. } => 16, + View::Buffer { stride: Stride::Structured(n), .. } => n, + View::Buffer { stride: Stride::Format(f, n), .. } | View::TypedUav(f, _, n) => n | kind(f), + View::HalfUav(_) => 8, + _ => 0, + }) + .collect() +} + /// How [`View::Buffer`] is viewed. #[cfg(test)] #[derive(Clone, Copy)] From a1a2077a3d9ab6bf51d457c1a3f86db166554446 Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 13:53:55 +0100 Subject: [PATCH 77/83] Shaders: vertex, geometry and mesh programs with UAVs say so in their flags Since the read marks, every vertex, geometry and mesh program that reads a texture from the resource heap writes the marks' UAV (the write marks do the same for programs writing through views), and its shader flags did not declare "UAVs at every stage" (ShaderFlags bit 16, SFI0 0x4): the validator refused 5,046 programs of the title's list with "Flags must match usage" (VS_OctaWindFire_e6901d4b: declared 0x40000010, actual 0x40010010). The runtime does not validate, so their pipelines were made, but a driver may trust the flags. The validator counts UAV ranges the module declares, not UAVs indexed from the heap: `finish` sets the flag (and the SFI0 bit) when a program that is neither a pixel nor a compute program declares any (root UAVs, the memory bitmap, the marks). Counting every handle annotated as a UAV instead set it wrongly for 26 mesh and vertex programs whose only UAVs come from the heap (`MST_DS_TerrainTransform` and others: declared 0x40092000, actual 0x40082000). Whole list (translate --list --validate), validated: vertex and pixel 13,313 -> 14,254 of 14,254, mesh 4,625 -> 8,694 of 8,765 (the other 71 have outputs over 32 KB), compute 1,984 of 2,732 unchanged (748 sample with implicit LOD); no program newly fails. Test: `emit::shader::tests::uavs_outside_pixel_and_compute_programs_are_declared` (a marked vertex, pixel and compute program and a vertex program writing a heap-indexed UAV each pass the validator; the marked vertex program fails as the list's did without the flag, the heap one with it). Co-Authored-By: Claude Opus 5.5 --- crates/victory-shader/src/emit/shader.rs | 68 +++++++++++++++++++++++- 1 file changed, 67 insertions(+), 1 deletion(-) diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index a9879adfa4..441dae7435 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -58,6 +58,8 @@ pub(crate) mod flags { pub const RAW_BUFFERS: u64 = 1 << 4; pub const STENCIL_REF: u64 = 1 << 11; pub const TYPED_UAV_LOADS: u64 = 1 << 13; + /// UAVs in a vertex, geometry or mesh program. + pub const UAVS_EVERY_STAGE: u64 = 1 << 16; pub const ROVS: u64 = 1 << 18; pub const WAVE_OPS: u64 = 1 << 19; pub const INT64: u64 = 1 << 20; @@ -581,6 +583,15 @@ impl Shader { ] { self.flags = if used { self.flags | flag } else { self.flags & !flag }; } + // UAVs outside pixel and compute programs (the write and read marks + // of vertex, geometry and mesh programs), as DXC counts them: UAV + // ranges declared below, not UAVs indexed from the heap. + let compute = self.threads.is_some() && self.mesh.is_none() && self.gs.is_none(); + let declared_uavs = + !self.root_uavs.is_empty() || self.memory_dirty.is_some() || self.view_writes.is_some(); + if declared_uavs && !self.pixel && !compute { + self.flags |= flags::UAVS_EVERY_STAGE; + } let mut resources = None; let mut bindings = Vec::new(); let i32c = |s: &mut Self, v: u32| { @@ -693,7 +704,7 @@ impl Shader { srvs = Some(self.m.md_node(list)); } let mut uavs = None; - if !self.root_uavs.is_empty() || self.memory_dirty.is_some() || self.view_writes.is_some() { + if declared_uavs { let ty = self .m .named_struct("struct.RWByteAddressBuffer", vec![self.t.i32]); @@ -916,6 +927,9 @@ impl Shader { dxil.extend(&bitcode); let mut features = 0u64; + if self.flags & flags::UAVS_EVERY_STAGE != 0 { + features |= 0x4; + } if self.flags & flags::STENCIL_REF != 0 { features |= 0x200; } @@ -1023,3 +1037,55 @@ impl Shader { Some(self.m.md_node(list)) } } + +#[cfg(all(test, windows))] +mod tests { + use super::super::bitcode::Term; + use super::*; + + /// A program that sets a bit through the write marks' UAV, or (`heap`) + /// through a UAV indexed from the heap: a vertex (`pixel` false, no + /// thread-group size), pixel or compute program. + fn marked(pixel: bool, threads: Option<[u32; 3]>, heap: bool) -> Vec { + let mut s = Shader::new(pixel); + s.threads = threads; + let b = s.entry; + let h = if heap { + let index = s.m.i32(0); + s.heap_handle(b, index, false, false, (11 | 0x1000, 0)) + } else { + s.view_writes_handle() + }; + let (or, zero, one) = (s.m.i32(2), s.m.i32(0), s.m.i32(1)); + let iu = s.m.undef(s.t.i32); + let i32t = s.t.i32; + s.op(b, "atomicBinOp.i32", Attr::NoUnwind, i32t, 78, &[h, or, zero, iu, iu, one]); + s.m.terminate(b, Term::Ret); + s.finish() + } + + /// A vertex program writing a declared UAV declares UAVs at every stage + /// (the validator refuses it otherwise: "Flags must match usage", the + /// 5,046 programs of the title's list); pixel and compute programs need + /// not, nor a vertex program whose UAVs all come from the heap (the + /// validator counts declared ranges only: 26 mesh and vertex programs). + #[test] + fn uavs_outside_pixel_and_compute_programs_are_declared() { + let mut validator = super::super::validator::Validator::load( + super::super::validator::Validator::default_path().as_deref(), + ) + .ok(); + for (name, pixel, threads, heap) in [ + ("vertex", false, None, false), + ("pixel", true, None, false), + ("compute", false, Some([1, 1, 1]), false), + ("vertex, heap", false, None, true), + ] { + let mut dxil = marked(pixel, threads, heap); + if let Some(v) = validator.as_mut() { + v.validate(&mut dxil) + .unwrap_or_else(|e| panic!("{name}: {e}")); + } + } + } +} From 4015a182e3999bbaa881f6831360eb257f168c82 Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 14:26:11 +0100 Subject: [PATCH 78/83] Shaders: quad reads in pixel programs reach the helpers at triangle edges The console runs pixel programs in whole-quad mode: in every quad a triangle edge crosses, the pixels outside the triangle run as helpers, and the compiler takes derivatives of computed values (and quad reads) by reading the neighbour's register with DPP `quad_perm` or `ds_swizzle`. We lowered those reads to `WaveReadLaneAt` unless the program discards. Wave operations leave helper lanes out on the host, and on AMD a read of one gives 0: every pixel whose quad neighbour lies outside the triangle took a wrong derivative, along every triangle edge. WARP includes helpers in wave reads, so the tests passed there. Quad-local reads in pixel programs now always go through quad reads (`QuadReadLaneAt`), as they already did after a discard. What the host guarantees there: helper lanes execute the program so that derivatives can be taken, and quad operations include them (wave operations do not), so a quad read of a helper gives the value that helper computed, as the console's DPP read of a whole-quad-mode lane does. A discarded pixel stays a helper in the same way. Tests: two control-flow cases draw a triangle whose diagonal crosses quads (`ddx_fine`, `ddy_fine`, `QuadReadAcrossDiagonal`, `QuadReadLaneAt` of a computed value, console compiler against PC DXC). "derivatives and quad reads across a triangle edge": before, RX 6700 XT 24 of 256 texels differ (texel (0, 0): ddx -1 instead of 15, the helper read as 0), WARP 0; now 0 and 0. "discard, then derivatives and quad reads across a triangle edge" discards some neighbours before the reads (the path that used quad reads already): 0 and 0. Whole list (translate --list --validate): 3,005 pixel programs change, 84,589 read sites (median 15 per program, at most 732); no program changes outcome. DXIL 1,197,299,944 -> 1,203,716,752 bytes (+0.54 %) on top of the writer folding (on main without it: 1,423,424,800 -> 1,429,871,224), blocks unchanged. Co-Authored-By: Claude Opus 5.5 --- crates/victory-shader/src/emit/flow_tests.rs | 51 +++++++++++++++++--- crates/victory-shader/src/emit/lower.rs | 10 ++-- 2 files changed, 49 insertions(+), 12 deletions(-) diff --git a/crates/victory-shader/src/emit/flow_tests.rs b/crates/victory-shader/src/emit/flow_tests.rs index 8945cdd1aa..73484c9bbd 100644 --- a/crates/victory-shader/src/emit/flow_tests.rs +++ b/crates/victory-shader/src/emit/flow_tests.rs @@ -252,6 +252,29 @@ const PS_CASES: &[(&str, &str)] = &[ return float4(ddx_fine(v), ddy_fine(v), v, 1); }"#, ), + // Derivatives and quad reads of values each pixel computes, on a + // triangle whose edge crosses quads: the neighbours outside it are + // helpers (`EDGE`). + ( + "derivatives and quad reads across a triangle edge", + r#"[RootSignature(RS)] float4 ps(V i) : SV_Target { + uint2 p = uint2(i.pos.xy); + float v = p.x * 3.0 + p.y * 5.0 + 1; + v = v * v; + return float4(ddx_fine(v), ddy_fine(v), QuadReadAcrossDiagonal(v), QuadReadLaneAt(v, 0)); + }"#, + ), + // The same with some neighbours discarded before the reads: helpers too. + ( + "discard, then derivatives and quad reads across a triangle edge", + r#"[RootSignature(RS)] float4 ps(V i) : SV_Target { + uint2 p = uint2(i.pos.xy); + float v = p.x * 3.0 + p.y * 5.0 + 1; + v = v * v; + if (((p.x * 7 + p.y * 3) & 5) == 5) discard; + return float4(ddx_fine(v), ddy_fine(v), QuadReadAcrossDiagonal(v), QuadReadLaneAt(v, 0)); + }"#, + ), ( "discard with depth and a second target", r#"struct O { float4 c : SV_Target0; float4 d : SV_Target1; float z : SV_Depth; }; @@ -268,6 +291,9 @@ const PS_CASES: &[(&str, &str)] = &[ ), ]; +/// Pixel cases named with this draw a triangle whose edge crosses quads. +const EDGE: &str = "triangle edge"; + /// Per-lane inputs: four dwords per lane from a fixed hash (low bits vary /// lane to lane; a few lanes hold larger values). fn lane_inputs(lanes: u32) -> Vec { @@ -441,17 +467,23 @@ fn run(pick: &dyn Fn(&str) -> bool) -> Vec { )); } } - // Pixel shapes. + // Pixel shapes: a triangle covering the target, or for cases named + // with `EDGE` one whose diagonal crosses quads. let vertices = [ -1.0, -1.0, 0.5, 1.0, 0.0, 1.0, // -1.0, 3.0, 0.5, 1.0, 0.0, -1.0, // 3.0, -1.0, 0.5, 1.0, 2.0, 1.0, ]; - let draw = |roots| Draw { + let half = [ + -1.0, -1.0, 0.5, 1.0, 0.0, 1.0, // + -1.0, 1.1, 0.5, 1.0, 0.0, -0.05, // + 1.1, -1.0, 0.5, 1.0, 1.05, 1.0, + ]; + let draw = |roots, edge: bool| Draw { roots, textures: &[], samplers: &[], - vertices: &vertices, + vertices: if edge { &half } else { &vertices }, stride: 24, size: (16, 16), mesh_groups: 0, @@ -481,10 +513,13 @@ fn run(pick: &dyn Fn(&str) -> bool) -> Vec { .draw( &root_t, &pso_t, - &draw(vec![ - (0, Root::Constants(console_user_data(&vs_c))), - (1, Root::Constants(console_user_data(&ps_c))), - ]), + &draw( + vec![ + (0, Root::Constants(console_user_data(&vs_c))), + (1, Root::Constants(console_user_data(&ps_c))), + ], + name.contains(EDGE), + ), ) .unwrap_or_else(|e| panic!("{name}: {label}: {e}")); let (vs_p, ps_p) = ( @@ -499,7 +534,7 @@ fn run(pick: &dyn Fn(&str) -> bool) -> Vec { .draw( &root_p, &pso_p, - &draw(vec![(0, Root::Constants(vec![0; 4]))]), + &draw(vec![(0, Root::Constants(vec![0; 4]))], name.contains(EDGE)), ) .unwrap(); let bad: Vec = (0..got.len()).filter(|&t| got[t] != want[t]).collect(); diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index f33bcddfae..5c483b4e97 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -2937,11 +2937,13 @@ impl<'a> Lower<'a> { r } - /// Whether a quad-local read must reach discarded lanes: after a pixel's - /// discard they are the host's helpers, which only quad reads see (wave - /// reads give 0 from them on AMD). + /// Whether a quad-local read must reach helper lanes: in a pixel program + /// every quad a triangle edge crosses has some (the console's whole-quad + /// mode runs them; discarded pixels stay helpers too), and only quad + /// reads see them on the host (wave reads give 0 from them on AMD: wrong + /// derivatives of computed values along every triangle edge). fn helpers_read(&self, quad: bool) -> bool { - quad && self.s.pixel && !self.x.st.discards.is_empty() + quad && self.s.pixel } /// `v_readfirstlane_b32`'s result `first` of `own` in a pixel shader: From 315cea185d2505ed84643b2b47c39c224e757837 Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 15:26:43 +0100 Subject: [PATCH 79/83] GPU: barriers start from the states resources are in: prelude order, the clamp's own buffer The debug layer reported ~16 resource-state errors a second in the world on main (run light21) and with the queue order (light19), four kinds: Depth twins, and 16-bit depth textures with twins (COPY_SOURCE, UNORDERED_ ACCESS and COMMON against DEPTH_WRITE): a list's prelude swapped each texture's real state for the one the list leaves before recording the twin copies it owed, so those copies moved the textures from the wrong states. The prelude now records the copies from the real states, then the list's moves from them, and only then stores the states the list leaves. The title's 174 MB GPU heap, bound as a vertex buffer while in UNORDERED_ ACCESS, and barriers on it disagreeing with the state an earlier vertex binding promoted it to: our only transitions on a title buffer's copy were the indirect clamp's, UAV to INDIRECT_ARGUMENT and back to UAV. The clamp now reads the title's records through a root view and writes the clamped ones into an argument buffer of the list's own, which the execution reads; only that buffer is transitioned (common, unordered access, indirect argument, common). Title buffers' copies are never transitioned: common between submissions, promoted by every use, ordered by unordered-access barriers (the shortcut is in indirect.rs). The clamp no longer writes the copy of the title's memory; the capture's read-back reads the clamped records from the list's buffer. Tests: a transition log (every barrier built on the test thread) replayed in GPU order by the debug layer's rule: twin::tests::prelude_copies_start_ from_the_real_states (fails on the old order: "before COPY_SOURCE, the resource is in COMMON", run light21's message) and indirect::tests:: argument_buffers_move_from_their_current_states (two lists in either order; the title's copy untouched); the clamp tests now also check the whole title copy is as written. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/capture.rs | 16 +-- crates/victory-gpu/src/draw.rs | 14 +-- crates/victory-gpu/src/host.rs | 89 +++++++++++++--- crates/victory-gpu/src/indirect.rs | 160 +++++++++++++++++++++-------- crates/victory-gpu/src/twin.rs | 52 ++++++++++ 5 files changed, 255 insertions(+), 76 deletions(-) diff --git a/crates/victory-gpu/src/capture.rs b/crates/victory-gpu/src/capture.rs index 88adb536bb..dad1de03e1 100644 --- a/crates/victory-gpu/src/capture.rs +++ b/crates/victory-gpu/src/capture.rs @@ -423,9 +423,9 @@ fn peek(when: &str) { } } -/// In a listed frame: copies an indirect execution's records (`args`: -/// buffer, offset; in the indirect-argument state) and its count (in the -/// unordered-access state unless in the same buffer) to readback memory, +/// In a listed frame: copies an indirect execution's records (`args`: the +/// list's argument buffer and offset, in the indirect-argument state) and +/// its count (a title buffer's copy) to readback memory, /// logged once the list has run: how many records ask for work, and the /// first ones. pub(crate) fn read_indirect( @@ -457,7 +457,6 @@ pub(crate) fn read_indirect( let mut buffer: Option = None; let l = &list.list; use crate::host::transition; - use windows::core::Interface; let (arg_state, copy) = (D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COPY_SOURCE); // SAFETY: plain creation; an open list and live buffers in the states // named, put back after the copies. @@ -473,15 +472,8 @@ pub(crate) fn read_indirect( l.ResourceBarrier(&[transition(args.0, arg_state, copy)]); l.CopyBufferRegion(&buffer, 0, args.0, args.1, len); if let Some((c, at)) = count { - let same = c.as_raw() == args.0.as_raw(); - let state = if same { copy } else { D3D12_RESOURCE_STATE_UNORDERED_ACCESS }; - if !same { - l.ResourceBarrier(&[transition(c, state, copy)]); - } + // A title buffer's copy: never transitioned, the read promotes it. l.CopyBufferRegion(&buffer, len, c, at, 4); - if !same { - l.ResourceBarrier(&[transition(c, copy, state)]); - } } l.ResourceBarrier(&[transition(args.0, copy, arg_state)]); list.keep(&buffer); diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 4a3aa3840b..c5e5840563 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -1695,10 +1695,10 @@ impl State { s.refresh(list, *at, 4); } // Bounded first: the clamp binds a compute pipeline of its own. - if !crate::indirect::bound(list, &args.buffer, args.gpu(arguments), (kind, stride, max)) { + let Some(clamped) = crate::indirect::bound(list, args.gpu(arguments), (kind, stride, max)) else { why("not bounded (no clamp, or arguments not 4-byte aligned)"); return false; - } + }; self.host_pipeline = 0; self.host_roots[1] = 0; let ran = match kind { @@ -1716,7 +1716,7 @@ impl State { _ => false, }; if !ran { - crate::indirect::done(list, &args.buffer); + crate::indirect::done(list, &clamped); #[cfg(feature = "diagnostics")] match crate::pipeline::host_pipeline(self.pipeline as This) { None => { @@ -1742,8 +1742,8 @@ impl State { list.list.ExecuteIndirect( &signature, max, - &args.buffer, - args.offset(arguments), + &clamped, + 0, counter.as_ref().map(|(s, _)| &s.buffer), counter.as_ref().map_or(0, |(s, at)| s.offset(*at)), ) @@ -1757,10 +1757,10 @@ impl State { if always || crate::capture::dump_on() { let count = counter.as_ref().map(|(s, at)| (&s.buffer, s.offset(*at))); let name = crate::pipeline::shaders_of(pipeline); - crate::capture::read_indirect(list, (&args.buffer, args.offset(arguments)), count, (kind, stride, max), name, always); + crate::capture::read_indirect(list, (&clamped, 0), count, (kind, stride, max), name, always); } } - crate::indirect::done(list, &args.buffer); + crate::indirect::done(list, &clamped); if kind == DISPATCH { DISPATCHED.fetch_add(1, Ordering::Relaxed); } else { diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 3e2039e0bf..17852d82ea 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -369,7 +369,34 @@ pub(crate) fn video_memory() -> Option<[(f64, f64); 2]> { } #[cfg(test)] -mod tests { +pub(crate) mod tests { + thread_local! { + /// Every transition barrier built on this thread (resource, before, + /// after), in order. + pub(crate) static ISSUED: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; + } + + /// The barriers built on this thread since the last call. + pub(crate) fn issued() -> Vec<(usize, u32, u32)> { + ISSUED.with(|l| std::mem::take(&mut *l.borrow_mut())) + } + + /// Replays transitions in the order the GPU runs them from the states + /// in `states` (resources not in it are not checked), by the debug + /// layer's rule: each barrier's before-state is the resource's current + /// one. The first that is not, else the states after. + pub(crate) fn replay(issued: &[(usize, u32, u32)], states: &mut std::collections::HashMap) -> Result<(), String> { + for (k, &(resource, before, after)) in issued.iter().enumerate() { + if let Some(state) = states.get_mut(&resource) { + if *state != before { + return Err(format!("barrier {k} on {resource:#x}: before {before:#x}, but the resource is in {state:#x}")); + } + *state = after; + } + } + Ok(()) + } + #[test] fn swap_chain_failures_retry_once_per_second_and_success_clears_the_wait() { use super::{Duration, Instant, SwapChainRetry}; @@ -772,6 +799,9 @@ pub(crate) struct HostList { /// The work its indirect executions may still do (`indirect`): a /// shader-writable word, zeroed when the list is submitted. budget: OnceLock>, + /// Clamped indirect arguments (`crate::indirect`), reused by each + /// execution in turn; replaced by a bigger one when too small. + arguments: Mutex>, /// The texts of the markers `note_op` set, in order (for device-removed /// data without marker texts), with the host GPU range a copy reads. #[cfg(feature = "diagnostics")] @@ -1082,6 +1112,7 @@ impl Host { pipelines: Mutex::default(), id, budget: OnceLock::new(), + arguments: Mutex::new(None), #[cfg(feature = "diagnostics")] notes: Mutex::default(), #[cfg(feature = "diagnostics")] @@ -1866,20 +1897,26 @@ impl HostList { let copies = crate::twin::at_submission(twins.values()); drop(twins); let states = self.states.lock().unwrap_or_else(|e| e.into_inner()); - let barriers: Vec = states - .values() - .filter_map(|(first, last, copy)| { - let real = copy.state.swap(*last, Ordering::Relaxed); - (real != *first).then(|| { - transition( - ©.texture, - D3D12_RESOURCE_STATES(real as i32), - D3D12_RESOURCE_STATES(*first as i32), - ) + // The copies start from the real states, then the list's moves from + // them; only after both do they become the states the list leaves. + let moves = || -> Vec { + states + .values() + .filter_map(|(first, _, copy)| { + let real = copy.state.load(Ordering::Relaxed); + (real != *first).then(|| { + transition(©.texture, D3D12_RESOURCE_STATES(real as i32), D3D12_RESOURCE_STATES(*first as i32)) + }) }) - }) - .collect(); - if barriers.is_empty() && copies.is_empty() { + .collect() + }; + let left = || { + for (_, last, copy) in states.values() { + copy.state.store(*last, Ordering::Relaxed); + } + }; + if copies.is_empty() && states.values().all(|(first, _, copy)| copy.state.load(Ordering::Relaxed) == *first) { + left(); return None; } let (allocator, list) = &self.prelude; @@ -1896,24 +1933,27 @@ impl HostList { let real = t.state.load(Ordering::Relaxed); let wanted = legal_state(&t.texture, wanted); (real != wanted).then(|| { + let there = transition(&t.texture, D3D12_RESOURCE_STATES(real as i32), D3D12_RESOURCE_STATES(wanted as i32)); back.push(transition( &t.texture, D3D12_RESOURCE_STATES(wanted as i32), D3D12_RESOURCE_STATES(real as i32), )); - transition(&t.texture, D3D12_RESOURCE_STATES(real as i32), D3D12_RESOURCE_STATES(wanted as i32)) + there }) }); if !back.is_empty() { list.ResourceBarrier(&back); } } + let barriers = moves(); if !barriers.is_empty() { list.ResourceBarrier(&barriers); } list.Close() }) }; + left(); if let Err(e) = recorded { fail(format_args!("a host state prelude did not record ({e})")); } @@ -2172,6 +2212,23 @@ impl HostList { Some(unsafe { buffer.GetGPUVirtualAddress() }) } + /// The list's argument buffer, at least `bytes` long, common between + /// its uses (`crate::indirect`). + pub(crate) fn arguments(&self, bytes: u64) -> Option { + let mut arguments = self.arguments.lock().unwrap_or_else(|e| e.into_inner()); + // SAFETY: a plain query on a live buffer. + if let Some(b) = arguments.as_ref().filter(|b| unsafe { b.GetDesc() }.Width >= bytes) { + return Some(b.clone()); + } + let (made, _) = host()?.shared_buffer(bytes.next_power_of_two().max(1 << 16))?; + name(&made, || "indirect arguments".into()); + // Commands recorded earlier may still name the smaller one. + if let Some(old) = arguments.replace(made.clone()) { + self.keep(&old); + } + Some(made) + } + /// Keeps `object` alive until the list is reset. pub(crate) fn keep(&self, object: &impl Interface) { if let Ok(object) = object.cast::() { @@ -3333,6 +3390,8 @@ pub(crate) fn transition( before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES, ) -> D3D12_RESOURCE_BARRIER { + #[cfg(test)] + tests::ISSUED.with(|l| l.borrow_mut().push((resource.as_raw() as usize, before.0 as u32, after.0 as u32))); D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index 7cde54b444..0960ed91e1 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -24,16 +24,18 @@ use windows::core::s; use crate::host::{HostList, host, transition}; const SOURCE: &str = r#" -#define RS "RootConstants(num32BitConstants=4, b0), UAV(u0), UAV(u1)" +#define RS "RootConstants(num32BitConstants=4, b0), SRV(t0), UAV(u1), UAV(u0)" cbuffer Record : register(b0) { uint kind; uint stride; uint records; uint unused; }; -RWByteAddressBuffer args : register(u0); +// The title's records, read only; the clamped ones go to the list's own. +ByteAddressBuffer args : register(t0); +RWByteAddressBuffer dest : register(u0); // The list's work so far (vertex instances, threads): past the budget, // records run empty. RWByteAddressBuffer budget : register(u1); static const uint BUDGET = 1u << 27; // Groups of one dispatch; more run empty. static const uint GROUPS = 1u << 20; -// Clamps the record at `at` in place; its cost. +// Clamps the record at `at` into `dest`; its cost. uint clamped(uint at) { uint cost; if (kind <= 1) { @@ -41,7 +43,14 @@ uint clamped(uint at) { uint count = min(args.Load(at), 1u << 24); uint instances = min(args.Load(at + 4), (1u << 26) / max(count, 1u)); cost = count * instances; - args.Store2(at, uint2(count, instances)); + dest.Store2(at, uint2(count, instances)); + // The rest of the record as it is: first vertex and instance (4 words + // in all), or first index, base vertex and first instance (5). + if (kind == 1) { + dest.Store3(at + 8, args.Load3(at + 8)); + } else { + dest.Store2(at + 8, args.Load2(at + 8)); + } } else if (kind == 2) { uint3 g = min(args.Load3(at), uint3(65535, 65535, 65535)); // x * y fits 32 bits; the whole count may not. @@ -49,13 +58,13 @@ uint clamped(uint at) { g = uint3(0, 0, 0); } cost = g.x * g.y * g.z * 64; - args.Store3(at, g); + dest.Store3(at, g); } else { // Mesh dispatches: the console's are one-dimensional. uint3 g = args.Load3(at); g = uint3(min(g.x, 65535u), min(g.y, 1u), min(g.z, 1u)); cost = g.x * g.y * g.z * 128; - args.Store3(at, g); + dest.Store3(at, g); } return cost; } @@ -97,7 +106,7 @@ void main(uint lane : SV_GroupIndex) { GroupMemoryBarrierWithGroupSync(); if (costs[lane] == PAST) { // Draws keep their layout with no vertices; groups become zero. - args.Store(at, 0); + dest.Store(at, 0); } } if (lane == 0) { @@ -177,57 +186,65 @@ fn make() -> windows::core::Result { } /// Records, in `list`, the clamp of `records` records of `kind` (PC -/// argument numbering) `stride` bytes apart at host address `gpu` in -/// `buffer`, and leaves the buffer ready to be read as arguments. Replaces -/// the list's compute root signature and pipeline (callers bind theirs -/// after). False if the clamp is not available. -pub(crate) fn bound( - list: &HostList, - buffer: &ID3D12Resource, - gpu: u64, - (kind, stride, records): (u32, u32, u32), -) -> bool { +/// argument numbering) `stride` bytes apart at host address `gpu` (a title +/// buffer's copy, only read) into the list's own argument buffer, left +/// ready to be read as arguments: that buffer, for [`done`] after the +/// execution. Replaces the list's compute root signature and pipeline +/// (callers bind theirs after). `None` if the clamp is not available. +/// +/// Title buffers' copies are never transitioned: they are common between +/// submissions and every use promotes them (shader and root views, the +/// input assembler, these reads), with unordered-access barriers for order. +/// Only the list's argument buffer moves, common, unordered access, +/// indirect argument, common: its states are known whatever order lists +/// run in. +// shortcut: a buffer a shader writes through an unordered view and the +// input assembler then reads in one submission is, by the letter of D3D12, +// promoted to a write state the input assembler may not use (the debug +// layer cannot see view accesses; GPU-based validation might); upgrade to +// per-list tracked buffer states if a driver or that validation minds. +pub(crate) fn bound(list: &HostList, gpu: u64, (kind, stride, records): (u32, u32, u32)) -> Option { let (Some(c), Some(budget)) = (clamp(), list.budget()) else { - return false; + return None; }; if !gpu.is_multiple_of(4) || !stride.is_multiple_of(4) { - return false; + return None; } + let out = list.arguments(u64::from(stride) * u64::from(records.max(1)))?; let l = &list.list; let constants = [kind, stride, records, 0]; - // SAFETY: an open list; our root signature, pipeline and a live buffer - // the caller's list holds. + // SAFETY: an open list; our root signature, pipeline and buffers, and + // a title buffer's copy the caller's list holds. unsafe { // Earlier shader writes (the title's argument passes) first. - l.ResourceBarrier(&[uav_barrier()]); + l.ResourceBarrier(&[ + uav_barrier(), + transition(&out, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), + ]); l.SetComputeRootSignature(&c.root); l.SetPipelineState(&c.pso); l.SetComputeRoot32BitConstants(0, 4, constants.as_ptr().cast(), 0); - l.SetComputeRootUnorderedAccessView(1, gpu); + l.SetComputeRootShaderResourceView(1, gpu); l.SetComputeRootUnorderedAccessView(2, budget); + l.SetComputeRootUnorderedAccessView(3, out.GetGPUVirtualAddress()); // One group walks every record. l.Dispatch(records.min(1), 1, 1); l.ResourceBarrier(&[ uav_barrier(), - transition( - buffer, - D3D12_RESOURCE_STATE_UNORDERED_ACCESS, - D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, - ), + transition(&out, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT), ]); } - true + Some(out) } -/// After the execution: the buffer back to unordered access, where the -/// title's passes keep using it. -pub(crate) fn done(list: &HostList, buffer: &ID3D12Resource) { +/// After the execution: the list's argument buffer back to common. +pub(crate) fn done(list: &HostList, arguments: &ID3D12Resource) { // SAFETY: an open list and a live buffer. unsafe { list.list.ResourceBarrier(&[transition( - buffer, + arguments, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, - D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COMMON, )]) }; } @@ -254,9 +271,10 @@ mod tests { } /// Clamps `records` records of `kind`, filled by repeating `words`, - /// `calls` times in one list: each record's first word after (zero when - /// it runs empty). One record more follows them and must stay as - /// written. `None` without a host GPU. + /// `calls` times in one list: each record's first word in the list's + /// argument buffer after (zero when it runs empty). The title's copy, + /// one record more included, stays as written. `None` without a host + /// GPU. fn clamped(kind: u32, words: &[u32], records: u32, calls: u32) -> Option> { let host = super::host()?; // Words in a record of `kind`. @@ -277,16 +295,20 @@ mod tests { data.add(at).write_volatile(words[at % words.len()]); } let gpu = buffer.GetGPUVirtualAddress(); + let mut out = None; for _ in 0..calls { - assert!(super::bound(&list, &buffer, gpu, spec)); - super::done(&list, &buffer); + let clamped = super::bound(&list, gpu, spec).unwrap(); + super::done(&list, &clamped); + out = Some(clamped); } list.close(); host.execute(&[&list]); - for at in all - per..all { - assert_eq!(data.add(at).read_volatile(), words[at % words.len()]); + for at in 0..all { + assert_eq!(data.add(at).read_volatile(), words[at % words.len()], "the title's copy as written"); } - let first = |i: usize| data.add(i * per).read_volatile(); + let mut out_data = std::ptr::null_mut(); + out?.Map(0, None, Some(&mut out_data)).unwrap(); + let first = |i: usize| out_data.cast::().add(i * per).read_volatile(); Some((0..records as usize).map(first).collect()) } } @@ -332,6 +354,60 @@ mod tests { assert_eq!(ran, [true, true, false, false, false, false, false, false]); } + /// Two lists clamping into their own argument buffers, run in either + /// order: every barrier starts from the buffer's current state (the + /// debug layer's rule; runs light19 and light21 had the title's GPU + /// heap moved to unordered access under the input assembler), the + /// title's copy is never transitioned, and all end common. + #[test] + fn argument_buffers_move_from_their_current_states() { + use crate::host::tests::{issued, replay}; + use windows::core::Interface; + let Some(host) = super::host() else { + return; // no host GPU here + }; + let (title, data) = host.shared_buffer(1 << 16).unwrap(); + // SAFETY: our mapped buffer; a live buffer. + let gpu = unsafe { + data.cast::<[u32; 3]>().write_volatile([70_000, 1, 1]); + title.GetGPUVirtualAddress() + }; + let key = |r: &super::ID3D12Resource| r.as_raw() as usize; + for a_first in [true, false] { + let lists = [host.new_list().unwrap(), host.new_list().unwrap()]; + issued(); + let recorded: Vec<_> = lists + .iter() + .map(|l| { + let out = super::bound(l, gpu, (2, 12, 1)).unwrap(); + super::done(l, &out); + l.close(); + (out, issued()) + }) + .collect(); + let order = if a_first { [0, 1] } else { [1, 0] }; + host.execute(&[&lists[order[0]], &lists[order[1]]]); + let mut run = issued(); + run.extend(order.iter().flat_map(|&i| recorded[i].1.clone())); + let mut states: std::collections::HashMap = + [key(&title), key(&recorded[0].0), key(&recorded[1].0)].into_iter().map(|k| (k, 0)).collect(); + replay(&run, &mut states).unwrap(); + assert!(run.iter().all(|t| t.0 != key(&title)), "the title's copy is never transitioned"); + assert!(states.values().all(|&s| s == 0), "all common again"); + for (out, _) in &recorded { + let mut p = std::ptr::null_mut(); + // SAFETY: a mapped buffer of ours, the lists have run. + let clamped = unsafe { + out.Map(0, None, Some(&mut p)).unwrap(); + p.cast::<[u32; 3]>().read_volatile() + }; + assert_eq!(clamped, [65_535, 1, 1]); + } + // SAFETY: as above. + assert_eq!(unsafe { data.cast::<[u32; 3]>().read_volatile() }, [70_000, 1, 1], "the title's copy as written"); + } + } + /// The budget is the list's: a second execution of the same records /// finds it spent, and they all run empty. #[test] diff --git a/crates/victory-gpu/src/twin.rs b/crates/victory-gpu/src/twin.rs index 89554ec787..1d5532cb0f 100644 --- a/crates/victory-gpu/src/twin.rs +++ b/crates/victory-gpu/src/twin.rs @@ -565,4 +565,56 @@ mod tests { assert_eq!(again(DEPTH, &mut last, TWIN, true), Some(false)); assert_eq!(last, Some(TWIN)); } + + /// A list that writes a depth texture through its twin and then reads + /// its depth side: its prelude owes a copy into the twin first. Every + /// barrier the prelude and the list issue starts from the state the + /// texture is in, as the debug layer checks (run light21: the prelude's + /// copy started from the states the list leaves). + #[test] + fn prelude_copies_start_from_the_real_states() { + use crate::host::tests::{issued, replay}; + use windows::core::Interface; + let Some(host) = host() else { + return; // no host GPU here + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 64, + Height: 64, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R16_TYPELESS, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, + ..Default::default() + }; + let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + let mut texture: Option = None; + // SAFETY: plain creation; our out pointer. + unsafe { host.device.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_DEPTH_WRITE, None, &mut texture) }.unwrap(); + let depth = Arc::new(HostTexture::new(texture.unwrap(), DEPTH_WRITE, Vec::new())); + let twin = depth.twin.get_or_init(|| make(53, &depth.texture)).as_ref().unwrap(); + let list = host.new_list().unwrap(); + issued(); + assert!(route(&list, &depth, twin, UNORDERED_ACCESS)); + const PIXEL_SHADER_RESOURCE: u32 = 0x80; + assert!(!route(&list, &depth, twin, PIXEL_SHADER_RESOURCE)); + if let Some(b) = list.move_texture(&depth, PIXEL_SHADER_RESOURCE) { + // SAFETY: an open list and a live texture. + unsafe { list.list.ResourceBarrier(&[b]) }; + } + list.close(); + let recorded = issued(); + host.execute(&[&list]); + // The GPU runs the prelude, then the list. + let mut run = issued(); + run.extend(recorded); + let key = |t: &HostTexture| t.texture.as_raw() as usize; + let mut states = std::collections::HashMap::from([(key(&depth), DEPTH_WRITE), (key(&twin.planes[0]), 0)]); + replay(&run, &mut states).unwrap(); + // What the list left is what the next prelude starts from. + assert_eq!(states[&key(&depth)], depth.state.load(Relaxed)); + assert_eq!(states[&key(&twin.planes[0])], twin.planes[0].state.load(Relaxed)); + } } From 54ab40676850007650e71cd147c1bff1d0c4a4de Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 13:08:24 +0100 Subject: [PATCH 80/83] Shaders: descriptors joined by nested control flow, again Brings back PR #1012's recursive heap index (taken back by fbac5bb6): a descriptor every lane shares, chosen by an if/else nested in another, reaches the outer join with an edge that is itself a join; its heap index is a phi at each join of what each predecessor computes at its end. It lets `indirect_diffuse_lighting:CS_ScreenProbes_ActivateRays` (39f0e9aeb156a61c, issued every cutscene frame) through, whose host pipeline the AMD driver could not make before the two commits ahead of this one. The program itself is large: 74,700 GFX10 instructions, 11,896 branches (488 backward), 1,889 typed buffer loads, each after a reload of the same descriptor. Its DXIL, and what the AMD driver (RX 6700 XT, 32.0.21045) does with it: | | #1012 alone | now | |---|---|---| | lines (dxc -dumpbin) | 151,610 | 24,896 | | branches (conditional) | 22,382 (10,040) | 3,070 (1,295) | | blocks | 22,384 | 3,072 | | heap handles | 2,608 | 65 | | size queries | 2,477 | 0 | | phis | 2,883 | 1,124 | | DXIL bytes | 864 K | 144 K | | validator | passes | passes | | host pipeline | over 6 GB at 64 s, never finished (26.7 GB unwatched) | 2.36-2.45 GB, 78-107 s (with other work on the machine) | What remains costly is the program's shape: one loop of 2,941 blocks holding 1,239 of its 1,295 conditional branches, an inner one of 1,440 (the largest loop of the largest program by DXIL bytes, RTShadowTrace32TemporalHQ_OneOver4RPP_Tiled, has 110 blocks; it compiles in 14 s, 353 MB). Making every branch uniform (an experiment) took the compile to 1.9 GB and 54 s, so divergence is not most of it. The pipeline library keeps it after the first make. WARP refuses the pipeline at once (E_INVALIDARG): the program declares the console's wave size (32), which WARP's 4-lane waves cannot run, as for every compute program that declares one. Whole list, translate --list --validate: 0 newly failing, 1 newly emitted and validated (this program). Test: the nested-join lowering test is back (`descriptors_joined_by_nested_control_flow_lower_to_one_uniform_handle`). Co-Authored-By: Claude Opus 5.5 --- crates/victory-shader/src/emit/lower.rs | 117 +++++++++++++++++------- 1 file changed, 83 insertions(+), 34 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 5c483b4e97..2f24f27138 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -5213,43 +5213,39 @@ impl<'a> Lower<'a> { self.s.m.bin(entry, Bin::LShr, addr, shift) } - /// The heap index of a descriptor every lane shares, chosen by control - /// flow: a phi at its join of the index each predecessor computes at its - /// end. - // shortcut: an edge that is itself a join (if/else nested in another) - // stays refused: the one program it would let through, `indirect_ - // diffuse_lighting:CS_ScreenProbes_ActivateRays` (22k branches, 2.6k - // heap handles), takes the AMD driver over 6 GB and a minute to compile - // (PR #1012 did it; take it once pipelines that costly stay off the - // title's pipeline worker). + /// The heap index of a descriptor every lane shares, computed in the + /// current block. One chosen by control flow is a phi at its join of the + /// index each predecessor computes at its end; an edge may bring another + /// join's (nested if/else). fn uniform_heap_index(&mut self, src: &Source, sampler: bool) -> Result { - let Source::Phi { block, args } = src else { - return Err("a descriptor chosen by control flow"); - }; - let mut incoming = Vec::new(); - for (&q, arg) in self.x.p.blocks[*block].preds.iter().zip(args) { - if self.block[q].is_none() { - continue; - } - let (Some(tail), Source::Loaded { load, first }) = (self.tail[q], arg) else { - return Err("a descriptor chosen by control flow"); - }; - let at = self.edges.get(&(q, *block)).copied().unwrap_or(tail); - // No lane comes this way (`resource` gave it another - // edge's source): any index will do. - if self.never_taken(q, *block) { - incoming.push((self.s.m.i32(0), at)); - continue; + match src { + Source::Loaded { load, first } => self.heap_index(*load, *first, sampler), + Source::Phi { block, args } => { + let mut incoming = Vec::new(); + for (&q, arg) in self.x.p.blocks[*block].preds.iter().zip(args) { + if self.block[q].is_none() { + continue; + } + let tail = self.tail[q].ok_or("a descriptor chosen by control flow")?; + let at = self.edges.get(&(q, *block)).copied().unwrap_or(tail); + // No lane comes this way (`resource` gave it another + // edge's source): any index will do. + if self.never_taken(q, *block) { + incoming.push((self.s.m.i32(0), at)); + continue; + } + let here = std::mem::replace(&mut self.cur, at); + let index = self.uniform_heap_index(arg, sampler); + self.cur = here; + incoming.push((index?, at)); + } + let join = self.block[*block].ok_or("a descriptor chosen by control flow")?; + let phi = self.s.m.phi(join, self.s.t.i32); + self.s.m.set_phi(phi, incoming); + Ok(phi) } - let here = std::mem::replace(&mut self.cur, at); - let index = self.heap_index(*load, *first, sampler); - self.cur = here; - incoming.push((index?, at)); + _ => Err("a descriptor chosen by control flow"), } - let join = self.block[*block].ok_or("a descriptor chosen by control flow")?; - let phi = self.s.m.phi(join, self.s.t.i32); - self.s.m.set_phi(phi, incoming); - Ok(phi) } /// The heap index of a descriptor that may differ between lanes, @@ -11022,6 +11018,59 @@ mod tests { } } + #[test] + fn descriptors_joined_by_nested_control_flow_lower_to_one_uniform_handle() { + // The view table at s0 (2D textures at entries 0 and 1, a raw UAV at + // dword 16) and a root constant at s1: entry 0 if s1 is 0, else + // entry 1 if it is 1, else entry 0 again, the inner if/else joined + // before the outer one. The join's edges are a load and a join. + let words = [ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0A02, + 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 + 0xBE88_03FF, + 0x0000_0092, // s_mov_b32 s8, 0x92 (an immediate sampler) + 0xBE89_0380, // s_mov_b32 s9, 0 + 0xBE8A_0380, // s_mov_b32 s10, 0 + 0xBE8B_0380, // s_mov_b32 s11, 0 + 0xBF06_8001, // s_cmp_eq_u32 s1, 0 + 0xBF84_0003, // s_cbranch_scc0 -> 0x38 + 0xF40C_0302, + 0xFA00_0000, // s_load_dwordx8 s[12:19], s[4:5], 0x0 + 0xBF82_0008, // s_branch -> 0x58 + 0xBF06_8101, // 0x38: s_cmp_eq_u32 s1, 1 + 0xBF84_0003, // s_cbranch_scc0 -> 0x4c + 0xF40C_0302, + 0xFA00_0020, // s_load_dwordx8 s[12:19], s[4:5], 0x20 + 0xBF82_0002, // s_branch -> 0x54 + 0xF40C_0302, + 0xFA00_0000, // 0x4c: s_load_dwordx8 s[12:19], s[4:5], 0x0 + 0xBE86_0301, // 0x54: s_mov_b32 s6, s1 + 0x7E04_02F0, // 0x58: v_mov_b32 v2, 0.5 + 0x7E06_02F0, // v_mov_b32 v3, 0.5 + 0x3420_0082, // v_lshlrev_b32 v16, 2, v0 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xF09C_0F08, + 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xE070_1000, + 0x800A_0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen + S_ENDPGM, + ]; + let (_, mut used) = texture_and_uav_tables(); + used.retain(|u| u.user_data == 0); + let layout = vec![root(RootType::Table, 0, 0), root(RootType::Constants, 1, 1)]; + let l = lower_with(&words, layout, used).unwrap(); + // One image handle from the joins' heap index, the same in all lanes. + assert_eq!(l.nonuniform_handles, 0); + if let Ok(mut v) = super::super::validator::Validator::load( + super::super::validator::Validator::default_path().as_deref(), + ) { + v.validate(&mut l.dxil.clone()) + .expect("DXIL validation failed"); + } + } + #[test] fn descriptors_reloaded_from_a_root_table_share_one_handle() { // The view table at s0 (2D textures at entries 0 and 1, a raw UAV at From da82e444ec46a162ca779c82d4cf191a69182971 Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 12:31:47 +0100 Subject: [PATCH 81/83] Shader: normalized buffer codes convert to the float nearest their quotient What was wrong: buffer and typed-buffer loads of normalized formats (UNORM, SNORM) converted a code by dividing it on the host. The host's division is not exact. On the RX 6700 XT, 125 of the 256 8-bit codes loaded one ulp high, and 16-bit codes such as 257, 261, ..., 32896 loaded one ulp low; WARP was exact. The console's buffer unit gives the float nearest the exact quotient, and titles rely on it in decisions: Grand Theft Auto VI's mesh programs read a material index from a vertex colour's alpha as `v_mul_legacy_f32 255.0` then `v_cvt_u32_f32`. A quotient one ulp low truncates to the code below (the 16-bit codes above did), so another material is picked. What changed: for formats up to 16 bits per channel the quotient a / (2^n - 1) is worked out from integers: Q = floor(a * 2^32 / d) as a * K plus a correction (none when n divides 32), rounded to 24 bits up exactly when its highest dropped bit is set (the quotient is never exact, so never a tie), and that integer, at most 2^24 and so exact as a float on any host, scaled by a power of two. The reference is the exact quotient rounded to the nearest float, which removes the dependence on how the host rounds a division or converts a large integer (WARP rounds integers above 2^31 otherwise). Signed formats convert their magnitude the same way; their two lowest codes stay -1.0. The 11- and 12-bit widths, whose smallest codes need more bits, are rounded fully in integers. Cost: about 18-21 DXIL operations a channel where the division was 2 (a division by a constant more where n does not divide 32), so a 4-channel 8-bit fetch is about 80 operations instead of about 12. The car body's mesh program grows from 4,616 to 5,103 instructions (+487 for about 23 normalized channels). In the title it is not measurable: in a run of the intro cutscene with this commit (cost2, on the previous main 4015a182), on world windows with no pipelines being made, the frame median was 881 ms and the GPU 349 ms a frame (median 335), against 1,013 and 389 (365) for the same tree without it (s1a). Two runs of one tree have differed by 132 ms of GPU a frame, so the difference is within run-to-run noise. Evidence: tests `normalized_buffer_formats_load_correctly_rounded_quotients` (every 8- and 10-bit code and a 16-bit sample, unsigned and signed, bit-exact on hardware and WARP; it failed on the RX 6700 XT before, at 8-bit code 3) and `normalized_codes_truncate_back_to_themselves` (the title's truncation gives every code back; 16-bit code 257 came back as 256 before). Offline, the integer arithmetic as emitted matches the exact quotient for every code of every width 2 to 16. Co-Authored-By: Claude Opus 5.5 --- crates/victory-shader/src/emit/lower.rs | 173 +++++++++++++++++-- crates/victory-shader/src/emit/valu_tests.rs | 60 +++++++ 2 files changed, 223 insertions(+), 10 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 2f24f27138..d61239cf89 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -4671,10 +4671,7 @@ impl<'a> Lower<'a> { /// typed loads do (channels past the format's read 0, 0, 0, 1). // shortcut: the descriptor's channel swizzle is taken as the identity // (it is for raw views and the descriptors code builds), elements of 4 - // bytes or more as dword-aligned. Norm formats divide, which the AMD - // driver does 1 ULP off the hardware's correctly rounded conversion for - // some values; correct it with an integer check if a title compares - // converted values exactly. + // bytes or more as dword-aligned. fn format_load(&mut self, h: V, off: V, format: u8, channels: u32) -> Result, Why> { let (bits, numeric) = buffer_format(format).ok_or("a buffer format")?; let c = self.cur; @@ -4737,10 +4734,15 @@ impl<'a> Lower<'a> { // 4 loaded 16_16_UNORM's 65535 as the half 0x3BFF, not 0x3C00. let x = match numeric { Numeric::Unorm => { - let f = self.s.m.cast(c, Cast::UiToFp, field, f32t); let top = (1u64 << w) - 1; - let max = self.s.m.f32((top as f32).to_bits()); - let q = self.s.m.bin(c, Bin::SDiv, f, max); + let q = if w <= 16 { + let q = self.norm_quotient(field, w); + self.as_float(q) + } else { + let f = self.s.m.cast(c, Cast::UiToFp, field, f32t); + let max = self.s.m.f32((top as f32).to_bits()); + self.s.m.bin(c, Bin::SDiv, f, max) + }; let (high, one) = (self.s.m.i32(top as u32), self.s.m.f32(1.0f32.to_bits())); let at_top = self.s.m.cmp(c, pred::EQ, field, high); let q = self.s.m.select(c, at_top, one, q); @@ -4748,10 +4750,23 @@ impl<'a> Lower<'a> { } Numeric::Snorm => { let s = signed(self); - let f = self.s.m.cast(c, Cast::SiToFp, s, f32t); let top = (1u32 << (w - 1)) - 1; - let max = self.s.m.f32((top as f32).to_bits()); - let q = self.s.m.bin(c, Bin::SDiv, f, max); + let q = if w <= 17 { + // The magnitude's quotient, signed (codes at and + // below -top are -1.0 below). + let (zero, sign) = (self.s.m.i32(0), self.s.m.i32(0x8000_0000)); + let neg = self.s.m.cmp(c, pred::SLT, s, zero); + let minus = self.s.m.bin(c, Bin::Sub, zero, s); + let m = self.s.m.select(c, neg, minus, s); + let q = self.norm_quotient(m, w - 1); + let sign = self.s.m.select(c, neg, sign, zero); + let q = self.s.m.bin(c, Bin::Or, q, sign); + self.as_float(q) + } else { + let f = self.s.m.cast(c, Cast::SiToFp, s, f32t); + let max = self.s.m.f32((top as f32).to_bits()); + self.s.m.bin(c, Bin::SDiv, f, max) + }; // The lowest value is -1.0 too, as is the one above it. let (high, one) = (self.s.m.i32(top), self.s.m.f32(1.0f32.to_bits())); let at_top = self.s.m.cmp(c, pred::SGE, s, high); @@ -4801,6 +4816,144 @@ impl<'a> Lower<'a> { Ok(out) } + /// The bits of the float nearest to `a / d`, `d = 2^w - 1`, for codes + /// `0 <= a < d` and `w <= 16`: what the console's buffer unit gives for + /// a normalized code. The host's division is not exact (the RX 6700 XT + /// returns 8-bit codes one ulp high and some 16-bit codes one ulp low), + /// and titles truncate `x * d` back to the code (a material index in a + /// vertex colour's alpha), which a quotient one ulp low turns into the + /// code below. + /// + /// `Q = floor(a * 2^32 / d) = a * K + floor(a * r / d)` with `K = + /// floor(2^32 / d)` and `r = 2^32 mod d` (no division when `r` is 1: + /// widths dividing 32). `a / d` is never exact for `0 < a < d` (`d` + /// odd, `r` coprime to it), so `Q` rounds to 24 bits up exactly when + /// its highest dropped bit is set, and the result is that integer (at + /// most 2^24, so its conversion is exact on any host) scaled by a power + /// of two; `Q` itself when it fits, the quotient's further bits then + /// lying below half an ulp. That holds for every code of every width but + /// 11 and 12 (checked for all codes of widths 2 to 16), which take + /// [`Self::exact_norm`]. The host's conversion of a larger integer is + /// not relied on: WARP rounds those above 2^31 otherwise. + fn norm_quotient(&mut self, a: V, w: u32) -> V { + if matches!(w, 11 | 12) { + return self.exact_norm(a, w); + } + let c = self.cur; + let d = (1u64 << w) - 1; + let (kk, r) = ((1u64 << 32) / d, (1u64 << 32) % d); + let k = |l: &mut Self, v: u64| l.s.m.i32(v as u32); + let (one, kv) = (k(self, 1), k(self, kk)); + let mut q = self.s.m.bin(c, Bin::Mul, a, kv); + if r != 1 { + let (rv, dv) = (k(self, r), k(self, d)); + let t = self.s.m.bin(c, Bin::Mul, a, rv); + let more = self.s.m.bin(c, Bin::UDiv, t, dv); + q = self.s.m.bin(c, Bin::Add, q, more); + } + // The bits to drop (1 to 8) from the exponent of `q >> 8`, which + // converts exactly (fewer than 25 bits); none when `q` fits. + let k8 = k(self, 8); + let top = self.s.m.bin(c, Bin::LShr, q, k8); + let top = self.s.m.cast(c, Cast::UiToFp, top, self.s.t.f32); + let top = self.as_int(top); + let k23 = k(self, 23); + let e = self.s.m.bin(c, Bin::LShr, top, k23); + let bias = k(self, 127 + 15); + let shift = self.s.m.bin(c, Bin::Sub, e, bias); + let (zero, b24) = (k(self, 0), k(self, 1 << 24)); + let fits = self.s.m.cmp(c, pred::IULT, q, b24); + let shift = self.s.m.select(c, fits, zero, shift); + // Rounded up when the highest dropped bit is set: `a / d` is never + // exact, so a dropped half is more than half, never a tie. + let up = self.s.m.bin(c, Bin::Shl, q, one); + let up = self.s.m.bin(c, Bin::LShr, up, shift); + let up = self.s.m.bin(c, Bin::And, up, one); + let m = self.s.m.bin(c, Bin::LShr, q, shift); + let m = self.s.m.bin(c, Bin::Add, m, up); + // At most 2^24: exact as a float, and so its scale by 2^(shift - 32). + let f = self.s.m.cast(c, Cast::UiToFp, m, self.s.t.f32); + let b95 = k(self, 127 - 32); + let scale = self.s.m.bin(c, Bin::Add, shift, b95); + let scale = self.s.m.bin(c, Bin::Shl, scale, k23); + let scale = self.as_float(scale); + let f = self.s.m.bin(c, Bin::Mul, f, scale); + self.as_int(f) + } + + /// [`Self::norm_quotient`] in integers only, for any width up to 16: `Q` + /// as there, 8 more bits when that leaves fewer than 25 (codes of wide + /// formats near 0), then rounded to 24 bits to nearest even with the + /// remainder as sticky bit, and assembled as float bits. + fn exact_norm(&mut self, a: V, w: u32) -> V { + let c = self.cur; + let d = (1u64 << w) - 1; + let (kk, r) = ((1u64 << 32) / d, (1u64 << 32) % d); + let k = |l: &mut Self, v: u64| l.s.m.i32(v as u32); + let (one, zero, dv, k8) = (k(self, 1), k(self, 0), k(self, d), k(self, 8)); + let kv = k(self, kk); + let mut q = self.s.m.bin(c, Bin::Mul, a, kv); + let mut rem = a; + if r != 1 { + let rv = k(self, r); + let t = self.s.m.bin(c, Bin::Mul, a, rv); + let more = self.s.m.bin(c, Bin::UDiv, t, dv); + q = self.s.m.bin(c, Bin::Add, q, more); + rem = self.s.m.bin(c, Bin::URem, t, dv); + } + // The exponent's bias less the 32 (or 40) fraction bits of `q`; the + // shift below is added. + let mut bias = k(self, 127 + 23 - 32); + if kk < 1 << 24 { + // Fewer than 25 bits for the smallest codes: 8 more. + let t = self.s.m.bin(c, Bin::Shl, rem, k8); + let more = self.s.m.bin(c, Bin::UDiv, t, dv); + let rest = self.s.m.bin(c, Bin::URem, t, dv); + let wide = self.s.m.bin(c, Bin::Shl, q, k8); + let wide = self.s.m.bin(c, Bin::Or, wide, more); + let limit = k(self, 1 << 24); + let small = self.s.m.cmp(c, pred::IULT, q, limit); + q = self.s.m.select(c, small, wide, q); + rem = self.s.m.select(c, small, rest, rem); + let b40 = k(self, 127 + 23 - 40); + bias = self.s.m.select(c, small, b40, bias); + } + // Bits to drop: the bit length less 24, 1 to 8. + let mut shift = one; + for bit in 25..32 { + let at = k(self, 1 << bit); + let ge = self.s.m.cmp(c, pred::IUGE, q, at); + let add = self.s.m.select(c, ge, one, zero); + shift = self.s.m.bin(c, Bin::Add, shift, add); + } + let mant = self.s.m.bin(c, Bin::LShr, q, shift); + let below = self.s.m.bin(c, Bin::Sub, shift, one); + let half = self.s.m.bin(c, Bin::LShr, q, below); + let half = self.s.m.bin(c, Bin::And, half, one); + let low = self.s.m.bin(c, Bin::Shl, one, below); + let low = self.s.m.bin(c, Bin::Sub, low, one); + let low = self.s.m.bin(c, Bin::And, q, low); + let rest = self.s.m.bin(c, Bin::Or, low, rem); + let sticky = self.s.m.cmp(c, pred::NE, rest, zero); + let odd = self.s.m.bin(c, Bin::And, mant, one); + let tie = self.s.m.select(c, sticky, one, odd); + let up = self.s.m.bin(c, Bin::And, half, tie); + let mant = self.s.m.bin(c, Bin::Add, mant, up); + // Rounding up to 2^24 moves to the next exponent. + let k24 = k(self, 24); + let carry = self.s.m.bin(c, Bin::LShr, mant, k24); + let mant = self.s.m.bin(c, Bin::LShr, mant, carry); + let e = self.s.m.bin(c, Bin::Add, bias, shift); + let e = self.s.m.bin(c, Bin::Add, e, carry); + let k23 = k(self, 23); + let e = self.s.m.bin(c, Bin::Shl, e, k23); + let fraction = k(self, 0x7F_FFFF); + let m = self.s.m.bin(c, Bin::And, mant, fraction); + let bits = self.s.m.bin(c, Bin::Or, e, m); + let is_zero = self.s.m.cmp(c, pred::EQ, a, zero); + self.s.m.select(c, is_zero, zero, bits) + } + /// Channels of buffer format `format`, as [`Self::format_load`] gives /// them, as d16 data: 16 bits each, two per dword, low half first (an /// odd last high half 0). Integer formats keep their low 16 bits; the diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index 3bf9d6160b..201acdbc63 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -378,6 +378,66 @@ fn normalized_buffer_formats_load_their_ends_exactly() { } } +/// Codes of the normalized formats sampled below: every 8-bit code; for +/// 16 bits a stride, the RX 6700 XT's division misses (257, 261, ...) and +/// the ends. +fn normalized_codes(bits: u32) -> Vec { + if bits <= 10 { + return (0..1 << bits).collect(); + } + let edges = [1, 2, 3, 255, 256, 257, 261, 265, 269, 511, 512, 1000, 0x7FFF, 0x8000, 0x8001, 0xFFFE]; + (0..=0xFFFF).step_by(257).chain(edges).collect() +} + +/// Every normalized code loads as the float nearest its exact quotient, +/// as the console's buffer unit converts it, not as the host divides (the +/// RX 6700 XT gave 125 of the 8-bit codes one ulp high and 16-bit codes +/// such as 257 one ulp low): unsigned and signed, 8, 10 (the x channel of +/// 2_10_10_10) and 16 bits, the signed formats' two lowest codes -1.0. +#[test] +fn normalized_buffer_formats_load_correctly_rounded_quotients() { + let x = 0; + // (format, bits, signed): 8_UNORM, 16_UNORM, 8_SNORM, 16_SNORM, + // 2_10_10_10_UNORM and _SNORM. + for (format, bits, signed) in [(1u8, 8u32, false), (7, 16, false), (2, 8, true), (8, 16, true), (50, 10, false), (51, 10, true)] { + let shader = tbuffer_load_of_v1(x, format); + let cases: Vec<[u32; 4]> = normalized_codes(bits).iter().map(|&a| [a, 0, 0, 0]).collect(); + run_cases(&shader, &cases, |backend, _, [a, ..], got| { + let want = if signed { + let top = (1i32 << (bits - 1)) - 1; + let s = ((a << (32 - bits)) as i32) >> (32 - bits); + (s.max(-top) as f32 / top as f32).to_bits() + } else { + (a as f32 / ((1u32 << bits) - 1) as f32).to_bits() + }; + let sign = if signed { "signed" } else { "unsigned" }; + assert_eq!(got, want, "{backend}: {bits}-bit {sign} normalized {a:#x} loads as {got:#010x}, want {want:#010x}"); + }); + } +} + +/// A title truncates `x * (2^n - 1)` back to the code it stored (the +/// material index a mesh program reads from a vertex colour's alpha, as +/// `v_mul_legacy_f32` by 255.0 then `v_cvt_u32_f32`): every code comes back +/// as itself, on hardware and WARP, which a quotient one ulp low breaks. +#[test] +fn normalized_codes_truncate_back_to_themselves() { + let x = 0; + for (format, bits) in [(1u8, 8u32), (7, 16)] { + let scale = (((1u32 << bits) - 1) as f32).to_bits(); + let mut body = buffer_store_dword(1, 8, 0).to_vec(); + body.extend(mtbuf(x, 0, 8, format)); + // v_mul_legacy_f32 v0, literal, v0; v_cvt_u32_f32 v0, v0. + body.extend([0x07 << 25 | 0xFF, scale]); + body.push(vop1(0x07, 0, vgpr(0))); + let shader = build_valu_cs(&body); + let cases: Vec<[u32; 4]> = normalized_codes(bits).iter().map(|&a| [a, 0, 0, 0]).collect(); + run_cases(&shader, &cases, |backend, _, [a, ..], got| { + assert_eq!(got, a, "{backend}: {bits}-bit code {a} comes back as {got}"); + }); + } +} + #[test] fn packed_add_selects_halves_of_inline_constants() { // Add the inline constant 1/(2*pi) to v1 (zero) to read back its two halves. From 67e8ae1401df112248aed36d0024483181b718b7 Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 16:46:21 +0100 Subject: [PATCH 82/83] Shader tests: the compute harness zeroes its UAVs A new committed resource is not always zeroed: on the CI's WARP the 512 KiB mark buffer of heap_direct_texture_reads_mark_their_heap_index came back holding the page table an earlier test had uploaded and freed, so the test saw 16,389 bits besides the one the shader set. Buffers, root UAVs and UAV textures are now made as copy destinations and get zeros from an upload buffer before the dispatch. Co-Authored-By: Claude Fable 5.2 --- crates/victory-shader/src/emit/host.rs | 39 ++++++++++++++++++++++---- 1 file changed, 34 insertions(+), 5 deletions(-) diff --git a/crates/victory-shader/src/emit/host.rs b/crates/victory-shader/src/emit/host.rs index 856eb87bb2..3cf40653c1 100644 --- a/crates/victory-shader/src/emit/host.rs +++ b/crates/victory-shader/src/emit/host.rs @@ -1433,6 +1433,32 @@ impl Host { b.Unmap(0, None); Ok(b) }; + // Zeros a UAV made as a copy destination (`size`: a texture's, + // `n` its words per texel, else a buffer's dwords) and returns + // the upload buffer to keep. A new committed resource is not + // always zeroed: WARP hands out memory a freed buffer of ours held. + let zero = |r: &ID3D12Resource, size: Option<(u32, u32)>, n: u32| { + let zeros = match size { + Some((w, h)) => { + let pitch = (w * 4 * n).next_multiple_of(256); + let zeros = upload(&vec![0; (pitch * h / 4) as usize])?; + let from = footprint_as(&zeros, w, h, n); + list.CopyTextureRegion(&subresource(r), 0, 0, 0, &from, None); + zeros + } + None => { + let zeros = upload(&vec![0; n as usize])?; + list.CopyBufferRegion(r, 0, &zeros, 0, u64::from(n) * 4); + zeros + } + }; + list.ResourceBarrier(&[transition( + r, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + )]); + Ok::<_, String>(zeros) + }; let slots = match d.views.last() { Some(View::NullBuffers) => super::HEAP_VIEWS as usize, _ => d.views.len(), @@ -1595,7 +1621,7 @@ impl Host { let b = make( D3D12_HEAP_TYPE_DEFAULT, &buffer(bytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS), - D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_COPY_DEST, )?; let desc = D3D12_UNORDERED_ACCESS_VIEW_DESC { Format: format, @@ -1609,6 +1635,7 @@ impl Host { }, }; dev.CreateUnorderedAccessView(&b, None, Some(&desc), at); + keep.push(zero(&b, None, n)?); let rb = make( D3D12_HEAP_TYPE_READBACK, &buffer(bytes, D3D12_RESOURCE_FLAG_NONE), @@ -1620,9 +1647,10 @@ impl Host { let t = make( D3D12_HEAP_TYPE_DEFAULT, &texture(w, h, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS), - D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COPY_DEST, )?; dev.CreateUnorderedAccessView(&t, None, None, at); + keep.push(zero(&t, Some((w, h)), 4)?); let pitch = (w * 16).next_multiple_of(256); let rb = make( D3D12_HEAP_TYPE_READBACK, @@ -1639,9 +1667,10 @@ impl Host { let t = make( D3D12_HEAP_TYPE_DEFAULT, &texture_as(w, h, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, format), - D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COPY_DEST, )?; dev.CreateUnorderedAccessView(&t, None, None, at); + keep.push(zero(&t, Some((w, h)), words)?); let pitch = (w * 4 * words).next_multiple_of(256); let rb = make( D3D12_HEAP_TYPE_READBACK, @@ -1839,9 +1868,10 @@ impl Host { let b = make( D3D12_HEAP_TYPE_DEFAULT, &buffer(bytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS), - D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_COPY_DEST, )?; list.SetComputeRootUnorderedAccessView(*param, b.GetGPUVirtualAddress()); + keep.push(zero(&b, None, n)?); let rb = make( D3D12_HEAP_TYPE_READBACK, &buffer(bytes, D3D12_RESOURCE_FLAG_NONE), @@ -1854,7 +1884,6 @@ impl Host { let [x, y, z] = d.groups; list.Dispatch(x, y, z); for (r, size, n, rb) in &uavs { - // (Buffers were promoted from the common state by the dispatch.) list.ResourceBarrier(&[transition( r, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, From 5b602d8ed342367e95beed9489505201566e015e Mon Sep 17 00:00:00 2001 From: openhands Date: Wed, 25 Nov 2026 16:38:27 +0000 Subject: [PATCH 83/83] AGENTS.md: record the second upstream sync's conflict resolutions --- AGENTS.md | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index 575c2d6bd1..42957cfeef 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -53,7 +53,7 @@ Fork: MagiccConch/VIctory, upstream: Marvisak/VIctory. CI: windows-latest only ( - Title run (2026-11-25 ~02:17): title boots deep into init on the 5080, then 0xc0000005 null write (title-image+0x2215c35) amid a flood of "title slot past the host heap index~1179606 count=934464 for_draw=false" (also the title's own Breakpad minidump upload attempt, blocked by net HLE - benign). Root cause: the title requests 0x120000 (1179648) shader-visible slots; HostHeap::new fallback jumped from make(max(count+DYNAMIC, HEAP_VIEWS)=2M) straight to the 1M cap (PORTABLE_VIEWS, NVIDIA), leaving count=934464 and every title slot past it null. Commit 6ac8fbe (CI 45532159717 green): ordered fallbacks - try make(count+DYNAMIC) then make(count+MIN_DYNAMIC) before the PORTABLE_VIEWS cap, so the full console heap fits when the host allows ~1.245M. If the 5080 still caps (log shows host view heap capped at 1000000), real remapping is needed (upstream comment: a title that reaches them needs remapping). Breakpad line = the title's own crash reporter trying submit.backtrace.io, net-blocked, harmless. - Remap sketch (for the 2-heap fix): uniform root layout on ALL hosts - two root SRVs (heap0=title slots [0, 1000000), heap1=title slots [1000000, 1179648) + the DYNAMIC tail) with SPLIT=1000000 fixed in emit (HEAP_VIEWS clamp stays; NULL_BUFFER_VIEW lands in heap0). Heap0 exactly 1000000 slots (NVIDIA max, empirically confirmed), heap1 sized per host. Root signature changes -> pipeline library rebuilds (user re-runs pre-build). Update: emit/shader.rs, pipeline/make.rs root layout, descriptor/host.rs heap manager + GPU_RANGES. -## Upstream sync (2026-11-24/25, merge 42b5c9c) +## Upstream sync (2026-11-24/25, merge 42b5c9c; second sync 971a975 → 67e8ae1 via PR #14) - Reviewed upstream's 291 commits since 70564ae, checked upstream CI (green), merged, resolved 5 conflict files, CI 45536238395 green on windows-latest. - Key upstream fixes now in the fork: copy-back page marks via shader view writes (cd94d35) — touches `crate::memory` copy-back and `emit::HostShader::view_marks` (new `Parts::view_marks`, `Options::view_marks`, `HostShader::view_marks`; test initializers must set it); descriptor cursor range (c6c244d) + dynamic wraparound scan (c1c3281); swap-chain throttle (f096774); TDR log (42961e8, `crate::tdr::log` — called beside our adapter-by-preference in `victory-gpu/src/host.rs`); device-removed reason (13185f5); no-GPU skip for hardware-only shader checks (42363ab/ccfb029: `hardware_adapter` requires DedicatedVideoMemory > 0). @@ -129,3 +129,16 @@ Fork: MagiccConch/VIctory, upstream: Marvisak/VIctory. CI: windows-latest only ( - **#911 ported (same commit):** `tables()` now rolls back the failing stage's just-allocated ranges on `table_failed` — release(first, n), fresh_tables entry removed, self.dynamic entry dropped, made cleared. Safe because those binds were never recorded (the draw drops before its root arguments are set); later draws re-make them. Previous behavior cached them until list reset, amplifying exhaustion exactly as #911 describes. - NOT ported now: #876/#2190 (typeless views — 494-line unmerged rework; our cutscene/UI symptoms were addressed by the twin work), wave64/compute translation (#2176, large), #2189's tier ladder (our ladder already degrades gracefully with the 2^18 port). Re-check #2177/#2185/#2189/#2190 when upstream merges any — all touch descriptor/host.rs + emit/lower.rs, which PR #13 now modifies; expect rebase work then. - Run 8 expectations UPDATED by 3bf9424: capped warn now logs `kept=705085`; `host view heap capped at 1000000` count=934464. The past-cap title range widens (title slots [705,085, 1,179,648) read null) — that is #747's accepted trade (its own tested config mirrored only 672,319 title slots). Watch for "no dynamic slots" drops GONE from the log (was thousands/frame in #747's measurements). + +## Second upstream sync (971a975, PR #14, upstream 67e8ae1; 2026-11-25) + +- Scope: upstream commits 940d32f..67e8ae1 (58 commits). Key fixes: 315cea1 barriers start from the states resources are in (prelude copies from real states; indirect clamp writes clamped records into a list-owned argument buffer - addresses run-9's id=538 vertex-buffer-in-UAV class); 98c654b 16-bit depth w/ stencil is host D32_FLOAT_S8X24 (depth() = f32(u)*0x37800080 - EQUAL-tested depth now exact on AMD/any-float-depth); 4015a18 quad reads reach helpers at edges (helpers at triangle edges exist regardless of discards); 8f2a6f1 texture refresh per-subresource spans + thread-local staging (Buffers reuse); a1a2077 vertex/mesh UAV flag declaration (the 5,046 "Flags must match usage" programs); da82e44/67e8ae1 buffer codes + compute-harness UAV zeroing. +- Conflict resolutions (7 files): + - texture.rs: took UPSTREAM wholesale - the fork's PR #9 splitmix digest (527c237) is superseded by upstream's per-subresource spans + blake3 + Buffers. Do not re-merge digest() by hand. + - twin.rs: kept BOTH - upstream's float depth (depth()/u16()) AND the fork's packed-colour modes 1-3 (up()/down(), B5G6R5/B5G5R5A1/B4G4R4A4 twins from b3a8b22). Doc comment merged. + - emit/shader.rs: tests mod is upstream's #[cfg(all(test, windows))]; kept BOTH fork's heap_handles_stay_inside_the_host_limits AND upstream's uavs_outside_pixel_and_compute_programs_are_declared. + - emit/lower.rs: Parts keeps BOTH heap_props (fork) and heap_handles (upstream, via m.written_calls); dropped the FORK's older helpers_read (quad && pixel && !discards.is_empty()) - upstream's 4015a18 (quad && pixel) is the corrected semantics (helpers at edges regardless of discard). Same dedupe trap as helper_reads_own in 42b5c9c. + - draw.rs/list.rs: fork's twin-redirect plumbing (format-patched tuple desc/view) wins over upstream's plain record.desc() line - the conflict sat INSIDE the fork's rewritten set_targets/clear_rtv. + - host.rs: kept by_preference (fork) + process_memory (upstream diagnostics). +- NOTE: CI does not run on non-main branch pushes (workflow triggers: pull_request, push to main only). Get a run by opening a PR. Run 45655729340 = PR #14. +- Local loader test failures (file_name_is_stable_per_build, patches_own_test_binary, keeps_iat_slots_...) are Linux-exe artifacts (tests parse current_exe() as PE, ELF gives "Unknown file magic"); Windows CI tests them. Not merge-related.