From e837b604fe69686fe52a7a7367101eacd82b158c Mon Sep 17 00:00:00 2001 From: CocoBeans64 Date: Wed, 25 Nov 2026 23:39:41 +0100 Subject: [PATCH 1/5] GPU: release title-buffer copies off the submission thread A profile of the prologue's world (xperf, context switches and ready events) shows the title's recording threads and the submission thread (queue::pump -> Host::execute) taking turns: the submission thread runs alone at ~100 % of a core for ~400 ms a frame while everything else waits, so it is the frame's critical path. 17 % of its time was the driver freeing the memory of host copies gone (memory::Shared::rewrite dropping the old page table's last references -> ID3D12Resource release -> amdxc64). - `Shadow::buffer` is released by a thread of its own (`release_later`). A copy goes only once no submission holds it, and D3D12 objects are free-threaded. - `shadow::BUFFERS` becomes a read-write lock: `find` looks buffers up shared and writes only to make a first copy. The title's five recording threads woke each other ~2,400 times a second on the mutex (no gain of its own, measured). Bench (Series X, FSR 0.5, BVH builder skipped, 300 s of the prologue on an RX 6800 XT / Ryzen 7 7800X3D, Windows 10 + Agility SDK): mean frame 647 ms against 705-759 ms over four reference runs, 1.69 fps mean (1.41-1.56). victory-gpu shadow tests pass. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor/host.rs | 8 +-- crates/victory-gpu/src/draw.rs | 4 +- crates/victory-gpu/src/shadow.rs | 64 ++++++++++++++++++++--- 3 files changed, 64 insertions(+), 12 deletions(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 74e4bf550c..fdd90e9f76 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -1254,9 +1254,9 @@ fn buffer_srv( // SAFETY: a live buffer and a slot of our heap. unsafe { host.device - .CreateShaderResourceView(&shadow.buffer, Some(&desc), at) + .CreateShaderResourceView(&*shadow.buffer, Some(&desc), at) }; - Some(Some((shadow.buffer.clone(), own.then_some(shadow)))) + Some(Some(((*shadow.buffer).clone(), own.then_some(shadow)))) } /// Whether `count` elements of `element` bytes from element `first` lie in @@ -1314,10 +1314,10 @@ fn buffer_uav( // SAFETY: a live buffer and a slot of our heap. unsafe { host.device - .CreateUnorderedAccessView(&shadow.buffer, None::<&ID3D12Resource>, Some(&desc), at) + .CreateUnorderedAccessView(&*shadow.buffer, None::<&ID3D12Resource>, Some(&desc), at) }; MARK.with(|m| m.set(shadow.mark_entry(start))); - Some(Some((shadow.buffer.clone(), own.then_some(shadow)))) + Some(Some(((*shadow.buffer).clone(), own.then_some(shadow)))) } thread_local! { diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index c44f0369a8..4c84562872 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -1813,7 +1813,7 @@ impl State { max, &clamped, 0, - counter.as_ref().map(|(s, _)| &s.buffer), + counter.as_ref().map(|(s, _)| &*s.buffer), counter.as_ref().map_or(0, |(s, at)| s.offset(*at)), ) }; @@ -1824,7 +1824,7 @@ impl State { 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 count = counter.as_ref().map(|(s, at)| (&*s.buffer, s.offset(*at))); let name = crate::pipeline::shaders_of(pipeline); crate::capture::read_indirect(list, (&clamped, 0), count, (kind, stride, max), name, always); } diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index a455a965ea..9a67727ffb 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -65,7 +65,8 @@ fn writeback_merge_matches_bytewise_oracle() { /// A title buffer's host copy. pub(crate) struct Shadow { - pub(crate) buffer: ID3D12Resource, + /// Released by [`release_later`] when the copy goes. + pub(crate) buffer: std::mem::ManuallyDrop, data: *mut u8, gpu: u64, /// Where the title buffer starts and how long it is. @@ -253,7 +254,7 @@ impl Shadow { 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, + buffer: std::mem::ManuallyDrop::new(buffer), data, gpu, start, @@ -693,6 +694,8 @@ impl Shadow { impl Drop for Shadow { fn drop(&mut self) { + // SAFETY: taken once, here; the field is not used after. + release_later(unsafe { std::mem::ManuallyDrop::take(&mut self.buffer) }); if let Some(slice) = self.slice { arena().give_back(slice); } @@ -704,6 +707,32 @@ impl Drop for Shadow { } } +/// Releases `buffer` on a thread of its own: the driver frees a buffer's +/// memory in the release (up to milliseconds), which the submission thread +/// paid for every copy gone when it rewrote a page table (~17 % of its +/// time, profile cpu-waits). The GPU no longer reads it: a copy goes only +/// once no submission holds it. +fn release_later(buffer: ID3D12Resource) { + struct Sent(#[allow(dead_code)] ID3D12Resource); + // SAFETY: D3D12 objects are free-threaded. + unsafe impl Send for Sent {} + static TX: std::sync::OnceLock>>> = std::sync::OnceLock::new(); + let tx = TX.get_or_init(|| { + let (tx, rx) = std::sync::mpsc::channel::(); + std::thread::Builder::new() + .name("victory buffer release".into()) + .spawn(move || rx.into_iter().for_each(drop)) + .ok() + .map(|_| Mutex::new(tx)) + }); + let buffer = Sent(buffer); + if let Some(tx) = tx + && let Err(e) = tx.lock().unwrap_or_else(|e| e.into_inner()).send(buffer) + { + drop(e.0); + } +} + /// The 64 KiB title pages `[start, start + len)` touches. fn pages(start: u64, len: u64) -> u32 { ((start + len.max(1) - 1) >> 16).saturating_sub(start >> 16) as u32 + 1 @@ -970,10 +999,15 @@ struct Entry { } /// Title buffers by (start address, resource), with their copy once made. -static BUFFERS: Mutex> = Mutex::new(BTreeMap::new()); - -fn buffers() -> std::sync::MutexGuard<'static, BTreeMap<(u64, usize), Entry>> { - BUFFERS.lock().unwrap_or_else(|e| e.into_inner()) +/// A read-write lock: every draw of the title's recording threads looks its +/// buffers up here ([`find`]), almost always finding the copy made, while +/// only a first use, a release or a new buffer writes (one mutex had the +/// recording threads wake each other ~2,400 times a second, profile +/// cpu-waits). +static BUFFERS: std::sync::RwLock> = std::sync::RwLock::new(BTreeMap::new()); + +fn buffers() -> std::sync::RwLockWriteGuard<'static, BTreeMap<(u64, usize), Entry>> { + BUFFERS.write().unwrap_or_else(|e| e.into_inner()) } /// Counts copies made and title buffers released: [`all`] may differ when @@ -1011,6 +1045,24 @@ pub(crate) fn unregister(resource: usize, start: u64) { /// len)`, made on first use. pub(crate) fn find(address: u64, len: u64) -> Option> { let end = address.checked_add(len.max(1))?; + // Shared first: a buffer whose copy is made needs no write. + { + let map = BUFFERS.read().unwrap_or_else(|e| e.into_inner()); + let hit = map + .range(..=(address, usize::MAX)) + .rev() + .take(64) + .find(|(_, e)| e.end >= end) + .map(|(_, e)| e.shadow.clone()); + match hit { + None => { + drop(map); + return loose(address, end); + } + Some(Some(shadow)) => return Some(shadow), + Some(None) => {} + } + } let mut map = buffers(); let key = map .range(..=(address, usize::MAX)) From 39cc5f49bc796a3443c37546862d5424fcc489f3 Mon Sep 17 00:00:00 2001 From: CocoBeans64 Date: Wed, 25 Nov 2026 23:40:25 +0100 Subject: [PATCH 2/5] GPU (diagnostics): what heap syncs look at and make Counters per frame-rate line for `sync_heaps`, to find what its time goes to: - "heap syncs per frame": syncs, mapped pages, slots looked at, slots stale, time reading/comparing records and time making the stale ones. - "stale slots per frame": made null, first made, the same view again (by content), another view; by kind. - "made null per frame": zeroed records, old generations, anything else; time making null slots and views. Each call takes under a microsecond, so this split reads low (truncated to whole us). - "unknown records per frame": records neither zero nor ours: how many repeat their bytes, become ours or zero when read again, look like a GPU address; their most frequent first dwords and a few samples. In the prologue's world (Series X, FSR 0.5) a frame syncs ~19 times and looks at ~590,000 slots, ~34,000 of them stale: 6.7 ms reading, ~36 ms making. ~21,000 of those are made null: ~9,200 zeroed records, ~12,200 "unknown" records that are the title's own data (floats such as 0x3f800000, index lists), which shares the big shader-visible heap's memory with descriptors in turn. Only ~0.5 % are the same view again. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/copystat.rs | 60 +++++++- crates/victory-gpu/src/descriptor.rs | 6 +- crates/victory-gpu/src/descriptor/host.rs | 160 ++++++++++++++++++++++ 3 files changed, 224 insertions(+), 2 deletions(-) diff --git a/crates/victory-gpu/src/copystat.rs b/crates/victory-gpu/src/copystat.rs index 792d942953..a55f4faa30 100644 --- a/crates/victory-gpu/src/copystat.rs +++ b/crates/victory-gpu/src/copystat.rs @@ -104,8 +104,36 @@ pub(crate) enum C { /// Title threads writing a view into a shader-visible heap: time /// waiting for the heaps' lock (held by heap syncs and other writers). MirrorWaitUs, + /// Heap syncs (proposal 2 diagnostics): syncs, mapped pages looked at, + /// slots found stale and made again, time reading and comparing + /// records, time making the stale slots. + SyncCalls, + SyncPages, + SyncStale, + SyncReadUs, + SyncMirrorUs, + /// Stale slots by what the title wrote (step 2a): a record of no + /// current view (made null), a slot never made, the same view as the + /// slot was last made from (by content), another view; and by kind. + StaleNull, + StaleFirst, + StaleSame, + StaleOther, + StaleConstant, + StaleShader, + StaleUnordered, + StalePlaced, + StaleSampler, + /// Slots made null by heap syncs, by record: zeroed (tag 0), our tag + /// with a generation no longer current, anything else; the time + /// making null slots and making views. + NullZero, + NullOld, + NullOther, + NullUs, + ViewUs, } -const COUNTERS: usize = 61; +const COUNTERS: usize = 80; static COUNT: [AtomicU64; COUNTERS] = [const { AtomicU64::new(0) }; COUNTERS]; pub(crate) fn add(c: C, n: u64) { @@ -310,6 +338,36 @@ pub(crate) fn log(frames: f64) { .map(|(line, total, longest)| format!("watch.rs:{line} {:.1} ms (longest {longest:.1})", total / frames)) .collect(); tracing::info!(" guard lock held per frame: {}", held.join(", ")); + tracing::info!( + " heap syncs per frame: {:.1} syncs, {:.0} pages, {:.0} slots looked at, {:.0} stale; reading {:.1} ms, making {:.1} ms", + c[C::SyncCalls as usize], + c[C::SyncPages as usize], + c[C::SyncSlots as usize], + c[C::SyncStale as usize], + ms(c[C::SyncReadUs as usize]), + ms(c[C::SyncMirrorUs as usize]), + ); + tracing::info!( + " stale slots per frame: {:.0} made null, {:.0} first made, {:.0} same view again, {:.0} other view; {:.0} constant, {:.0} shader, {:.0} unordered, {:.0} placed, {:.0} sampler", + c[C::StaleNull as usize], + c[C::StaleFirst as usize], + c[C::StaleSame as usize], + c[C::StaleOther as usize], + c[C::StaleConstant as usize], + c[C::StaleShader as usize], + c[C::StaleUnordered as usize], + c[C::StalePlaced as usize], + c[C::StaleSampler as usize], + ); + tracing::info!( + " made null per frame: {:.0} zeroed records, {:.0} old generations, {:.0} other; making null {:.1} ms, views {:.1} ms", + c[C::NullZero as usize], + c[C::NullOld as usize], + c[C::NullOther as usize], + ms(c[C::NullUs as usize]), + ms(c[C::ViewUs as usize]), + ); + crate::descriptor::host::unknown::log(frames); let mut snapshots: Vec<((u64, u64), u64)> = SNAPSHOTS.lock().unwrap_or_else(|e| e.into_inner()).take().into_iter().flatten().collect(); snapshots.sort_by_key(|&(_, bytes)| std::cmp::Reverse(bytes)); diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 1057d56423..7c62d29c17 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -169,6 +169,8 @@ fn mirror(handle: u64) { pub(crate) fn sync_heaps() { // Held throughout: a heap is not dropped while its slots are made. let heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner()); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::SyncCalls, 1); for &(start, _, at) in heaps.iter() { // SAFETY: registered heaps are live (removed when dropped). let heap = unsafe { &*(at as *const Heap) }; @@ -189,6 +191,8 @@ pub(crate) fn sync_heaps() { } let (first, last) = ((page as u64 - start) / step, (end as u64 - start).div_ceil(step)); #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::SyncPages, 1); + #[cfg(feature = "diagnostics")] crate::copystat::add( crate::copystat::C::SyncSlots, last.min(u64::from(heap.desc.count)).saturating_sub(first), @@ -423,7 +427,7 @@ const DSV_TAG: u32 = u32::from_le_bytes(*b"vDSV"); /// A shader view or sampler as the title described it (descriptions in the /// host's layout, kept as words), for the host to build its own from. -#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub(crate) enum View { /// Constant buffer: GPU address and size. Constant(u64, u32), diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index fdd90e9f76..3e2f09a42a 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -694,6 +694,8 @@ impl HostHeap { /// (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; + #[cfg(feature = "diagnostics")] + let reading = crate::watch::Timed(std::time::Instant::now(), crate::copystat::C::SyncReadUs); // 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(); @@ -710,11 +712,82 @@ impl HostHeap { .map(|(i, _)| i) .collect() }; + #[cfg(feature = "diagnostics")] + { + drop(reading); + crate::copystat::add(crate::copystat::C::SyncStale, stale.len() as u64); + self.classify_stale(&stale, first, &records, start, step); + } + #[cfg(feature = "diagnostics")] + let _making = crate::watch::Timed(std::time::Instant::now(), crate::copystat::C::SyncMirrorUs); for i in stale { + #[cfg(feature = "diagnostics")] + let _one = { + let [tag, v, generation] = records[(i - first) as usize]; + let null = tag != VIEW_TAG || view_at(v, generation).is_none(); + crate::watch::Timed( + std::time::Instant::now(), + if null { crate::copystat::C::NullUs } else { crate::copystat::C::ViewUs }, + ) + }; self.mirror(i, at(i), false); } } + /// Diagnostics (step 2a): what the title wrote in stale slots, against + /// the view each slot was last seen with (a hash of its content). + #[cfg(feature = "diagnostics")] + fn classify_stale(&self, stale: &[u32], first: u32, records: &[[u32; 3]], start: u64, step: u64) { + use crate::copystat::{add, C}; + use std::hash::{Hash, Hasher}; + static LAST: std::sync::Mutex>> = + std::sync::Mutex::new(None); + let mut last = LAST.lock().unwrap_or_else(|e| e.into_inner()); + let last = last.get_or_insert_with(Default::default); + let me = self as *const Self as usize; + for &i in stale { + let [tag, v, generation] = records[(i - first) as usize]; + let view = (tag == VIEW_TAG).then(|| view_at(v, generation)).flatten(); + let Some(view) = view else { + add(C::StaleNull, 1); + add( + match tag { + 0 => C::NullZero, + VIEW_TAG => C::NullOld, + _ => C::NullOther, + }, + 1, + ); + if tag != 0 && tag != VIEW_TAG { + unknown::note(me, i, start + u64::from(i) * step, step); + } + last.remove(&(me, i)); + continue; + }; + add( + match view { + View::Constant(..) => C::StaleConstant, + View::Shader(..) => C::StaleShader, + View::Unordered(..) => C::StaleUnordered, + View::Placed(..) => C::StalePlaced, + _ => C::StaleSampler, + }, + 1, + ); + let mut h = std::collections::hash_map::DefaultHasher::new(); + view.hash(&mut h); + let h = h.finish(); + add( + match last.insert((me, i), h) { + None => C::StaleFirst, + Some(old) if old == h => C::StaleSame, + Some(_) => C::StaleOther, + }, + 1, + ); + } + } + /// 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 @@ -2463,3 +2536,90 @@ mod tests { assert_eq!(host.log_messages(), None); } } + +/// Diagnostics: slots heap syncs made null whose record is neither zero +/// nor ours (step 2a, "other"): what they hold, logged per frame-rate line. +#[cfg(feature = "diagnostics")] +pub(crate) mod unknown { + use std::collections::HashMap; + use std::sync::Mutex; + + #[derive(Default)] + struct State { + /// First dword: count. + tags: HashMap, + /// Per slot (heap, index): hash of its last unknown bytes. + last: HashMap<(usize, u32), u64>, + samples: Vec, + seen: u64, + repeated: u64, + ours_on_reread: u64, + zero_on_reread: u64, + address_like: u64, + address_mapped: u64, + } + static STATE: Mutex> = Mutex::new(None); + + /// Slot `index` of heap `heap` at title address `at` (`step` bytes). + pub(crate) fn note(heap: usize, index: u32, at: u64, step: u64) { + let len = step.min(32) as usize; + let mut bytes = [0u8; 32]; + if !crate::host::read_into(at as *const u8, &mut bytes[..len]) { + return; + } + let dw: Vec = bytes[..len].chunks(4).map(|c| u32::from_le_bytes(c.try_into().unwrap())).collect(); + let mut st = STATE.lock().unwrap_or_else(|e| e.into_inner()); + let st = st.get_or_insert_with(Default::default); + st.seen += 1; + *st.tags.entry(dw[0]).or_default() += 1; + use std::hash::{Hash, Hasher}; + let mut h = std::collections::hash_map::DefaultHasher::new(); + bytes[..len].hash(&mut h); + if st.last.insert((heap, index), h.finish()) == Some(h.finish()) { + st.repeated += 1; + } + // Torn read? What the slot holds now. + match dw[0] { + t if t == super::VIEW_TAG => st.ours_on_reread += 1, + 0 => st.zero_on_reread += 1, + _ => {} + } + // A 48-bit GPU address in dwords 0-1 (AMD buffer/image descriptors). + let address = u64::from(dw[0]) | (u64::from(dw[1] & 0xffff) << 32); + if address > 0x10000 && address & 0xff == 0 { + st.address_like += 1; + if crate::host::read_into(address as *const u8, &mut [0u8; 1]) { + st.address_mapped += 1; + } + } + if st.samples.len() < 24 && st.seen % 97 == 1 { + let hex: Vec = dw.iter().map(|d| format!("{d:08x}")).collect(); + st.samples.push(format!("heap {heap:#x} slot {index} at {at:#x}: {}", hex.join(" "))); + } + } + + pub(crate) fn log(frames: f64) { + let st = { + let mut guard = STATE.lock().unwrap_or_else(|e| e.into_inner()); + let Some(state) = guard.as_mut() else { return }; + let last = std::mem::take(&mut state.last); + std::mem::replace(state, State { last, ..Default::default() }) + }; + let mut tags: Vec<_> = st.tags.into_iter().collect(); + tags.sort_by(|a, b| b.1.cmp(&a.1)); + let tags: Vec = tags.iter().take(10).map(|(t, n)| format!("{t:08x} x{:.0}", *n as f64 / frames)).collect(); + tracing::info!( + " unknown records per frame: {:.0} seen, {:.0} same bytes as last time, now ours {:.0}, now zero {:.0}, address-like {:.0} (mapped {:.0}); first dwords: {}", + st.seen as f64 / frames, + st.repeated as f64 / frames, + st.ours_on_reread as f64 / frames, + st.zero_on_reread as f64 / frames, + st.address_like as f64 / frames, + st.address_mapped as f64 / frames, + tags.join(", ") + ); + for sample in &st.samples { + tracing::info!(" unknown record {sample}"); + } + } +} From 28ea153b7c46d011c84aa1fa53e0428c340e96be Mon Sep 17 00:00:00 2001 From: CocoBeans64 Date: Wed, 25 Nov 2026 23:40:59 +0100 Subject: [PATCH 3/5] translate: name programs by the hash `run` logs; VICTORY_EMIT_ONLY `run` names shaders by the blake3 of the container as the title passes it (its own size), e.g. in VICTORY_GPU_TIMING's "GPU ... ms/frame" lines; `translate --list` named them by file and offset only. Each program's label now starts with that hash (`h<16 hex digits>`), so a costly pipeline in a run can be found in the list (the two costliest compute pipelines of the prologue's world, 51.6 ms/frame, are XboxBvhBuilder.dll's). VICTORY_EMIT_ONLY (comma-separated label substrings) limits VICTORY_EMIT_DUMP to those programs, and dumped files keep the start of the label, where the hash is. Co-Authored-By: Claude Opus 5.5 --- apps/victory/src/translate.rs | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/apps/victory/src/translate.rs b/apps/victory/src/translate.rs index 242ea26261..474430266a 100644 --- a/apps/victory/src/translate.rs +++ b/apps/victory/src/translate.rs @@ -483,10 +483,15 @@ fn translate( t: &mut Tally, checks: &mut Checks, ) { - let example = || format!("{}{}", path.display(), source.label()); let Some(bytes) = source.bytes() else { + let example = || format!("{}{}", path.display(), source.label()); return t.fail("corrupt record".into(), example); }; + // Local diagnostics: the hash `run` names the shader by (the container + // as the title passes it, its own size). + let size = bytes.get(0x18..0x1c).map_or(0, |b| u32::from_le_bytes(b.try_into().expect("4")) as usize); + let run_hash = blake3::hash(&bytes[..size.min(bytes.len())]).to_hex()[..16].to_owned(); + let example = || format!("h{run_hash} {}{}", path.display(), source.label()); t.containers += 1; let Ok(container) = Container::parse(&bytes) else { return t.fail("no DXIL part (SM5 or older)".into(), example); @@ -607,14 +612,16 @@ fn check( if t.list && let Ok(dir) = std::env::var("VICTORY_EMIT_DUMP") { - let name: String = label() + let only = std::env::var("VICTORY_EMIT_ONLY").unwrap_or_default(); + let l = label(); + let wanted = only.is_empty() || only.split(',').any(|h| l.contains(h)); + let name: String = if wanted { l } else { String::new() } .chars() .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' }) .collect(); - let _ = std::fs::write( - format!("{dir}/{}.dxil", &name[name.len().saturating_sub(100)..]), - &shader.dxil, - ); + if !name.is_empty() { + let _ = std::fs::write(format!("{dir}/{}_{:?}.dxil", &name[..name.len().min(100)], shader.stage), &shader.dxil); + } } if let Some((h, stub_ps)) = &checks.host { let made = match shader.stage { From 2295330f9707252dd0d692fbafef69cc2f656379 Mon Sep 17 00:00:00 2001 From: CocoBeans64 Date: Wed, 25 Nov 2026 23:51:40 +0100 Subject: [PATCH 4/5] GPU (diagnostics): sort unknown record tags by key (clippy) Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor/host.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 3e2f09a42a..2055863867 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -2606,7 +2606,7 @@ pub(crate) mod unknown { std::mem::replace(state, State { last, ..Default::default() }) }; let mut tags: Vec<_> = st.tags.into_iter().collect(); - tags.sort_by(|a, b| b.1.cmp(&a.1)); + tags.sort_by_key(|a| std::cmp::Reverse(a.1)); let tags: Vec = tags.iter().take(10).map(|(t, n)| format!("{t:08x} x{:.0}", *n as f64 / frames)).collect(); tracing::info!( " unknown records per frame: {:.0} seen, {:.0} same bytes as last time, now ours {:.0}, now zero {:.0}, address-like {:.0} (mapped {:.0}); first dwords: {}", From adfdbcbeca19d77b048f2464a9a1ba595fd45b0e Mon Sep 17 00:00:00 2001 From: CocoBeans64 Date: Thu, 26 Nov 2026 08:29:06 +0100 Subject: [PATCH 5/5] Revert "GPU: release title-buffer copies off the submission thread" This reverts commit e837b60. On upstream 842b0cb the cost it moved is gone: a profile of the prologue's world (xperf, sampled stacks) shows memory::prepare / Shared::rewrite at 0.09 % of the process, against 17 % of the submission thread on the old base (13f91ca), most likely since #1865 writes the page tables directly. A control run gave 799 ms/frame with the commit and 750 ms/frame without (one run each, noise ~5 %), so it adds a thread and a ManuallyDrop for nothing. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor/host.rs | 8 +-- crates/victory-gpu/src/draw.rs | 4 +- crates/victory-gpu/src/shadow.rs | 64 +++-------------------- 3 files changed, 12 insertions(+), 64 deletions(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 2055863867..9eae5c9273 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -1327,9 +1327,9 @@ fn buffer_srv( // SAFETY: a live buffer and a slot of our heap. unsafe { host.device - .CreateShaderResourceView(&*shadow.buffer, Some(&desc), at) + .CreateShaderResourceView(&shadow.buffer, Some(&desc), at) }; - Some(Some(((*shadow.buffer).clone(), own.then_some(shadow)))) + Some(Some((shadow.buffer.clone(), own.then_some(shadow)))) } /// Whether `count` elements of `element` bytes from element `first` lie in @@ -1387,10 +1387,10 @@ fn buffer_uav( // SAFETY: a live buffer and a slot of our heap. unsafe { host.device - .CreateUnorderedAccessView(&*shadow.buffer, None::<&ID3D12Resource>, Some(&desc), at) + .CreateUnorderedAccessView(&shadow.buffer, None::<&ID3D12Resource>, Some(&desc), at) }; MARK.with(|m| m.set(shadow.mark_entry(start))); - Some(Some(((*shadow.buffer).clone(), own.then_some(shadow)))) + Some(Some((shadow.buffer.clone(), own.then_some(shadow)))) } thread_local! { diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 4c84562872..c44f0369a8 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -1813,7 +1813,7 @@ impl State { max, &clamped, 0, - counter.as_ref().map(|(s, _)| &*s.buffer), + counter.as_ref().map(|(s, _)| &s.buffer), counter.as_ref().map_or(0, |(s, at)| s.offset(*at)), ) }; @@ -1824,7 +1824,7 @@ impl State { 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 count = counter.as_ref().map(|(s, at)| (&s.buffer, s.offset(*at))); let name = crate::pipeline::shaders_of(pipeline); crate::capture::read_indirect(list, (&clamped, 0), count, (kind, stride, max), name, always); } diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 9a67727ffb..a455a965ea 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -65,8 +65,7 @@ fn writeback_merge_matches_bytewise_oracle() { /// A title buffer's host copy. pub(crate) struct Shadow { - /// Released by [`release_later`] when the copy goes. - pub(crate) buffer: std::mem::ManuallyDrop, + pub(crate) buffer: ID3D12Resource, data: *mut u8, gpu: u64, /// Where the title buffer starts and how long it is. @@ -254,7 +253,7 @@ impl Shadow { 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: std::mem::ManuallyDrop::new(buffer), + buffer, data, gpu, start, @@ -694,8 +693,6 @@ impl Shadow { impl Drop for Shadow { fn drop(&mut self) { - // SAFETY: taken once, here; the field is not used after. - release_later(unsafe { std::mem::ManuallyDrop::take(&mut self.buffer) }); if let Some(slice) = self.slice { arena().give_back(slice); } @@ -707,32 +704,6 @@ impl Drop for Shadow { } } -/// Releases `buffer` on a thread of its own: the driver frees a buffer's -/// memory in the release (up to milliseconds), which the submission thread -/// paid for every copy gone when it rewrote a page table (~17 % of its -/// time, profile cpu-waits). The GPU no longer reads it: a copy goes only -/// once no submission holds it. -fn release_later(buffer: ID3D12Resource) { - struct Sent(#[allow(dead_code)] ID3D12Resource); - // SAFETY: D3D12 objects are free-threaded. - unsafe impl Send for Sent {} - static TX: std::sync::OnceLock>>> = std::sync::OnceLock::new(); - let tx = TX.get_or_init(|| { - let (tx, rx) = std::sync::mpsc::channel::(); - std::thread::Builder::new() - .name("victory buffer release".into()) - .spawn(move || rx.into_iter().for_each(drop)) - .ok() - .map(|_| Mutex::new(tx)) - }); - let buffer = Sent(buffer); - if let Some(tx) = tx - && let Err(e) = tx.lock().unwrap_or_else(|e| e.into_inner()).send(buffer) - { - drop(e.0); - } -} - /// The 64 KiB title pages `[start, start + len)` touches. fn pages(start: u64, len: u64) -> u32 { ((start + len.max(1) - 1) >> 16).saturating_sub(start >> 16) as u32 + 1 @@ -999,15 +970,10 @@ struct Entry { } /// Title buffers by (start address, resource), with their copy once made. -/// A read-write lock: every draw of the title's recording threads looks its -/// buffers up here ([`find`]), almost always finding the copy made, while -/// only a first use, a release or a new buffer writes (one mutex had the -/// recording threads wake each other ~2,400 times a second, profile -/// cpu-waits). -static BUFFERS: std::sync::RwLock> = std::sync::RwLock::new(BTreeMap::new()); - -fn buffers() -> std::sync::RwLockWriteGuard<'static, BTreeMap<(u64, usize), Entry>> { - BUFFERS.write().unwrap_or_else(|e| e.into_inner()) +static BUFFERS: Mutex> = Mutex::new(BTreeMap::new()); + +fn buffers() -> std::sync::MutexGuard<'static, BTreeMap<(u64, usize), Entry>> { + BUFFERS.lock().unwrap_or_else(|e| e.into_inner()) } /// Counts copies made and title buffers released: [`all`] may differ when @@ -1045,24 +1011,6 @@ pub(crate) fn unregister(resource: usize, start: u64) { /// len)`, made on first use. pub(crate) fn find(address: u64, len: u64) -> Option> { let end = address.checked_add(len.max(1))?; - // Shared first: a buffer whose copy is made needs no write. - { - let map = BUFFERS.read().unwrap_or_else(|e| e.into_inner()); - let hit = map - .range(..=(address, usize::MAX)) - .rev() - .take(64) - .find(|(_, e)| e.end >= end) - .map(|(_, e)| e.shadow.clone()); - match hit { - None => { - drop(map); - return loose(address, end); - } - Some(Some(shadow)) => return Some(shadow), - Some(None) => {} - } - } let mut map = buffers(); let key = map .range(..=(address, usize::MAX))