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 { 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 74e4bf550c..9eae5c9273 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_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: {}", + 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}"); + } + } +}